code:
for letter in str:
    sys.stdout.write(letter)
    time.sleep(.1)

rawDescription: print slowly in python, (Simulate typing)

description: Print slowly in python, (Simulate typing)


code:
import Bio.PDB as bpdb

s = bpdb.PDBParser().get_structure('temp', '1y26.pdb')

start_res=20
end_res=30
chain_id = 'X'

rawDescription: remove parts from a pdb file using python

description: Remove parts from a pdb file using python


rawDescription: Parameterizing Python's json.loads() object_hook to a Factory Method


code:
from collections import OrderedDict

dic = OrderedDict()

def insert(name):
    current_dic = dic
    current_name = ''
    for name_elem in name.split('::'):
        current_name += ('::' if current_name else '') + name_elem
        if not current_name in current_dic:
            current_dic[current_name] = OrderedDict()
        current_dic = current_dic[current_name]

for group in ["foo", "bar", "foo::fone", "foo::ftwo", "foo::ftwo::ffone"]:
    insert(group)

rawDescription: Recursive sorting function for list in Python


code:
class Item(models.Model):
    parent = models.ForeignKey('self')

rawDescription: Django related key of the same model

description: Django related key of the same model


code:
def on_button(self, event):
    self.button.SetSize(self.sizes.next())
    self.ultimateList._mainWin.ResetLineDimensions(True)
    self.ultimateList._mainWin.RecalculatePositions()

rawDescription: Widget Windows in UltimateListCtrl Won't Resize/Refresh


rawDescription: Count rows that match string and numeric with pandas


code:
from scipy.ndimage import rotate, zoom
from scipy.misc import ascent
from matplotlib import pyplot as plt

img = ascent()

rot = rotate(img, 30, reshape=False)

fig, ax = plt.subplots(1, 2)
ax[0].imshow(img, cmap='gray')
ax[1].imshow(rot, cmap='gray')

rawDescription: Scipy rotate and zoom an image without changing its dimensions


code:
import math
math.copysign(int(d['_int']) ** d['_exp'], d['_sign'] * -1)

rawDescription: Stuck with Number Float format in Python Decimal


code:
import itertools
n = sum(1 for _ in itertools.takewhile(lambda x: x < mx, lst))

rawDescription: Efficient way of counting number of elements smaller (larger) than cutoff in a sorted list


code:
def FlipCoins(num_flips):
    heads_rounds_won = 0
    tails_rounds_won = 0
    tied_rounds = 0
    for i in range(10000):
        heads = 0
        tails = 0
        for j in range(num_flips):
            dice = random.randint(0,1)
            if dice==1: heads += 1
            else: tails += 1
        if heads > tails: heads_rounds_won += 1
        elif heads < tails: tails_rounds_won+= 1
        else: tied_rounds += 1
    return heads_rounds_won, tails_rounds_won, tied_rounds

rawDescription: Python coin-toss

description: Python coin-toss


code:
def redo_range(start, end):
    while start < end:
        start += 1
        redo = (yield start)
        if redo:
            start -= 2

redone_5 = False
r = redo_range(2, 10)
for i in r:
    print(i)
    if i == 5 and not redone_5:
        r.send(True)
        redone_5 = True

rawDescription: How to change for-loop iterator variable in the loop in Python?

description: Change for-loop iterator variable in the loop in Python


code:
s = df['A']
s.index
s.index.values
s.index.get_indexer([('one',1), ('two', 2)])

rawDescription: Series.index versus Series.index.values

description: Series.index versus Series.index.values


code: ''.join(u'\\u{:04X}'.format(ord(c)) for c in su)

rawDescription: Converting a unicode string to see unicode code points


code:
myList=['two','one','three']
'The number {} is larger than {} but smaller than {}.'.format(*myList)

rawDescription: String Formatting Easiest Prettiest

description: String Formatting Easiest Prettiest


code:
def area_of_polygon(points):
    if len(points) == 3:
        return area_of_triangle(points)
    else:
        triangle, polygon = lop_triangle(points)
        return area_of_triangle(triangle) + area_of_polygon(polygon)

rawDescription: Area of a polygon (Recursively using Python)


code: df.loc[df['float_col'] > 5, 'int_col'] = df.loc[df['float_col'] > 5, 'int_col'] * 2

rawDescription: Applying Operation to Pandas column if other column meets criteria


code: number = line[-2:]

rawDescription: extracting data from multiple text files using python

description: Extracting data from multiple text files using python


code: x = os.mkfifo(filename)

rawDescription: python interprocess querying/control

description: Python interprocess querying/control


code:
class myApp(App):
    def build(self):
        self.load_kv("main.kv")
        return ThemeBackground()

rawDescription: Apps in Kivy: get values in kv file

description: Apps in Kivy: get values in kv file


rawDescription: count how many of an object type there are in a list Python

description: Count how many of an object type there are in a list Python


code: "distance(survey_marker, geopoint(35.2, 40.5)) < 100"

rawDescription: Finding all the locations in a given radius using Google App Engine GQL


code:
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import Insert

@compiles(Insert)
def append_string(insert, compiler, **kw):
    s = compiler.visit_insert(insert, **kw)
    if 'append_string' in insert.kwargs:
        return s + " " + insert.kwargs['append_string']
    return s

my_connection.execute(my_table.insert(append_string = 'ON DUPLICATE KEY UPDATE foo=foo'), my_values)

rawDescription: SQLAlchemy ON DUPLICATE KEY UPDATE

description: SQLAlchemy ON DUPLICATE KEY UPDATE


code:
val = StringVar()
val.trace('w', callback)

rawDescription: Python 3 tkinter: check when an entry has the value of a string


code:
for commit in repo_changes(remote_commit):
  if commit.hexsha == local_commit.hexsha:
    return
  authors.append(remote_commit.author.email)

rawDescription: GitPython: get list of remote commits not yet applied


code:
res = [(s, d1[k]) for k, s in list2]
res

rawDescription: Python merge lists by common element

description: Python merge lists by common element


code:
def newArray(num):
    array=[]
    for x in range(num):
        array.append(0)
    return array

def convertToWordArray(string):
    #print(string)
    lMessageLength=len(string)
    #print(lMessageLength)
    lNumberOfWords_temp1=lMessageLength+8
    #print(lNumberOfWords_temp1)
    lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1%64))/64
    #print(lNumberOfWords_temp2)
    lNumberOfWords=int((lNumberOfWords_temp2+1)*16)
    #print(lNumberOfWords)
    lWordArray=newArray(lNumberOfWords-1)
    lBytePosition=0
    lByteCount=0
    while lByteCount<lMessageLength:
        lWordCount=int((lByteCount-(lByteCount%4))/4)
        lBytePosition=(lByteCount%4)*8
        #print(string[int(lByteCount)])
        lWordArray[lWordCount]=(lWordArray[lWordCount]|(ord(string[int(lByteCount)])<<lBytePosition))
        lByteCount+=1
    lWordCount=int((lByteCount-(lByteCount%4))/4)
    lBytePosition=(lByteCount%4)*8
    lWordArray[lWordCount]=lWordArray[lWordCount]|(0x80<<lBytePosition)
    lWordArray[lNumberOfWords-2]=lMessageLength<<3
    lWordArray.append(lMessageLength>>29)
    return lWordArray

def F(x,y,z):
    print(x,y,x)
    return (x & y) | ((~x) & z)
def G(x,y,z):
    return (x & z) | (y & (~z))
def H(x,y,z):
    return x ^ y ^ z
def I(x,y,z):
    return y ^ (x | (~z))
def XX(func, a, b, c, d, x, s, ac):
    res=0
    res=res+a+func(b,c,d)
    res+=x
    res+=ac
    res=res & 0xffffffff
    res=rol(res,s)
    res=res & 0xffffffff
    res+=b
    return res & 0xffffffff
##    return addu(rol(addu(addu(a,q),addu(x,ac)),s),b)
##def FF(a,b,c,d,x,s,ac):
##    return C((b & c)|((~b) & d),a,b,x,s,ac)
##def GG(a,b,c,d,x,s,ac):
##    return C((b & d)|(c & (~d)),a,b,x,s,ac)
##def HH(a,b,c,d,x,s,ac):
##    return C(b ^ c ^ d,a,b,x,s,ac)
##def II(a,b,c,d,x,s,ac):
##    return C(c ^ (b|(~d)),a,b,x,s,ac)
def addu(x,y):
    ls=(x & 0xffffffff)+(y & 0xffffffff)
    return (((x>>16)+(y>>16)+(ls>>16))<<16)|(ls & 0xffffffff)
def rol(v,s):
    return (v<<s)|(v>>(32-s))
def wordToHex(lValue):
    wordToHexValue=''
    wordToHexValue_temp=''
    for lCount in range(4):
        lByte=(lValue>>(lCount*8)) & 255
        wordToHexValue_temp="0"+format(lByte, 'x')
        wordToHexValue=wordToHexValue+wordToHexValue_temp[-2:]
    return wordToHexValue

def md5hash(message):
    x=convertToWordArray(message)
    a=0x67452301
    b=0xEFCDAB89
    c=0x98BADCFE
    d=0x10325476
    xl=len(x)
    j=0
    while j<xl:
        aa=a
        bb=b
        cc=c
        dd=d
        a=XX(F,a,b,c,d, x[j+0], 7,0xD76AA478)
        d=XX(F,d,a,b,c, x[j+1],12,0xE8C7B756)
        c=XX(F,c,d,a,b, x[j+2],17,0x242070DB)
        b=XX(F,b,c,d,a, x[j+3],22,0xC1BDCEEE)
        a=XX(F,a,b,c,d, x[j+4], 7,0xF57C0FAF)
        d=XX(F,d,a,b,c, x[j+5],12,0x4787C62A)
        c=XX(F,c,d,a,b, x[j+6],17,0xA8304613)
        b=XX(F,b,c,d,a, x[j+7],22,0xFD469501)
        a=XX(F,a,b,c,d, x[j+8], 7,0x698098D8)
        d=XX(F,d,a,b,c, x[j+9],12,0x8B44F7AF)
        c=XX(F,c,d,a,b,x[j+10],17,0xFFFF5BB1)
        b=XX(F,b,c,d,a,x[j+11],22,0x895CD7BE)
        a=XX(F,a,b,c,d,x[j+12], 7,0x6B901122)
        d=XX(F,d,a,b,c,x[j+13],12,0xFD987193)
        c=XX(F,c,d,a,b,x[j+14],17,0xA679438E)
        b=XX(F,b,c,d,a,x[j+15],22,0x49B40821)
        a=XX(G,a,b,c,d, x[j+1], 5,0xF61E2562)
        d=XX(G,d,a,b,c, x[j+6], 9,0xC040B340)
        c=XX(G,c,d,a,b,x[j+11],14,0x265E5A51)
        b=XX(G,b,c,d,a, x[j+0],20,0xE9B6C7AA)
        a=XX(G,a,b,c,d, x[j+5], 5,0xD62F105D)
        d=XX(G,d,a,b,c,x[j+10], 9,0x2441453)
        c=XX(G,c,d,a,b,x[j+15],14,0xD8A1E681)
        b=XX(G,b,c,d,a, x[j+4],20,0xE7D3FBC8)
        a=XX(G,a,b,c,d, x[j+9], 5,0x21E1CDE6)
        d=XX(G,d,a,b,c,x[j+14], 9,0xC33707D6)
        c=XX(G,c,d,a,b, x[j+3],14,0xF4D50D87)
        b=XX(G,b,c,d,a, x[j+8],20,0x455A14ED)
        a=XX(G,a,b,c,d,x[j+13], 5,0xA9E3E905)
        d=XX(G,d,a,b,c, x[j+2], 9,0xFCEFA3F8)
        c=XX(G,c,d,a,b, x[j+7],14,0x676F02D9)
        b=XX(G,b,c,d,a,x[j+12],20,0x8D2A4C8A)
        a=XX(H,a,b,c,d, x[j+5], 4,0xFFFA3942)
        d=XX(H,d,a,b,c, x[j+8],11,0x8771F681)
        c=XX(H,c,d,a,b,x[j+11],16,0x6D9D6122)
        b=XX(H,b,c,d,a,x[j+14],23,0xFDE5380C)
        a=XX(H,a,b,c,d, x[j+1], 4,0xA4BEEA44)
        d=XX(H,d,a,b,c, x[j+4],11,0x4BDECFA9)
        c=XX(H,c,d,a,b, x[j+7],16,0xF6BB4B60)
        b=XX(H,b,c,d,a,x[j+10],23,0xBEBFBC70)
        a=XX(H,a,b,c,d,x[j+13], 4,0x289B7EC6)
        d=XX(H,d,a,b,c, x[j+0],11,0xEAA127FA)
        c=XX(H,c,d,a,b, x[j+3],16,0xD4EF3085)
        b=XX(H,b,c,d,a, x[j+6],23,0x4881D05)
        a=XX(H,a,b,c,d, x[j+9], 4,0xD9D4D039)
        d=XX(H,d,a,b,c,x[j+12],11,0xE6DB99E5)
        c=XX(H,c,d,a,b,x[j+15],16,0x1FA27CF8)
        b=XX(H,b,c,d,a, x[j+2],23,0xC4AC5665)
        a=XX(I,a,b,c,d, x[j+0], 6,0xF4292244)
        d=XX(I,d,a,b,c, x[j+7],10,0x432AFF97)
        c=XX(I,c,d,a,b,x[j+14],15,0xAB9423A7)
        b=XX(I,b,c,d,a, x[j+5],21,0xFC93A039)
        a=XX(I,a,b,c,d,x[j+12], 6,0x655B59C3)
        d=XX(I,d,a,b,c, x[j+3],10,0x8F0CCC92)
        c=XX(I,c,d,a,b,x[j+10],15,0xFFEFF47D)
        b=XX(I,b,c,d,a, x[j+1],21,0x85845DD1)
        a=XX(I,a,b,c,d, x[j+8], 6,0x6FA87E4F)
        d=XX(I,d,a,b,c,x[j+15],10,0xFE2CE6E0)
        c=XX(I,c,d,a,b, x[j+6],15,0xA3014314)
        b=XX(I,b,c,d,a,x[j+13],21,0x4E0811A1)
        a=XX(I,a,b,c,d, x[j+4], 6,0xF7537E82)
        d=XX(I,d,a,b,c,x[j+11],10,0xBD3AF235)
        c=XX(I,c,d,a,b, x[j+2],15,0x2AD7D2BB)
        b=XX(I,b,c,d,a, x[j+9],21,0xEB86D391)
        a=addu(a,aa)
        b=addu(b,bb)
        c=addu(c,cc)
        d=addu(d,dd)
        j+=16
    return (wordToHex(a)+wordToHex(b)+wordToHex(c)+wordToHex(d)).lower()

rawDescription: MD5 Python Implementation

description: MD5 Python Implementation


code:
def str_to_number(time_str):
    if not isinstance(time_str, str):
        return 0
    minutes, sec, *_ = [int(x) for x in time_str.split(':')]
    return minutes + sec / 60

rawDescription: Pandas: convert column from minutes (type object) to number


code: number = ''.join([ n for n in number if n.isdigit() ])

rawDescription: How to format a list of phone numbers e.g. 202.202.2020 into (202) 202-2020 using Python?

description: Format a list of phone numbers e.g. 202.202.2020 into (202) 202-2020 using Python


code:
import base64

im_filename = 'background.png'
im_variableName = 'background'
py_filename = 'embeddedImage.py'

with open(im_filename,'rb') as f:
    str64 = base64.b64encode(f.read())

with open(py_filename,'w') as f:
    f.write('%s="%s"'%(im_variable_name,str64))

rawDescription: Include picture data in Python, possible?


code:
import wx
class ExampleFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent)
        baseSizer = wx.BoxSizer(wx.VERTICAL)

        # Create an editable text field
        self.textfield = wx.TextCtrl(self)
        # Attach event handlers to text field
        # Event for when the text changes
        self.Bind(wx.EVT_TEXT, self.OnChange, self.textfield)
        # Event for when a key is pressed, for example an arrow key should fire this event but not the EVT_TEXT event
        self.textfield.Bind(wx.EVT_CHAR, self.OnKeyPress, self.textfield)

        # Create a button that will clear the textfield
        clearButton = wx.Button(self, wx.ID_CLEAR, "Clear")
        # Attach event handler on the clearButton to call OnClear()
        self.Bind(wx.EVT_BUTTON, self.OnClear, clearButton)

        # Multiline text field for seeing the events fire
        self.logger = wx.TextCtrl(self, -1, style= wx.TE_MULTILINE | wx.TE_READONLY )

        # Add items to frame sizer
        baseSizer.Add(self.textfield, 1, flag=wx.EXPAND)
        baseSizer.Add(clearButton,0)
        baseSizer.Add(self.logger, 1, flag=wx.EXPAND)

        # Set sizer for frame
        self.SetSizer(baseSizer)

        # Show
        self.Show()

    def OnClear(self, e):
        # Clear all text entered into the textfield and return focus
        self.textfield.SetValue("")
        self.textfield.SetFocus()
        e.Skip()

    def OnChange(self, e):
        # Log every time this event is fired
        self.logger.AppendText("OnChange: " + e.GetString() + '\n')
        e.Skip()

    def OnKeyPress(self, e):
        # Log every key press in the textfield
        self.logger.AppendText("OnKeyPress: " + str(e.GetKeyCode()) + '\n')
        e.Skip()

app = wx.App(False)
ExampleFrame(None)
app.MainLoop()

rawDescription: Is there a wx.EVT_CHAR or event.GetKeyCode() equivalent for wxPython( Phoenix )?


code: df['new_column'] = df.merge(df_unique, on=['col_a','col_b'], how='left')['new_column']

rawDescription: Pandas, append column based on unique subset of column values


code:
def obsfucate(word):
    new_word = ''
    for char in word:
        if random.random() > 0.1:
            new_word += random.choice(["!", "%", "*", "#", "@"])
        else:
            new_word += char
    return new_word

rawDescription: Python, obfuscating letters in a list

description: Python, obfuscating letters in a list


code:
out = np.zeros(np.max(row_lengths) + nr - 1, a.dtype)

for ii, aa in enumerate(arr_list):
    out[ii:(ii + row_lengths[ii])] += aa

print(out)
# [ 1  4  9 12 10  6]

rawDescription: Adding numpy arrays in specific way

description: Adding numpy arrays in specific way


code: {'key3': 'value with spaces', 'key2': 'value2', 'key1': 'value1'}

rawDescription: Turning string with embedded brackets into a dictionary


code: df = df.dropna()

rawDescription: How can I delete a row in a Pandas dataframe if the entire row is null?

description: Delete a row in a Pandas dataframe if the entire row is null


code:
pd.options.display.max_colwidth = 200
df

rawDescription: Formatting issue in IPython/pandas

description: Formatting issue in IPython/pandas


code: coordinate_row = list(coordinate) + coordinate_row

rawDescription: Add a number to the front of a number row python


code:
class NoSlots(object): pass

n = NoSlots()
class WithSlots(object): __slots__ = 'a', 'b', 'c'

w = WithSlots()
n.a = n.b = n.c = 23
w.a = w.b = w.c = 23
sys.getsizeof(n)
sys.getsizeof(w)

rawDescription: Python: How does inheritance of __slots__ in subclasses actually work?


code: my_objects = [MyClass(0) for _ in xrange(100)]

rawDescription: Creating an array of objects in python without having to append in a loop


rawDescription: Set Tkinter label texts as elements of list


code:
def main(ifilename, ofilename):
    with open(ifilename,'r') as i, open(ofilename,'w') as o:
        for line in i:
            for digit in (0,1,2,3,4,5,6,7,8,9):
                line = line.replace(str(digit), '')
            print(line,file=o,end='')

if __name__ == '__main__':
    from sys import argv
    main(argv[1], argv[2])

rawDescription: How to remove numbers from every list entry

description: Remove numbers from every list entry


rawDescription: Python splitting strings and jumbling the middle


code:
num_cols = lg + 6
for row in data:
    writer.writerow(row[:num_cols])

rawDescription: Python loop to write across columns in CSV


rawDescription: Store Numpy array index in variable

description: Store Numpy array index in variable


code:
def fast_iter(context, func, *args, **kwargs):
    """
    fast_iter is useful if you need to free memory while iterating through a
    very large XML file.

    http://lxml.de/parsing.html#modifying-the-tree
    Based on Liza Daly's fast_iter
    http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
    See also http://effbot.org/zone/element-iterparse.htm
    """
    for event, elem in context:
        func(elem, *args, **kwargs)
        # It's safe to call clear() here because no descendants will be
        # accessed
        elem.clear()
        # Also eliminate now-empty references from the root node to elem
        for ancestor in elem.xpath('ancestor-or-self::*'):
            while ancestor.getprevious() is not None:
                del ancestor.getparent()[0]
    del context

def process_element(elt):
    print(elt.text)

context=etree.iterparse(io.BytesIO(xml), events=('end',), tag='b')
fast_iter(context, process_element)

rawDescription: Efficient way to iterate throught xml elements


rawDescription: Pandas: Grouping DataFrame by hundreds

description: Pandas: Grouping DataFrame by hundreds


code:
areas = np.where(cross_test < 0, areas_neg, areas_pos)
total_area = np.sum(areas)

rawDescription: Find the area between two curves ploted in matplotlib (fill_between area)


code:
data = pd.DataFrame(np.random.randn(3, 2), columns=columns)
data
data.loc[0,'a']
data.loc[1,'a']

rawDescription: How to assign one row of a hierarchically indexed Pandas DataFrame to another row?

description: Assign one row of a hierarchically indexed Pandas DataFrame to another row


code:
import csv
with open('save_file.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerows(zip(*sorted))

rawDescription: Transpose multiple txt data files and import into excel or database


code:
def make_tree(path):
    return [
        make_tree(os.path.join(path, element))
        for element in get_elements(path)]

rawDescription: Is there a way to tell if I'm using recursion in Python?


rawDescription: How to create copies of a python object that are not linked to original object?

description: Create copies of a python object that are not linked to original object


rawDescription: pandas groupby on a values based on n-1 index record

description: Pandas groupby on a values based on n-1 index record


code:
import sys
import re
import csv

colonseperated = re.compile(' *(.+) *: *(.+) *')
fixedfields = re.compile('(\d{3} \w{7}) +(.*)')

matchers = [colonseperated, fixedfields]

outfile = csv.writer(open('out.csv', 'w'))

outfile.writerow(['Filename', 'Key', 'Value'])
for filename in sys.argv[1:]:
    for line in open(filename):
        line = line.strip()
        for matcher in matchers:
            match = matcher.match(line)
            if match:
                outfile.writerow([filename] + list(match.groups()))

rawDescription: Python - Parsing structured text to excel


code:
class Foo(object):
    pass
dir(Foo.__class__)
class Bar():
    pass
dir(Bar.__class__)
dir(Bar)
dir(Foo)

rawDescription: Python new-style classes and __subclasses__ function


code:
import Tkinter, random
class App:
    def __init__(self, t):
        self.i = Tkinter.PhotoImage(width=100,height=100)
        colors = [[random.randint(0,255) for i in range(0,3)] for j in range(0,10000)]
        row = 0; col = 0
        for color in colors:
           self.i.put('#%02x%02x%02x' % tuple(color),(row,col))
           col += 1
           if col == 100:
               row +=1; col = 0
        c = Tkinter.Canvas(t, width=100, height=100); c.pack()
        c.create_image(0, 0, image = self.i, anchor=Tkinter.NW)

t = Tkinter.Tk()
a = App(t)
t.mainloop()

rawDescription: How to draw a bitmap real quick in python using Tk only?

description: Draw a bitmap real quick in python using Tk only


code:
import cv

cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
camera_index = 0
capture = cv.CaptureFromCAM(camera_index)

def repeat():
    global capture #declare as globals since we are assigning to them now
    global camera_index
    frame = cv.QueryFrame(capture)
    cv.ShowImage("w1", frame)
    c = cv.WaitKey(10)
    if(c=="n"): #in "n" key is pressed while the popup window is in focus
        camera_index += 1 #try the next camera index
        capture = cv.CaptureFromCAM(camera_index)
        if not capture: #if the next camera index didn't work, reset to 0.
            camera_index = 0
            capture = cv.CaptureFromCAM(camera_index)

while True:
    repeat()

rawDescription: Displaying a webcam feed using OpenCV and Python


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

def center_spines(ax=None, centerx=0, centery=0):
    """Centers the axis spines at <centerx, centery> on the axis "ax", and
    places arrows at the end of the axis spines."""
    if ax is None:
        ax = plt.gca()

    # Set the axis's spines to be centered at the given point
    # (Setting all 4 spines so that the tick marks go in both directions)
    ax.spines['left'].set_position(('data', centerx))
    ax.spines['bottom'].set_position(('data', centery))
    ax.spines['right'].set_position(('data', centerx - 1))
    ax.spines['top'].set_position(('data', centery - 1))

    # Draw an arrow at the end of the spines
    ax.spines['left'].set_path_effects([EndArrow()])
    ax.spines['bottom'].set_path_effects([EndArrow()])

    # Hide the line (but not ticks) for "extra" spines
    for side in ['right', 'top']:
        ax.spines[side].set_color('none')

    # On both the x and y axes...
    for axis, center in zip([ax.xaxis, ax.yaxis], [centerx, centery]):
        # Turn on minor and major gridlines and ticks
        axis.set_ticks_position('both')
        axis.grid(True, 'major', ls='solid', lw=0.5, color='gray')
        axis.grid(True, 'minor', ls='solid', lw=0.1, color='gray')
        axis.set_minor_locator(mpl.ticker.AutoMinorLocator())

        # Hide the ticklabels at <centerx, centery>
        formatter = CenteredFormatter()
        formatter.center = center
        axis.set_major_formatter(formatter)

    # Add offset ticklabels at <centerx, centery> using annotation
    # (Should probably make these update when the plot is redrawn...)
    xlabel, ylabel = map(formatter.format_data, [centerx, centery])
    ax.annotate('(%s, %s)' % (xlabel, ylabel), (centerx, centery),
            xytext=(-4, -4), textcoords='offset points',
            ha='right', va='top')

# Note: I'm implementing the arrows as a path effect rather than a custom
#       Spines class. In the long run, a custom Spines class would be a better
#       way to go. One of the side effects of this is that the arrows aren't
#       reversed when the axes are reversed!

class EndArrow(mpl.patheffects._Base):
    """A matplotlib patheffect to add arrows at the end of a path."""
    def __init__(self, headwidth=5, headheight=5, facecolor=(0,0,0), **kwargs):
        super(mpl.patheffects._Base, self).__init__()
        self.width, self.height = headwidth, headheight
        self._gc_args = kwargs
        self.facecolor = facecolor

        self.trans = mpl.transforms.Affine2D()

        self.arrowpath = mpl.path.Path(
                np.array([[-0.5, -0.2], [0.0, 0.0], [0.5, -0.2],
                          [0.0, 1.0], [-0.5, -0.2]]),
                np.array([1, 2, 2, 2, 79]))

    def draw_path(self, renderer, gc, tpath, affine, rgbFace):
        scalex = renderer.points_to_pixels(self.width)
        scaley = renderer.points_to_pixels(self.height)

        x0, y0 = tpath.vertices[-1]
        dx, dy = tpath.vertices[-1] - tpath.vertices[-2]
        azi =  np.arctan2(dy, dx) - np.pi / 2.0
        trans = affine + self.trans.clear(
                ).scale(scalex, scaley
                ).rotate(azi
                ).translate(x0, y0)

        gc0 = renderer.new_gc()
        gc0.copy_properties(gc)
        self._update_gc(gc0, self._gc_args)

        if self.facecolor is None:
            color = rgbFace
        else:
            color = self.facecolor

        renderer.draw_path(gc0, self.arrowpath, trans, color)
        renderer.draw_path(gc, tpath, affine, rgbFace)
        gc0.restore()

class CenteredFormatter(mpl.ticker.ScalarFormatter):
    """Acts exactly like the default Scalar Formatter, but yields an empty
    label for ticks at "center"."""
    center = 0
    def __call__(self, value, pos=None):
        if value == self.center:
            return ''
        else:
            return mpl.ticker.ScalarFormatter.__call__(self, value, pos)

rawDescription: Center origin in matplotlib

description: Center origin in matplotlib


code:
checkbox = driver.find_element_by_xpath('//tr/td[1][(@class="rowodd" or @class="roweven") and text() = "%s${nbsp}"]/following-sibling::td[2]/input[starts-with(@name, "selectionIndex")]' % k)
checkbox.click()

rawDescription: Iterating Through a Table in Selenium Very Slow


code: {'Keyword': 'Lions Tigers Bears', 'Source': 'US', 'Number': '3'}

rawDescription: Find a specific header in a CSV file using python 3 code


rawDescription: Timedeltas in Python

description: Timedeltas in Python


rawDescription: Slicing plot using different colors - manually recolor the bars


code:
import datetime

class Reminder(models.Model):
    email = models.EmailField("e-mail")
    event = models.ForeignKey(Event, unique=True, related_name='event',)
    date = models.DateTimeField(_(u"Remind date"), auto_now_add=False,)

    # update date on save
    def save(self, *args, **kwargs):
        self.date = self.event.date - datetime.timedelta(days=7)
        super(Reminder, self).save(*args, **kwargs)

class Event(models.Model):
    date = models.DateTimeField(_(u"Event Date"), auto_now_add=True,)

    # update all reminders on event save
    def save(self, *args, **kwargs):
        reminder_date = self.date - datetime.timedelta(days=7)
        self.reminders.update(date=reminder_date)
        super(Event, self).save(*args, **kwargs)

rawDescription: How to initialize model with calculated value

description: Initialize model with calculated value


code:
Update
import urllib2, re

def download(url, save_name):
    html = urllib2.urlopen(url).read()
    img_url = re.findall(r'http:[^" \\:]*_b\.jpg', html)[0]

    with open(save_name, "wb") as fp:
        fp.write(urllib2.urlopen(img_url).read())

download('http://www.flickr.com/photos/91440301@N03/9679566882/sizes/l/', 'elephant.jpg')

rawDescription: Download flickr images of specific url

description: Download flickr images of specific url


code: youtube_df = (df[df['metric_name'] == 'youtube_video'])

rawDescription: Transformations with DataFrame exporting series


code:
import operator
reduce(operator.add, seq)

rawDescription: Avoiding Python sum default start arg behavior


code:
for i in range(x):
    a[x*i:x*i+x]

rawDescription: I need help splitting a list into equal parts


code:
df
df['newDate'] = pd.to_datetime(df['Date'])

rawDescription: Splitting a column that contains multiple date formats


code: consume(imap(func, my_list), None) # On python 3 use map

rawDescription: is there some way execute every element simply?

description: Is there some way execute every element simply


code:
import sys
import win32_unicode_argv

rawDescription: Read Unicode characters from command-line arguments in Python 2.x on Windows


code: {key:val for key, val in iterable}

rawDescription: What's the pythonic idiom for making a simple list out of a list of instances?


code:
def isSorted(self):
    return set(self.a) == set(self.b)

rawDescription: Class and while loop?

description: Class and while loop


code: arr / 3

rawDescription: how to (simply) build a integer and float mixed numpy array


code:
from itertools import product
lst = [['one', 'two', 'three'], ['a', 'b'], ['left', 'right']]
print(list(product(*lst)))

rawDescription: Python 3.3: All possible combinations of list


code:
class UserModel(models.model):
    # fields here

    class Meta:
        app_label = "myapp"

rawDescription: How do I separate my models out in django?

description: Separate my models out in django


rawDescription: Python tab creation

description: Python tab creation


code:
if False:
    import re
    import email
    import time
    # ...

rawDescription: Importing the entire Python standard library


rawDescription: Pyparsing: word with at least one non-digit character


code:
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    result = serializers.SerializerMethodField()

    class Meta:
        model = Snippet
        fields = ('title', 'code', 'owner', 'url', 'result')

    def get_result(self, obj):
        # code here to calculate the result
        # or return obj.calc_result() if you have that calculation in the model
        return "some result"

rawDescription: Django rest framework: serializers.ReadOnlyField() doesn't display field in browsable api


rawDescription: How to capture query string parameter in form view?

description: Capture query string parameter in form view


code:
example = [0, 1, 0, 2, 0, 4]
map(sum, grouper(3, example, 0))

rawDescription: Adding up number in a list with every 3 number


code:
def __init__(self,S,Info):
    self.Term = S
    self.TermInfo = [Info]

rawDescription: Append to the same list

description: Append to the same list


code: print >> file, line,

rawDescription: Read every second line and print to new file


code:
def make_path_grouper(prefix_checker):
    matcher = difflib.SequenceMatcher()
    def path_grouper(path):
        if not matcher.a:
            matcher.set_seq1(path)
            return path
        else:
            matcher.set_seq2(path)
            matchings = tuple(matcher.get_matching_blocks())
            # arbitrary code to decide whether we have a match
            if matchings and prefix_checker(matcher.a[:matchings[0][2]]):
                # we have a match
                return matcher.a
            else:
                # no match. The new path supersedes old "a"
                matcher.set_seq1(path)
                return path
    return path_grouper

rawDescription: How to cluster similar file paths?

description: Cluster similar file paths


code:
def login(): ...
def check_tooltips(): ...

rawDescription: Python Selenium webdriver query

description: Python Selenium webdriver query


code:
def changelist_view(self, request, extra_context=None):
    # a lot of stuff happen here
    return TemplateResponse(request, self.change_list_template or [
        'admin/%s/%s/change_list.html' % (app_label, opts.object_name.lower()),
        'admin/%s/change_list.html' % app_label,
        'admin/change_list.html'
    ], context, current_app=self.admin_site.name)

rawDescription: How can i change the Django admin template on the fly

description: Change the Django admin template on the fly


code:
Nx1 = np.unique(data[:, 0]).shape[0]
Nx2 = np.unique(data[:, 1]).shape[0]
Nx3 = np.unique(data[:, 2]).shape[0]

rawDescription: Converting coordinate tuple information to numpy arrays


code: {'age': 24, 'friends': ['Bob', 'Alice', 'Karen', 'Daren'], 'name': 'Jack'}

rawDescription: Updating python dicts

description: Updating python dicts


code:
def dashboard(request):
    form = FilterForm()
    sightings = []
    if request.POST:
        form = FilterForm(request.POST)
        if form.is_valid():
            selectedplant = form.cleaned_data['selectedplant']
            sightings = Sighting.objects.filter(IMS_plant=selectedplant)
        else:
            sightings = Sighting.objects.all().order_by('date')
    else:
        sightings = Sighting.objects.all().order_by('date')

    context =  {'sightings':sightings, 'form': form}

    return render_to_response('dashboard.html', context, context_instance=RequestContext(request))

rawDescription: dropdown that filters results in django

description: Dropdown that filters results in django


rawDescription: savetxt two columns in python,numpy

description: Savetxt two columns in python,numpy


code:
from collections import defaultdict
dic2 = defaultdict(dict)
dic2['New York']['Chicago'] = 25

rawDescription: How to create a Dictionary in Python with 2 string keys to access an integer?

description: Create a Dictionary in Python with 2 string keys to access an integer


code:
def myfunc2(*args):
    pass

rawDescription: Passing n arguments to a function in Python


code:
# content of test_server.py

import pytest

@pytest.mark.webtest
def test_send_http():
    pass # perform some webtest test for your app

def test_always_succeeds():
    assert 2 == 3 - 1

def test_will_always_fail():
    assert 4 == 5

rawDescription: Is there a way to add metadata in py files for grouping tests?


code:
msg = "This is the message that I want displayed on my wall"
imageid = facebook_image_id  #to get this you will have execute a read via the graph api and select the image you want to "reference" on your wall post
GraphAPI.put_object("me", "feed", message=msg,object_attachment=imageid)

rawDescription: Upload images to Facebook wall via python and Graphapi


code:
positions = {}
positions[tutle.pos()] = []

rawDescription: List Title Depends on Variable in Python


code: from datetime import date

rawDescription: How to make a chronological list of files, with the file modification date

description: Make a chronological list of files, with the file modification date


code:
class NoNegativesDict(dict):
    def __sub__(self, other):
        if set(other) - set(self):
            raise ValueError
        else:
            res = NoNegativesDict()
            for key,sv in self.iteritems():
                ov = other.get(key, 0)
                if sv < ov:
                    raise ValueError
                # elif sv == ov:
                #     pass
                elif sv > ov:
                    res[key] = sv - ov
            return res

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


code:
mask = (weather == w)
masked_hour = hour[mask]
masked_rentals = rentals[mask]

rawDescription: Is there a way to use bincount with a clause in python?


code:
a = np.loadtxt('file1.txt')
b = np.loadtxt('file2.txt')

aind = np.lexsort((a[:,1], a[:,0]))
bind = np.lexsort((b[:,1], b[:,0]))

a = a[aind]
b = b[bind]

rawDescription: Finding the correspondence of the elements of two columns in a two dimensional array in another 2D array


code:
...
url(r'^list/$', 'dataports.views.list', name='list'),
...

rawDescription: Uploading files from a Python client to a Django Server


code: output = v[1].split("\n")

rawDescription: Storing bash commands in python list

description: Storing bash commands in python list


code:
line='1\t abc'
re.search('^(\d+)\s+(.*)', line).groups()

rawDescription: Extracting two values from python regex

description: Extracting two values from python regex


code:
LBRACK,RBRACK,LPAREN,RPAREN = map(Suppress,"[]()")
and_op = CaselessKeyword('and')
or_op = CaselessKeyword('or')
word = Word(alphanums + '.-/&')

field_qualifier = LBRACK + OneOrMore(word) + RBRACK
search_term = ((Group(OneOrMore(word)) | quoted_string)('search_text') +
               Optional(field_qualifier)('field'))
expr = Forward()
atom = search_term | (LPAREN + expr + RPAREN)
or_term = atom + ZeroOrMore(or_op + atom)
and_term = or_term + ZeroOrMore(and_op + or_term)
expr << and_term

rawDescription: pyparsing one query format to another one

description: Pyparsing one query format to another one


code:
{ "expiration": "2007-12-01T12:00:00.000Z",
  "conditions": [
    {"bucket": "johnsmith" },
    ["starts-with", "$key", "user/eric/"],
    {"acl": "public-read" },
    {"redirect": "http://johnsmith.s3.amazonaws.com/successful_upload.html" },
    ["starts-with", "$Content-Type", "image/"],
    {"x-amz-meta-uuid": "14365123651274"},
    ["starts-with", "$x-amz-meta-tag", ""],
  ]
}

rawDescription: Python Generated Signature for S3 Post

description: Python Generated Signature for S3 Post


code:
images = [img for img in gc.images.list()
          if 'CentOS-7-x86_64 'in img.name]

rawDescription: Openstack - Selectively deleting images based on some criteria?


rawDescription: Python sort CSV File

description: Python sort CSV File


code: return sum((doSomething(x) for x in originalList), [])

rawDescription: How can I use a list comprehension to extend a list in python?

description: Use a list comprehension to extend a list in python


code: cur.execute(query, text_list)

rawDescription: Unpack python list to pass to a MySQL WHERE clause?


code:
from rpyc import classic

c = classic.connect("0.0.0.0",port=18812)

print(c.modules.sys.platform)
linux

rawDescription: How to start an rpyc server?

description: Start an rpyc server


rawDescription: Understanding Python name objects, immutable data, and memory management


code:
num_pages = Math.Ceil( T / I ) # ceil(100/10) = 10 pages
cur_page = P # 0

start = I*P # 10 * 0 = 0
end = start + ipp # 0 + 10 = 10
if end > total: # false
  end = total

items = allitems[start:end] # this page's items

rawDescription: Pagination in web2py with no database

description: Pagination in web2py with no database


code: [''.join(zip(*v)[-1]) for k, v in groupby(zip(some_list, st), key = itemgetter(0)) if k]

rawDescription: Match character from string with binary list


code:
import csv

required = ['D0', 'D1', 'D2', 'D3', 'D4', 'D5']
entries = []

with open('input.csv', 'rb') as f_input:
    for dict_row in csv.DictReader(f_input):
        entries.append([dict_row[col] for col in required])

rawDescription: Python: How to pass multiple keys at a time to dictionary


code:
def error_handler(self, failure):
    global authorization_token
    status = failure.value.response.status
    if status == 401:
        form_data = {'grant_type': 'assertion', 'assertion_type': 'public', 'client_id': 'WDPRO-MOBILE.CLIENT-PROD'}
        auth_site_request = requests.post(url=AUTHORIZATION_URL, data=form_data)
        auth_site_response = json.loads(auth_site_request.text)
        disney_authorization_token = '{}'.format(auth_site_response['access_token'])

        yield failure.request

def start_requests(self):
    form_data = {'grant_type': 'assertion', 'assertion_type': 'public', 'client_id': 'WDPRO-MOBILE.CLIENT-PROD'}
    return [FormRequest(url=AUTHORIZATION_URL, formdata=form_data,
                        callback=self.start_first_run)]

def start_first_run(self, response):
    self.handle_auth(response)
    return self.request_ride_times()

def handle_auth(self, response):
    global authorization_token

    data = json.loads(response.body)

    # get auth token
    authorization_token = '{}'.format(data['access_token'])

def request_ride_times(self):
    # note: this probably isn't really necessary but it doesn't hurt (all the sites we are scraping are in EST)
    now = get_current_time_for_timezone("US/Eastern")

    # get ending timeframe for scraping dates - 190 days out
    until = now + SCRAPE_TIMEFRAME

    for filter_type in FILTER_TYPES:
        filter_url_query_attr = '&filters={}'.format(filter_type)

        scrape_date = now

        while scrape_date <= until:
            url = urljoin(SCRAPE_BASE_URL,
                          '{}{}&date={}'.format(SCRAPE_BASE_URL_QUERY_STRING,
                                                filter_url_query_attr, scrape_date.strftime("%Y-%m-%d")))
            yield AuthTokenRequest(url, callback=self.parse_ride_times, errback=self.error_handler, dont_filter=True,
                                meta={"scrape_date": scrape_date})

            scrape_date += timedelta(days=1)

def parse_ride_times(self, response):
    # parse json data
    data = json.loads(response.body)
    # process data...

rawDescription: Scrapy - scraped website authentication token expires while scraping


code: dis.dis('"foo" + "bar" + "baz"')

rawDescription: Why does string concatenation matter in Python?


code: import lighthouse

rawDescription: Manually installing python package

description: Manually installing python package


code:
q = [2,3,4]
res = []
for i in q:
    res.append(np.power(c, i))
res = np.array(res)
# afterwards res is just
# array([[ 1,  4,  9],
#        [ 1,  8, 27],
#        [ 1, 16, 81]], dtype=int32)

rawDescription: take different powers of a vector and save in txtfile

description: Take different powers of a vector and save in txtfile


code: type('object')

rawDescription: Identifying the class in which code is running


code:
afile = open('filename')
tuple_data = []
for line in afile:
    a = line.strip().split()
    tuple_data.append((a[0].strip(), a[-1].strip()))

rawDescription: creating dictionaries in python

description: Creating dictionaries in python


code: lista = [line.strip() for line in z.readlines()]

rawDescription: readlines() without EOL at the of the lines

description: Readlines() without EOL at the of the lines


code:
def shows_json(request):
    objects = Show.objects.all()
    l = [{"pk": d["pk"], "url": d["fields"]["url"], "image": d["fields"]["image"], "name": d["fields"]["name"]} for d in objects]
    tmp = dict(str((d["pk"]), d) for d in l)
    json = toJSON(tmp)
    result = render_to_string('jsonlist.html', RequestContext(request, {
                'json': json,
            }))
    return HttpResponse(result)

rawDescription: Deserialize list of nested dictionaries to a simpler form


code:
def SpecificPLayer(request, playerslug):
    player = Player_Bios.objects.get(player_id=playerslug) #this is the name, last and it is working fine
    batstats = player.batstat_set.all()
    context = {'player' : player, 'today' : date.today(), 'batstats': batstats, }
    return render_to_response ('singleplayer.html', context,context_instance=RequestContext(request))

rawDescription: Django: Foreign Key Query to post the information on the html template


code:
import sys
import asciitree
class Node(object):
    def __init__(self, name, indent, parent):
        self.name = name
        self.indent = indent
        self.parent = parent
        self.children = []
    def add(self, child):
        self.children.append(child)
    def __str__(self):
        return self.name
def main():
    current_indent = -1
    root_node = Node('Root', current_indent, None)
    current_node = root_node
    with open(sys.argv[1]) as file_to_parse:
        for scanned_line in (l.rstrip() for l in file_to_parse):
            line_content = scanned_line.lstrip()
            if not line_content:
                continue
            indent = len(scanned_line) - len(line_content)
            while True:
              if indent > current_node.indent:
                  parent = current_node
                  break
              elif indent == current_node.indent:
                  parent = current_node.parent
                  break
              else:
                  current_node = current_node.parent
            child = Node(line_content, indent, parent)
            parent.add(child)
            current_node = child
    print(asciitree.draw_tree(root_node))

if __name__ == '__main__':
    main()

rawDescription: Command output parsing

description: Command output parsing


code: dfrm

rawDescription: Python pandas: Getting the locations of a value in dataframe


code:
def divide(num, den, prec):
    a = (num*10**prec) // den
    s = str(a).zfill(prec+1)
    return s[0:-prec] + "." + s[-prec:]

rawDescription: Decimal precision in python without decimal module


code:
def is_happy(items):
    happy_children = True
    for item in items:
        if any(child.state not in ['happy', 'cheerful'] for child in item):
            happy_children = False
            break
    return all(item.state in ['happy', 'cheerful'] for item in items) and happy_children

rawDescription: Is it possible to nest the all function?

description: Is it possible to nest the all function


code:
import json

with open("file.txt", "w") as f:
    json.dump(Dict, f)

with open("file.txt") as f:
    Dict2 = json.load(f)

rawDescription: Python how to use a string to fill a dictionary in one go?


code: (indices,) = np.nonzero(consecutives == N)

rawDescription: Reasoning about consecutive data points without using iteration


code: raw_text.replace('     ','')

rawDescription: Identifying sections tabbed in from raw text


code:
from operator import itemgetter
dic = {}
dic.update(dict(sorted(d.items(), key=itemgetter(1), reverse=True)[:2]))

rawDescription: put top 2 biggest keys and values of dictionary in another dictionary

description: Put top 2 biggest keys and values of dictionary in another dictionary


code:
list2_set = set([tuple(x) for x in list2])
diff = [x for x in list1 if tuple(x) not in list2_set]

rawDescription: python function slowing down for no apparent reason

description: Python function slowing down for no apparent reason


code:
import re
pattern = '1**0*'.replace('*', '[01]')
bool(re.match(pattern, '00000'))
bool(re.match(pattern, '10000'))

rawDescription: Python wildcard matching

description: Python wildcard matching


code:
values = "MY VALUES ('{date}', {rec}, {rec_count})"
values.format(date='2015-07-01', rec='click', rec_count=222)

rawDescription: how to join various bits of string and data together using python

description: Join various bits of string and data together using python


code:
s = {i: v for i, v in enumerate(r)}
print(s)

rawDescription: How to index all chars in every item/key for a list/dictionary as unique ids

description: Index all chars in every item/key for a list/dictionary as unique ids


code:
import pandas as pd
pd.to_datetime(dataframe['column'],format='%d%b%y:%H:%M:%S')

rawDescription: Extract date from string Pandas data frame


code:
import re

re_flags = ( re.MULTILINE | re.IGNORECASE | re.UNICODE )
m = re.search( r"<div>\s*(\d*)\s*</div>" , vr , re_flags )
if m :
    print( m.groups()[0] )

rawDescription: Regex and BeautifulSoup using Python

description: Regex and BeautifulSoup using Python


rawDescription: Obtaining length of list as a value in dictionary in Python 2.7


code:
query = db.session.query(Tag, db.count(Post.id))
query = query.filter(
    (tags_to_posts_association_table.tag_id == Tag.id) & \
    (tags_to_posts_association_table.post_id == Post.id)
)
query = query.group_by(Tag.id)

rawDescription: Flask how to calculate tags count

description: Flask how to calculate tags count


code:
A[:,[1,2]] # choose all rows from columns 1-2 (gives C)
A[:,[0]+range(3, 10)] # choose all rows from columns 0, 3-9 (gives B)

rawDescription: splitting numpy array into 2 arrays

description: Splitting numpy array into 2 arrays


code:
def dot(a, b):
    return a.x*b.x + a.y*b.y + a.z*b.z

rawDescription: Getting local 2D coordinates of vertices of a planar polygon in 3D space


code:
r"""
\s             # Match a single character that is a “whitespace character” (spaces, tabs, and line breaks)
   +              # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
(?=            # Assert that the regex below can be matched, starting at this position (positive lookahead)
   [^()]          # Match a single character NOT present in the list “()”
      *              # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   (?:              # Match the regular expression below
                     # Match either the regular expression below (attempting the next alternative only if this one fails)
         \(             # Match the character “(” literally
      |              # Or match regular expression number 2 below (the entire group fails if this one fails to match)
         $              # Assert position at the end of a line (at the end of the string or before a line break character)
   )
)
"""

rawDescription: Python: splitting on spaces, except between certain characters


code:
class Class:
    def descriptor(self):
        return

foo_instance = Foo()
method_object = foo_instance.descriptor

rawDescription: Why should classes with __get__ or __set__ know who uses them?


code:
b = np.array([19, 17, 15, 14, 29, 33, 28, 4, 90, 6])
b_truncated = b[a < truncatevalue]
b_truncated

rawDescription: How to truncate a numpy array for values greater than a specified value?

description: Truncate a numpy array for values greater than a specified value


code:
sorted(product_list, key=lambda k: (k['verifier'] != 1, k['index']))
sorted(product_list, key=lambda k: k['index'] if k['verifier'] == 1 else float('inf'))

rawDescription: sort python list of dictionaires based on value of 2 keys

description: Sort python list of dictionaires based on value of 2 keys


code:
def f1():
  return True
f1 = validate_arguments(arg1, arg2)(f1)

rawDescription: Manually calling a decorator that takes arguments


code:
def create_new_pea(request):
    user = request.user
    def set_queryset(f, **kwargs):
        formfield = f.formfield(**kwargs)
        if f.name == 'bowl':
            formfield.queryset = user.bowl_set.all()
        return formfield
    PeaFormset = inlineformset_factory(django.contrib.auth.models.User, Pea, formfield_callback=set_queryset)

rawDescription: Passing queryset to foreignkeyfield in django inlineform


code:
from flask import Flask
app = Flask(__name__)

rawDescription: How Gunicorn forward request to flask

description: How Gunicorn forward request to flask


code: myobject = pickle.load(open('myfile', 'r'))

rawDescription: Making "durable" objects

description: Making "durable" objects


code: soup = bs4.BeautifulSoup(S, 'xml')

rawDescription: How to get BeautifulSoup 4 to respect a self-closing tag?

description: Get BeautifulSoup 4 to respect a self-closing tag


code:
import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])
df['foo'] = df['cost']
df['cost'] = df['cost'].map('${:,.2f}'.format)
print(df)

rawDescription: how to display pandas DataFrame using a format string for columns?

description: Display pandas DataFrame using a format string for columns


code:
list({callback(val): val for val in my_list}.values())

# In your case:
list({int(val['foo']/100): val for val in my_list}.values())

# Returns:
[{'foo': 320}, {'foo': 560}]

rawDescription: Remove duplicate according to a callback


rawDescription: Is a chained if...else expression in python faster than if..elif..else statements?


code: new_dict = {word:0 for word in text_file}

rawDescription: Vectorizing LIst of Unique Words into 0 or 1 using Python


rawDescription: How to solve non-linear equations using python

description: Solve non-linear equations using python


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

np.random.seed(2015)
N = 130
reso_values = np.random.randint(10, size=N)
reso_names = np.random.choice(list(string.letters), N*4).view('|S{}'.format(4))

fig, axs = plt.subplots(nrows=2, sharey=True, figsize=(14,18), dpi=50)

mpl.rcParams.update({'figure.autolayout': True})
fig.suptitle('Resolution Category Tier 3 Volume',
          **{'family': 'Arial Black', 'size': 22, 'weight': 'bold'})

for ax, start, end in zip(axs, (0, 60), (60, N)):
    names, values = list(reso_names[start:end]), reso_values[start:end]
    ax.bar(range(len(values)), values, align='center')
    ax.set_xlabel('Resolution Category Tier 3')
    ax.set_ylabel('Volume')
    ax.set_xticks(range(len(names)))
    ax.set_xticklabels(names, rotation='vertical')
    ax.set_xlim(0, len(names))
# plt.savefig('Reso3.pdf', format='pdf')
fig.subplots_adjust(bottom=0.05, top=0.95)
plt.show()

rawDescription: Pandas: Y Axis consistency across graphs


code: inputs = []

rawDescription: User Defined Interrupt

description: User Defined Interrupt


code:
limit = 5
subgraph = graph.subgraph(bfs[:limit])

rawDescription: APGL (Another Python Graph Library) - Set subgraph size after a Breadth First Search


code:
from datetime import datetime
start_time_1 = datetime.now()
res= findSeq("eth0",data)
print('Duration: {}'.format(datetime.now() - start_time_1))

from datetime import datetime
start_time_2 = datetime.now()
re.search(r'eth0.*?RX packets:(\d+)',data,re.DOTALL).group(1)
print('Duration: {}'.format(datetime.now() - start_time_2))

rawDescription: Extract string and assign to the variable using regex in Python


code:
['Mercury',
 'Venus',
 'Mars',
 'Jupiter',
 'Saturn',
 'Uranus',
 'Neptune',
 'Pluto',
 'Sun',
 'Moon',
 'Phobos',
 'Deimos',
 'Io',
 'Europa',
 'Ganymede',
 'Callisto',
 'Mimas',
 'Enceladus',
 'Tethys',
 'Dione',
 'Rhea',
 'Titan',
 'Hyperion',
 'Iapetus',
 'Ariel',
 'Umbriel',
 'Titania',
 'Oberon',
 'Miranda']

rawDescription: look up planet or moon by name in pyephem?

description: Look up planet or moon by name in pyephem


code:
import numpy as np
from scipy.optimize import minimize

A = np.array([[1., 2., 3.],[4., 5., 6.],[7., 8., 10.]], order='C')
b = np.array([6., 12., 21.])
n = len(b)

# Ax = b --> x = [1., -2., 3.]

fun = lambda x: np.linalg.norm(np.dot(A,x)-b)
# xo = np.linalg.solve(A,b)
# sol = minimize(fun, xo, method='SLSQP', constraints={'type': 'ineq', 'fun': lambda x:  x})
sol = minimize(fun, np.zeros(n), method='L-BFGS-B', bounds=[(0.,None) for x in xrange(n)])

x = sol['x'] # [2.79149722e-01, 1.02818379e-15, 1.88222298e+00]

rawDescription: Numpy: Linear system with specific conditions. No negative solutions


code:
with open('file') as f:
    w, h = [int(x) for x in next(f).split()]
    array = [[int(x) for x in line.split()] for line in f]

rawDescription: How to read numbers from file in Python?

description: Read numbers from file in Python


code: ABC = [ sum(z, []) for z in itertools.product(*SETS) ]

rawDescription: Python: Concatenate list of lists in the algebraic way


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

url = 'http://www.booking.com/searchresults.en-gb.html?label=gen173nr-17CAEoggJCAlhYSDNiBW5vcmVmaFCIAQGYAS64AQTIAQTYAQHoAQH4AQs;sid=1a43e0952558ac0ad0061d5b6523a7bc;dcid=1;checkin_monthday=4;checkin_year_month=2016-2;checkout_monthday=11;checkout_year_month=2016-2;city=-2601889;class_interval=1;csflt=%7B%7D;group_adults=7;group_children=0;highlighted_hotels=1192837;hp_sbox=1;label_click=undef;no_rooms=1;review_score_group=empty;room1=A%2CA%2CA%2CA%2CA%2CA%2CA;sb_price_type=total;score_min=0;si=ai%2Cco%2Cci%2Cre%2Cdi;ss=London;ssafas=1;ssb=empty;ssne=London;ssne_untouched=London&;order=price_for_two'

# setting a custom User-Agent
user_agent = (
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) " +
    "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36"
)

dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = user_agent

driver = webdriver.PhantomJS(desired_capabilities=dcap)
driver.get(url)

# wait for the total prices to become present
WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".totalPrice")))

content = driver.page_source
driver.close()

soup = bs(content, 'lxml')
for e in soup.select('.totalPrice'):
    print(e.text.strip())

rawDescription: BeautifulSoup not finding elements

description: BeautifulSoup not finding elements


code:
A
out

rawDescription: NumPy array sum reduce

description: NumPy array sum reduce


code:
from django import forms

class YourLoginForm(forms.Form):
   username = forms.CharField(max_length=254)
   password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)

rawDescription: how to use user authentication in django

description: Use user authentication in django


code: curve_fit(func, table[['A', 'B', 'C', 'D']].T, table['Z_real'])

rawDescription: Pass Pandas DataFrame to Scipy.optimize.curve_fit


code:
def func(x,y):
    global x #these tell the function to look at the outer scope
    global y #and use those references to x and y, not the inner scope
    x=200
    y=300

func(x,y)
print(x,y) #prints 200 300

rawDescription: How to change the scope of a variable in a function? Python

description: Change the scope of a variable in a function? Python


code: return [x for x in a_list if x.smth == 2]

rawDescription: Python: Subsetting a list according to the attribute


rawDescription: Check what proxies are used in Requests module in Python3


code:
db.junk.ensureIndex({ "b": 1, "a": 1 })

db.runCommand({
    "planCacheSetFilter": "junk",
    "query": { "a": 1 },
    "indexes": [
        { "b": 1, "a": 1 }
    ]
})

rawDescription: Provide a hint in bulk upserts

description: Provide a hint in bulk upserts


code:
from ctypes import *
from ctypes.wintypes import *

class MOUSEINPUT(Structure):
    _fields_ = [
        ('dx', LONG),
        ('dy', LONG),
        ('mouseData', DWORD),
        ('dwFlags', DWORD),
        ('time', DWORD),
        ('dwExtraInfo', POINTER(ULONG)),
    ]

class KEYBDINPUT(Structure):
    _fields_ = [
        ('wVk', WORD),
        ('wScan', WORD),
        ('dwFlags', DWORD),
        ('time', DWORD),
        ('dwExtraInfo', POINTER(ULONG)),
    ]

class HARDWAREINPUT(Structure):
    _fields_ = [
        ('uMsg', DWORD),
        ('wParamL', WORD),
        ('wParamH', DWORD)
    ]

class INPUT(Structure):
    class _I(Union):
        _fields_ = [
            ('mi', MOUSEINPUT),
            ('ki', KEYBDINPUT),
            ('hi', HARDWAREINPUT),
        ]

    _anonymous_ = ('i', )
    _fields_ = [
        ('type', DWORD),
        ('i', _I),
    ]

rawDescription: How would you recreate this Windows API Structure with ctypes?


code: return S.pop()

rawDescription: Python | Access the sole element of a set


code: print_hello = lambda *a, **kw: sys.stdout.write("Hello world\n", *a, **kw)

rawDescription: Python Argument Binders

description: Python Argument Binders


code:
df = pd.read_csv("rto2.txt",names=["date","period"]+list(range(1,13)),index_col=[0,1])
df = df.stack().reset_index().rename(columns={"level_2":"hour",0:"value"})
df.index = pd.to_datetime(df.apply(lambda x: "{date} {hour}:00 {period}".format(**x),axis=1))
df.drop(["date", "hour", "period"], axis=1, inplace=True)

rawDescription: Python Pandas: Find index based on value in DataFrame


code: return obj.choice_set.count()

rawDescription: How to see how many relations a Django model has in admin?

description: See how many relations a Django model has in admin


code:
b < a   # -1  true   --> [b, a, c, d]
c < b   # -1  true   --> [c, b, a, d]
d < c   # 1   false
d < b   # 1   false
d < a   # -1  true   --> [c, b, d, a]

rawDescription: How does a Python custom comparator work?


code:
parent:  p | {'num': 'p-0003'}
'\nProtein kinases are involved in the signal transduction pathways linking growth factors, hormones and other cell regulation molecules to cell growth, survival and metabolism under both normal and pathological conditions. One such protein kinase, protein kinase B (also known as Akt), is a serine/threonine kinase that plays a central role in promoting the proliferation and survival of a wide range of cell types, thereby protecting cells from apoptosis (programmed cell death) (Khwaja,\n'
child:  i | {}
'Nature' | u'\n33-34 (1990)). Three members of the Akt/PKB subfamily of second-messenger regulated serine/threonine protein kinases have been identified and are termed Akt1/PKB\u03b1, Akt2/PKB\u03b2, and Akt3/PKB\u03b3. A number of proteins involved in cell proliferation and survival have been described as substrates of Akt in cells. Two examples of such substrates include glycogen synthase kinase-3 (GSK3) and Forkhead transcription factors (FKs). See Brazil and Hemmings,\n'
child:  i | {}
'Trends in Biochemical Sciences' | '\n26, 675-664.\n'
parent:  p | {'num': 'p-0004'}
u'\nA number of protein kinases and phosphatases regulate the activity of Akt; For instance, activation of Akt is mediated by phosphatidylinositol 3-kinase (PI3-K), which initiates the binding of second messenger phospholipids to the pleckstrin homology (PH) binding domain of Akt. The binding anchors Akt to plasma membrane and results in phosphorylation and activation of the enzyme. Amplifications of the catalytic subunit of PI3-K, p110\u03b1, or mutations in the PI3-K regulatory subunit, p85\u03b1, lead to activation of Akt in several types of human cancer. (Vivanco and Sawyers,\n'
child:  i | {}
'Nature Reviews in Cancer' | '\n(2002) 2: 489-501.\n'
parent:  p | {'num': 'p-0005'}
'\nThe tumor suppressor, PTEN, is a critical negative regulator of Akt activation by PI3-K. Myers et al.\n'

rawDescription: How to parse all children and grandchildren elements from a current node using xml.etree.ElementTree in python

description: Parse all children and grandchildren elements from a current node using xml.etree.ElementTree in python


code:
# left: 20, top: 0, right: 20, bottom: 0
layout.setContentsMargins(20,0,20,0)

rawDescription: PySide Qt: Auto vertical growth for TextEdit Widget, and spacing between widgets in a vertical layout


code:
range(4) # range create a list of 'n' numbers
['elem' for _ in range(4)] # we use range to create 4 times 'elem'

rawDescription: Random string generation with upper case letters and digits in Python


code:
import random
s = ''
for i in range(0,8):
    key = random.randint(33,126)
    s += chr(key)
print(s)

rawDescription: How can I make a string of ASCII characters from a for loop (Python 3.3)?

description: Make a string of ASCII characters from a for loop (Python 3.3)


rawDescription: Formatting text to be justified in Python 3.3 with .format() method


rawDescription: Python List within List - References

description: Python List within List - References


code: return set(pair) - [core]

rawDescription: pythonic solution for finding the other element in a list of length two

description: Pythonic solution for finding the other element in a list of length two


code:
from scipy.optimize import brute
grid = [slice(1, 10, 1)]  # grid search over 1, 2, ..., 9
# it is important to specify finish=None in below
intcoef = brute(errfun, grid, args=(xs, ys,), finish=None)
floatcoef = optfloat(intcoef, xs, ys)['floatcoef'][0]

rawDescription: curve fitting with integer inputs Python 3.3

description: Curve fitting with integer inputs Python 3.3


code: 'foo bar spam'.rsplit(None, 1)

rawDescription: How to get frequency of specific character in a list?

description: Get frequency of specific character in a list


code:
X, Y = positions[:,None], positions_u[None,:]
selectedMat[X, Y] += originalMat[X, Y]
selectedMat[Y, X] += originalMat[Y, X]

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


code:
def even_only(lst):
    evens = []
    for number in lst:
        if is_even(number):
            evens.append(number)
    return evens

rawDescription: even numbers python list

description: Even numbers python list


rawDescription: How to get type of multidimensional Numpy array elements in Python

description: Get type of multidimensional Numpy array elements in Python


rawDescription: Using `find_all()` to get all tags of a subset of that same tag


code: {i: np.where(estimator.labels_ == i)[0] for i in range(estimator.n_clusters)}

rawDescription: cluster points after KMeans clustering (scikit learn)

description: Cluster points after KMeans clustering (scikit learn)


rawDescription: Advanced (maybe) selection rule for lists in Python


rawDescription: Is there a way to delist a list in python?


code:
def foo(some_dict=None):
  if some_dict is None:
    some_dict = {}

rawDescription: python local variable bizarre behavior

description: Python local variable bizarre behavior


code:
def page(self, number):
    "Returns a Page object for the given 1-based page number."
    number = self.validate_number(number)
    bottom = (number - 1) * self.per_page
    top = bottom + self.per_page
    if top + self.orphans >= self.count:
        top = self.count
    return Page(self.object_list[bottom:top], number, self)

rawDescription: Will this cost me two queries for the same thing?


code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
xlen = len(X)
Y = np.arange(-5, 5, 0.25)
ylen = len(Y)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
maxR = np.amax(R)
Z = np.sin(R)

# Note that the R values must still be normalized.
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=cm.jet(R/maxR),
        linewidth=0)

plt.show()

rawDescription: Distance dependent coloring in matplotlib


code:
values=["2","3"]
content=["line1","line2","line3"]
for line in content:
    if not any(value in line for value in values):
        print(line)

rawDescription: Applying conditional after nested loop to the parent loop


rawDescription: Calculate new value based on decreasing value


code: mylist[0][:1]  # get up to the first character in the first item in the list

rawDescription: Python: Get the first character of a the first string in a list?


code:
def searchFor(datafile):
    with open(datafile,'r') as f:
        data = f.readline()
        data = data.split()
        data = [thing.strip() for thing in data]
        return data

rawDescription: Searching logs, outputting lines before and after match


code:
import cPickle
pickled = cPickle.dumps(prng)
prng.random_sample()
prng.random_sample()
prng2 = cPickle.loads(pickled)
prng2.random_sample()
prng2.random_sample()

rawDescription: Choose random seed and save it

description: Choose random seed and save it


code:
import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36',
    'Content-Type': 'application/json',
    'Referer': 'http://droughtmonitor.unl.edu/MapsAndData/DataTables.aspx',
    'X-Requested-With': 'XMLHttpRequest',
}
import json
data = json.dumps({'area':'conus', 'type':'conus', 'statstype':'1'})

ajax = requests.post("http://droughtmonitor.unl.edu/Ajax.aspx/ReturnTabularDM",
                  data=data,
                  headers=headers)
from pprint import pprint as pp

pp(ajax.json())

rawDescription: Get all td content inside tbody of tr in python using lxml


code:
def isOdd(num):
    if type(num) not in [int, long]:
        return False
    if ((-1)**num) == 1:
        return False
    return True

rawDescription: How would I check if a number is odd in python without using modulo or a library?


code:
index, size = 0, len(sequence)
while index < size:
    spam(sequence[index])
    index += 1

rawDescription: Trying to return numbers in a list

description: Trying to return numbers in a list


code:
from jellyfish import soundex

class SoundexDict(dict):
    # __init__ and __repr__ is left as an exercise for the reader
    def __getitem__(self, key):
        return super().__getitem__(soundex(key))

    def __setitem__(self, key, value):
        super().__setitem__(soundex(key), value)

mydict = SoundexDict()
mydict['google'] = 'google.com'
print(mydict['gewgle'])  # prints 'google.com'

rawDescription: Python dictionary vague key search

description: Python dictionary vague key search


code:
import re
inputtext = '''\
<script type="text/javascript">
    window.DETAILS_PAGE_MAP_GLOBALS = {
        GOOGLE_MAPS_LONGITUDE: 55.4159330979,
        GOOGLE_MAPS_LATITUDE: 25.1549968578
    };
</script>
'''
pattern = re.compile(r'GOOGLE_MAPS_LONGITUDE:\s*(\d+\.\d+),\s*GOOGLE_MAPS_LATITUDE:\s*(\d+\.\d+)')
pattern.search(inputtext).groups()

rawDescription: python how to get the data of this script

description: Python how to get the data of this script


code:
matches = soup.find_all('dl', attrs={'class': ['class', 'method','function','describe', 'attribute', 'data', 'clasmethod', 'staticmethod']})
for element in matches:
    element.extract()  # remove from tree (and parent `dl` matches)

rawDescription: Grabbing different elements with BeautifulSoup: avoid duplicating in nested elements


code: re.findall(r'{[^}]*}|\b\w+\b', u'{Łatwe|Proste} szukanie mieszkania {Sprawdź|Wypróbuj juz dziś}, znalezienie {wcale|w ogóle}', re.U)

rawDescription: Python string split using regex

description: Python string split using regex


rawDescription: Non-linear scaling of a colormap to enhance contrast


code:
with open('Input_Domains.txt','r') as f:
    for line in f:
        full_spf=getspf(line.strip())

rawDescription: Issue in Writing the contents of a variable to a file


code:
tempdir = tempfile.mkdtemp()
xvfb = subprocess.Popen(['Xvfb', ':99', '-nolisten', 'tcp', '-fbdir', tempdir])

rawDescription: How do I start and stop a Linux program using the subprocess module in Python?

description: Start and stop a Linux program using the subprocess module in Python


code:
df = pd.DataFrame(...)
tag = pd.DataFrame(df.tags.tolist()).stack()
tag.index = tag.index.droplevel(-1)
tag.name = 'tag'
df.join(tag).groupby('tag').sum()

rawDescription: Groupby items within a list in a Pandas DataFrame


rawDescription: List of tuples with numbers and strings

description: List of tuples with numbers and strings


code:
import re

file = open('frank.txt', 'r')

file = file.read()

numbers = re.findall(r"[-+]?\d*\.\d+|\d+", file)

print(numbers)

rawDescription: How to extract only numbers from input file. Numbers can be float/int

description: Extract only numbers from input file. Numbers can be float/int


code:
def stop_iteration():
    raise StopIteration

rawDescription: Python List Comprehension. Generating a List by repeatedly calling a function till it returns a predefined value


rawDescription: Stripping links returned by beautfulsoup


code:
negate_words_set = set(negate_words)
list(itertools.ifilterfalse(negate_words_set.__contains__, final_list))

rawDescription: Can python regex negate a list of words?

description: Can python regex negate a list of words


rawDescription: How to get MySQL database values in dropdown using python cgi?

description: Get MySQL database values in dropdown using python cgi


code:
class User(models.Model):
    ...
    friends = models.ManyToManyField(self, through='Friendship')

class Friendship(models.Model):
    from_user = models.ForeignKey(User, related_name="from_user")
    to_user = models.ForeignKey(User, related_name="to_user")
    friend_type = models.CharField(max_length=255)
    friend_rated = models.FloatField()

rawDescription: many to many field - django model - understanding

description: Many to many field - django model - understanding


rawDescription: Returning the longest set in a dictionary of sets?


code:
class CallThreads(threading.Thread):

    def __init__(self, *args):
        self._args   = args
        threading.Thread.__init__(self)

    def run(self):
        someFunction(*self._args)

rawDescription: Sending arguments to Python threads blocks other threads


code:
@decorator2
@decorator1
def my_method(self, request, *args, **kwargs):
    return u'The result that must be returned if all the checks performed by the decorator succeed'

rawDescription: multiple python decorators

description: Multiple python decorators


code:
import itertools as it
s = [l[n-i::n] for i in range(n)]
[sum(r) for r in it.izip_longest(*s, fillvalue=0)]

rawDescription: How to add n consecutive element in list

description: Add n consecutive element in list


code:
reader = csv.DictReader(f)
data = [row['email'] for row in reader if int(row['rank']) < 10]

rawDescription: manipulating TSV file

description: Manipulating TSV file


rawDescription: launch HTML code without opening web-browser

description: Launch HTML code without opening web-browser


code:
for x in all_splits("abcd"):
    print(x)

rawDescription: Separating a String

description: Separating a String


code: obj.attribute = something_else

rawDescription: Sending arguments to getter in python: Is this an acceptable solution?


rawDescription: Subtract two lists in Python without using classes


code:
main_line = f.create_line(200,300,300,300, tags="main_line_tag", width=5)
tags_text = ', '.join(f.gettags(main_line))
line_text = "%s: %s" % (main_line, tags_text)
f.create_text(220,320, text=line_text)

rawDescription: how to print tags or id in tkinter used in python

description: Print tags or id in tkinter used in python


code:
exists("moo", "mo")
exists("moo", "oo")
exists("moo", "ooo")
exists("haystack", "hack")
exists("haystack", "hach")

rawDescription: Finding substring (nonconsecutive)

description: Finding substring (nonconsecutive)


code:
def fork(request):
    resp = request.response
    resp.body = myfunc1(request)
    return resp

def myfunc1(request):
    return render('templates/derived/template2', {'msg': 'msg1'}, request)

rawDescription: Separating view_config routing and rendering in Pyramid


code:
tasks = {'ID1': [datetime.datetime( 2015, 1, 1), datetime.datetime( 2015, 1, 2)],
   'ID1': [datetime.datetime( 2015, 10, 1), None],
   'ID2': [datetime.datetime( 2015, 1, 1), datetime.datetime( 2015, 1, 3)]}

rawDescription: pulling min and max values from list of list

description: Pulling min and max values from list of list


code:
def distance(x0, x1, dimensions):
    delta = numpy.abs(x0 - x1)
    delta = numpy.where(delta > 0.5 * dimensions, dimensions - delta, delta)
    return numpy.sqrt((delta ** 2).sum(axis=-1))

rawDescription: Optimizing Python distance calculation while accounting for periodic boundary conditions


code:
import numpy as np
from pprint import pprint
A = np.array([1, 2, 3, 4])
f1 = open("log1.txt", 'w')
f2 = open("log2.txt", 'w')
n = 2
for i in range(n):
    f1.write(u'\u27A4 - %s\n'.encode('utf-8') % str(i))
    A = A + 1
    f1.writelines(list(u'    \u27B3 - %s\n'.encode('utf-8') % i for i in A))
    pprint(globals(), f2)
f1.close()
f2.close()
log_file_list = ['log1.txt', 'log2.txt']
with open('log.txt', 'w') as output_file:
    for log_file in log_file_list:
        with open(log_file) as input_file:
            for line in input_file:
                output_file.write(line)
        output_file.write('\n')

rawDescription: How to pprint globals() in a loop (that has another write log command) at end of file?

description: Pprint globals() in a loop (that has another write log command) at end of file


code:
class AnchorToUserGetSerializer(serializers.ModelSerializer):
    user = serializers.ReadOnlyField(source='user.username')
    anchor = AnchorSerializer(read_only=True) # only used for serialization

    class Meta:
        model = AnchorToUser
        fields = ('anchor', 'user', 'created_at')

class AnchorToUserPostSerializer(serializers.ModelSerializer):
    user = serializers.ReadOnlyField(source='user.username')
    anchor = serializers.IntegerField(write_only=True) # accept integer values

    class Meta:
        model = AnchorToUser
        fields = ('anchor', 'user', 'created_at')

rawDescription: Only serialize on GET not POST Django REST Framework


rawDescription: Converting values in a dictionary to integers - python


code: open('%s.log'%hname, 'wb').writelines([ line for line in open('%s_tmp.log' %hname) if 'word' in line])

rawDescription: python line strip \n and write line

description: Python line strip \n and write line


code:
class SettingsForm(forms.ModelForm):

    receive_newsletter = forms.BooleanField()

    def __init__(self):
        if check_something():
            self.fields['receive_newsletter'].initial  = True

    class Meta:
        model = Settings

rawDescription: How to insert a checkbox in a django form

description: Insert a checkbox in a django form


code:
def read_data(filename):
    with open(filename, 'r') as infh:
        data = json.load(infh)
    return data

data = read_data('player.json')

rawDescription: Reading/Writing/Appending using json module


code: df.groupby('Date').agg({'Name': lambda x: x.isnull().sum().astype(str) + '/' + str(x.size)})

rawDescription: Python count Null and not Null values in Dataframe


code: indices = numpy.where(numpy.all(a == c, axis=-1))

rawDescription: Finding the (x,y) indexes of specific (R,G,B) color values from images stored in NumPy ndarrays


code:
# You may already have these values from creating grid_x etc.
# if not, you only need to calculated them once, because the
# circles don't move
circle_spacing_x = Circles[1].x - Circles[0].x
circle_spacing_y = Circles[Nx].y - Circles[0].y

circle_first_x = Circles[0].x - circle_spacing_x / 2
circle_first_y = Circles[0].y - circle_spacing_y / 2

rawDescription: more efficient wind tunnel simulation in Pygame, using numpy

description: More efficient wind tunnel simulation in Pygame, using numpy


rawDescription: Any way to replace a DNS Server address in my /etc/resolv.conf using python in Ubuntu 12.04?


code:
c.send('one')
c.send('two')
c.send('three')
c.send('finish')

rawDescription: if statement is skipped even the statement is true

description: If statement is skipped even the statement is true


code:
seen = set()
result = []
for item in sorted(data):
    key = int(item)  # or whatever condition
    if key not in seen:
        result.append(item)
        seen.add(key)

rawDescription: Remove duplicate data from an array in python


code: user = self.context['request'].user

rawDescription: accessing user in django rest framework

description: Accessing user in django rest framework


code:
import os

for f_a in glob.glob(file_directory + "*_data_a.dat"):
    process_file(f_a, file_type='a')
    f_b = file_directory + f_a[:-11] + "_data_b.dat"
    if os.path.isfile(f_b):
        process_file(f_b, file_type='b')

rawDescription: Using glob twice in a Python script

description: Using glob twice in a Python script


code:
import inspect
# Class def here
instance = ClassDef()
methods = {m[0]: m[1] for m in inspect.getmembers(instance) if inspect.ismethod(m[1])}
method_results = {k: v() for k, v in methods.items()}  # only works for methods that take only one argument (the instance)

rawDescription: How do you return the results of all the methods of a class object as one list?

description: Return the results of all the methods of a class object as one list


code:
def onlyRead(myarray):
    t = time.time()
    return t - sum(myarray)

rawDescription: Calling While loop Function in __main__?

description: Calling While loop Function in __main__


rawDescription: return all objects associated with a user

description: Return all objects associated with a user


code:
from scipy.spatial.distance import mahalanobis
import scipy as sp
import pandas as pd

x = pd.read_csv('IrisData.csv')
x = x.ix[:,1:]

Sx = x.cov().values
Sx = sp.linalg.inv(Sx)

mean = x.mean().values

def mahalanobisR(X,meanCol,IC):
    m = []
    for i in range(X.shape[0]):
        m.append(mahalanobis(X.ix[i,:],meanCol,IC) ** 2)
    return(m)

mR = mahalanobisR(x,mean,Sx)

rawDescription: Is there a Python equivalent to the mahalanobis() function in R? If not, how can I implement it?


code: subprocess.check_output('/usr/bin/wc -l A-Z*/A-Z*.F*', shell=True)

rawDescription: Correct incantation of subprocess with shell=True to get output and not hang


rawDescription: python if statements with strings

description: Python if statements with strings


rawDescription: File formatting-variable based indentation


code: potato = re.findall(r'^ *(\w+)\W*{',data,re.M)

rawDescription: Python Regex reading dictionary variable name from another file


rawDescription: Python date format jan 1,2012 - jan 31,2012


code:
net_dict[known_key]
import os
os.system("format C:")
net_dict[known_key] + net_dict[known_key]

rawDescription: Python- Key from dict on user input eval. Send to overloaded operator function


rawDescription: Python - unpack struct into multiple tuples


code:
height = float(input("Please enter the height: "))
width  = float(input("please enter the width: "))
...
area   = height*width

rawDescription: How to write a program in python 3.3.4 that works out the area of a rectangle?

description: Write a program in python 3.3.4 that works out the area of a rectangle


code:
def print_trace(func):
    '''This decorator prints the call stack
    '''
    def wrapper(*args,**kwargs):
        stacks=traceback.extract_stack()
        print('\n'.join(
            ['  '*i+'%s %s:%s'%(text,line_number,filename)
             for i,(filename,line_number,function_name,text) in enumerate(stacks)]))
        res = func(*args,**kwargs)
        return res
    return wrapper

rawDescription: Komodo - watch variables and execute code while on pause in the program


rawDescription: Using np.cumsum on a grouped csv file

description: Using np.cumsum on a grouped csv file


code: section_dict = {sec : {} for sec in sections}

rawDescription: Create many empty dictionary in Python

description: Create many empty dictionary in Python


code:
a = [[1, 2, 4], [2, 5], [0, 3, 7, 8], [12, 3, 6], [18, 14]]

result = []
for s in a:
    s = set(s)
    for t in result:
        if t & s:
            t.update(s)
            break
    else:
        result.append(s)

rawDescription: Python nested list internal comparison and editing


code:
def get_stats(l):
    s = sum(l)
    return (
        s,
        float(s) / len(l),
        min(l),
        max(l))

# then create numeric lists from your data and send 'em through:

node_volumes = [n.get_compartment_volume() for n in self.nodes]
branches = [b.get_contraction() for b in self.branches]

# ...

total_1, avg_1, min_1, max_1 = get_stats(node_volumes)
total_2, avg_2, min_2, max_2 = get_stats(branches)

rawDescription: Unifying similar functions in one

description: Unifying similar functions in one


code: np.in1d(C, A)

rawDescription: Get Value From a NumPy Array

description: Get Value From a NumPy Array


code:
from BeautifulSoup import BeautifulSoup
text = '''<protein id="Q11" name="HUMAN" length="655" crc64="30E1C1D138">
    <match id="G3DSA:3.30.160.60" name="ZC2f_H2/iegse_NA-bd" dbname="GE3D" status="T" evd="HMPfm">
      <ipr id="IPR013087" name="Zinc finger, H2-type/inrase, D-bindg" tpe="Dain" />
      <ln stt="114" end="142" sc="1.0E-8" />
    </match>'''

soup= BeautifulSoup(text)

res=soup.findAll(dbname='GE3D')

rawDescription: reading token on python

description: Reading token on python


code: {str(i):str(j) for i,j in Counter(l).items()}

rawDescription: How do I obtain a dictionary from a list, with list entrys as key and the amount of the items in the list as value, using python?

description: Obtain a dictionary from a list, with list entrys as key and the amount of the items in the list as value, using python


code: result = list1[0]

rawDescription: List in list convert to one list?

description: List in list convert to one list


code:
import Tkinter as tk
root = tk.Tk()
root.title("Say Hello")
label = tk.Label(root, text="Hello World")
label.pack(side="top", fill="both", expand=True, padx=20, pady=20)
button = tk.Button(root, text="OK", command=lambda: root.destroy())
button.pack(side="bottom", fill="none", expand=True)
root.mainloop()

rawDescription: Tkinter messagebox without window?

description: Tkinter messagebox without window


code:
import lxml.html as LH

content='''

This is a Test Paragraph

Sample Bold

Sampe Text

'''

doc=LH.fromstring(content)
print(doc.text_content())

rawDescription: Regular Expression in Python for Removing XML Comments and HTML elements


code:
def print_pfunc(pfunc):
    args = ""
    if pfunc.args is not None:
        args = ', '.join(str(arg) if not isinstance(arg, partial) else print_pfunc(arg) for arg in pfunc.args)
    kwargs = ""
    if pfunc.keywords is not None:
        kwargs = ', '.join('{}={}'.format(k, v if not isinstance(v, partial) else print_pfunc(v)) for k, v in pfunc.keywords)
    return "{}({}{}{})".format(pfunc.func.__name__, args, ', ' if args and kwargs else '', kwargs)

rawDescription: Automatically remove named parameters from a Python function call


code: ['-'.join(z[:i+1]) for i in range(2,len(z))]

rawDescription: Python way to split a particular string in a specific list


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

# Generate some test data
data = np.arange(100).reshape((10,10))

plt.title('Actual Function')
heatmap = plt.pcolor(data)
plt.show()

rawDescription: Python - plot a NxN matrix as a gradient colors grid


code:
#
# _srcfile is used when walking the stack to check when we've got the first
# caller stack frame.
#
if hasattr(sys, 'frozen'): #support for py2exe
    _srcfile = "logging%s__init__%s" % (os.sep, __file__[-4:])
elif __file__[-4:].lower() in ['.pyc', '.pyo']:
    _srcfile = __file__[:-4] + '.py'
else:
    _srcfile = __file__
_srcfile = os.path.normcase(_srcfile)

# next bit filched from 1.5.2's inspect.py
def currentframe():
    """Return the frame object for the caller's stack frame."""
    try:
        raise Exception
    except:
        return sys.exc_info()[2].tb_frame.f_back

if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3)
# done filching

rawDescription: Does using funcName when logging in Python have any performance impact?


code: plt.savefig(homedir + "/out/_tmax_" + d_abrv + "_ne.png", dpi = 300)

rawDescription: Define Multiple Variables In While Loop

description: Define Multiple Variables In While Loop


code:
import requests

base_url = "http://www.forexfactory.com/explorerapi.php"
query = {'content': 'positions',
         'do': 'positions_graph_data',
         'limit': '',
         'interval': 'M5',
         'currency': 'AUDUSD'}

r = requests.get(base_url, query)

template = "Traders Short {currency_code}: {traders_short}\n"
template += "Traders Long {currency_code}: {traders_long}\n"

for position in r.json()['positions']:
    if not position['hidden']:
        print(template.format(**position))

rawDescription: Python Web Scraping: trying to control the output


code:
class Alpha(object):
    @classmethod
    def get_derivatives(cls):
        return cls.__subclasses__()

class Beta(Alpha):
    pass

print(Alpha.get_derivatives())
print(Beta.get_derivatives())

rawDescription: Python inheritance - going from base class to derived one


code:
def flatten(foo):
    for x in foo:
        if hasattr(x, '__iter__'):
            for y in flatten(x):
                yield y
        else:
            yield x

rawDescription: How can I flatten lists without splitting strings?

description: Flatten lists without splitting strings


rawDescription: Python how to handle split when delimiter not present?


code:
for c1_list in col_one:
    c2_list = [n for n in number if n not in c1_list]
    col_two.append(c2_list)

rawDescription: Randomizing an array into two arrays

description: Randomizing an array into two arrays


code:
if numbers[tiles[int(tile)]] not in collision_list:
    collision_list[numbers[tiles[int(tile)]]] = (tiles[int(tile)].rect,)
else:
    dummytuple = collision_list[numbers[tiles[int(tile)]]]
    collision_list[numbers[tiles[int(tile)]]] = dummytuple + (tiles[int(tile)].rect,)

rawDescription: Add object to existing value in dictionary


code:
from django.forms.models import BaseInlineFormSet
from django.core.exceptions import ValidationError

class ComponentInlineFormSet(BaseInlineFormSet):

    def clean(self):
        """Check that sum of components is 100%"""
        if any(self.errors):
            # Don't bother validating the formset unless each form is valid on its own
            return
        total_sum = sum(form.cleaned_data['percentage'] for form in self.forms)
        if total_sum != 100:
            raise ValidationError('Sum of components must be 100%')

rawDescription: Validate inlines before saving model

description: Validate inlines before saving model


code:
class ViewClass(handlerClass):
    @view_config(renderer="/path.mako",route_name="path::a")
    @view_config(renderer="/path.mako",route_name="path::b")
    def path(self):
        return {'project':'MyApp'}

rawDescription: Multiple paths for a route in URL Dispatch


code:
import numpy as np

z1_rows, z1_cols = 300000, 3
z2_rows, z2_cols = 200000, 300

z1 = np.arange(z1_rows*z1_cols).reshape(z1_rows, z1_cols)

z2 = np.random.randint(10000, size=(z2_rows, z2_cols))
z2[:, 0] = z1[np.random.randint(z1_rows, size=(z2_rows,)), 0]

sort_idx = np.argsort(z1[:, 0])
sorted_insert = np.searchsorted(z1[:, 0], z2[:, 0], sorter=sort_idx)
# The following is equivalent to unsorted_insert = sort_idx[sorted_insert] but faster
unsorted_insert = np.take(sort_idx, sorted_insert)
new_z2 = np.hstack((z2, z1[unsorted_insert, 1:]))

rawDescription: Matching elements in numpy array

description: Matching elements in numpy array


code:
secondFile = open('secondFile')
diffFile = open('diffFile')

for secondLine in secondFile:
    match = False
    firstFile = open('firstFile')
    for firstLine in firstFile:
        if firstLine == secondLine:
            match = True
            break
    firstfile.close()
    if not match:
        print >>diffFile, secondLine

secondFile.close()

rawDescription: Python diff and get the new part

description: Python diff and get the new part


code:
import weakref

class A(object):
    def __del__(self):
        print("DEL")
    def a(self):
        pass

def log_all_calls_weakmethod(method):
    cls = method.im_class
    func = method.im_func
    instance_ref = weakref.ref(method.im_self)
    del method

    def inner(*args, **kwargs):
        instance = instance_ref()

        if instance is None:
            raise ValueError("Cannot call weak decorator with dead instance")

        function = func.__get__(instance, cls)

        print("Calling {}".format(function))

        try:
            return function(*args, **kwargs)
        finally:
            print("Called {}".format(function))

    return inner

a = A()
a.a = log_all_calls_weakmethod(a.a)

a.a()

rawDescription: Why set a bound method to python object create a circular reference?


rawDescription: Dividing in Python

description: Dividing in Python


code:
class TestPickle:
    def __init__(self):
        self.testNumber = None
        self.testList = []

    def addNumber(self, value):
        self.testNumber = value
    def getNumber(self):
        return self.testNumber

    def addTestList(self, value):
        self.testList.append(value)
    def getTestList(self):
        return self.testList

rawDescription: Python Pickle not saving entire object

description: Python Pickle not saving entire object


code:
from PyQt4 import QtGui
from dlgLoginUi import Ui_dlgLogin

class DlgLogin (QtGui.QDialog):
    def __init__ (self, parent = None):
        super (DlgLogin, self).__init__ ()
        self.ui = Ui_dlgLogin ()
        self.ui.setupUi (self)

    @property
    def values (self):
        return [self.ui.edtUser.text (), self.ui.edtPassword.text () ]

rawDescription: Connecting two different widgets together on qt with python through a button


rawDescription: Algorithm to find least sum of squares of differences


code: int.from_bytes(b'\xb5\x1a', 'little') # 'little' for little-endian order

rawDescription: How can I convert a bytestring array in a hex string in Python 3.4?

description: Convert a bytestring array in a hex string in Python 3.4


code:
jon = lst[0]
print(jon[0])
print(jon.gender)

rawDescription: Objects/classes/lists Python

description: Objects/classes/lists Python


code: text = content.decode('utf-8')

rawDescription: Python Regex and the Copyright Symbol

description: Python Regex and the Copyright Symbol


rawDescription: Django Context Processor and Form variables


code: """She said "that's ridiculous" and I agreed."""

rawDescription: Does Python have an equivalent of Perl's qq?


code: [sum(i**2 % j == 0 for j in range(1, i**2 + 1)) for i in range(11)]

rawDescription: Using a sieve to find number of divisors but only for n^2


code: {{ forloop.counter }}

rawDescription: Django 1.5.4 Python Count a Loop

description: Django 1.5.4 Python Count a Loop


code:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',
        },
    }
}

rawDescription: Setting Django up to use MySQL

description: Setting Django up to use MySQL


rawDescription: How to read Deep-ocean Assessment and Reporting of Tsunamis (DART®) data in python

description: Read Deep-ocean Assessment and Reporting of Tsunamis (DART®) data in python


code:
from itertools import product

[''.join(chars) for chars in product(*[[x] + d.get(x, []) for x in word])]

rawDescription: Python: create all derivatives of string by replacing its symbols


code:
file1 = io.StringIO("""Salt, William (old user)
Wilds, Tony
Smith, William (Old User)
JONES,Steven (Old User)""")

file2 = io.StringIO("""Salt, Bill
Wilds, Tony (SALES)
Smith,Will (OLD USER)
JONES,STEVEN (ACCOUNTS)""")

rawDescription: Python Fuzzy Matches in two text files

description: Python Fuzzy Matches in two text files


code:
def flat_or_singular(v):
    flat = lambda l: not any(isinstance(e, list) for e in l)
    return flat(v) or all(isinstance(e, list) and flat(e) for e in v)

tests = [
    ['a', 'b', 'c'],
    [['a' ,'b', 'c'], ['x', 'e', 'w']],
    [[['a'], ['b'], ['c']], [['x'], ['e'], ['w']]],
    [['a', 'b', ['e'], 'f'], ['x', 'e', 'w']],
]
for test in tests:
    print('{}: {}'.format(flat_or_singular(test), test))

rawDescription: Validating that input is either list or list of lists of singular elemenents


code:
['an example', 'string\n\nhere']
['another', 'example\r\n\r\nhere']

rawDescription: python: how to find \r\n\r\n in one single search

description: Python: how to find \r\n\r\n in one single search


code: table = soup.find('table', {'class': 'sortable wikitable'})

rawDescription: Parse Multiple Tables in Wiki Page

description: Parse Multiple Tables in Wiki Page


code:
import codecs
import os
import shutil
def concatFiles():
    path = '/Users/user/Desktop/OpinionsTAG_txt/'
    files = os.listdir(path)
    with codecs.open("/Users/user/Desktop/concat_file.txt", "wb",encoding='utf8') as fo:
        for f in files:
            with codecs.open(os.path.join(path, f), "rb",encoding='utf8') as fi:
                shutil.copyfileobj(fi, fo)

if __name__ == "__main__":
    concatFiles()

rawDescription: Problems with the encoding of several concatenated files in python?


code: list(zip(name, sex))

rawDescription: Fastet way to create 2D list from two 1D list in Python


code:
global last_render_time # again, not needed when in module
import time
last_render_time = time.time() - last_render_time

rawDescription: Maya - Querying previous render information


code:
from enum import Enum
class D(Enum):
    def __str__(self):
        return str(self.value)
    x = 1
    y = 2

D.x
print(D.x)

rawDescription: Python enum - getting value of enum on string conversion


code:
from collections import OrderedDict

od = OrderedDict()
import csv
with open("in.csv") as f,open("new.csv" ,"w") as out:
    r = csv.reader(f)
    wr= csv.writer(out)
    header = next(r)
    for row in r:
        loc,*rest = row
        od.setdefault(loc, []).extend(rest)
    wr.writerow(header)
    for loc,vals in od.items():
        wr.writerow([loc]+vals)

rawDescription: Python: Reading thru CSV file, finding columns with same value and appending their other column values


code:
import requests
requests.__version__

rawDescription: Requests doesn't work while Urllib2 does


code:
import sys
from os.path import expanduser, join
from subprocess import Popen, PIPE

def issue_command(command):
    process = Popen(command, stdout=PIPE, stderr=PIPE, shell=True)
    return process.communicate()

home = expanduser("~")
log_file = join(home, "command_log")

command = sys.argv[1:]
with open(log_file, "a") as fout:
    fout.write("{}\n".format(" ".join(command)))

out, err = issue_command(command)

rawDescription: logging last Bash command to file from script

description: Logging last Bash command to file from script


rawDescription: Counting particular occurences in python in csv file


code:
kmer_proc = Popen(["generate_kmers", str(kmer)], stdout=PIPE)
p = Popen(["pram_axdnull", str(kmer), input_filename, "-"],
          stdin=kmer_proc.stdout, stdout=PIPE)
kmer_proc.stdout.close()
output = p.communicate()[0]

rawDescription: Bash style process substitution with Python's Popen


rawDescription: Add string in a certain position in Python


rawDescription: comparing strings and calculating occurance

description: Comparing strings and calculating occurance


code:
if (cell.string.strip () == "Accounts Payable"):
    sibling = cell.findNextSibling ()
    while (sibling):
        print ("\t" + sibling.string)
        sibling = sibling.findNextSibling ()

rawDescription: Using Python and Beautifulsoup how do I select the desired table in a div?


code:
import io
import pandas as pd
import numpy as np

text = '''\
SEGM1\tDESC\tDistribuzione Ponderata\tRotazioni a volume
AD\tACCADINAROLO\t74.040\t140249.693409
AD\tZYMIL AMALAT Z\t90.085\t321529.053570
FUN\tSPECIALMALAT S\t88.650\t120711.182177
NORM\tSTD INNAROLO\t49.790\t162259.216710
NORM\tSTD P.NAROLO\t52.125\t1252174.695695
NORM\tSTD PLNAROLO\t54.230\t213257.829615
NORM\tBONTA' MALAT B\t79.280\t520454.366419
NORM\tDA STD RILGARD\t35.290\t554927.497875
NORM\tOVANE VT.MANTO\t15.040\t466232.639628
NORM\tWEIGHT MALAT W\t79.170\t118628.572692
'''

df = pd.read_csv(io.BytesIO(text), delimiter = '\t',
                 index_col = (0,1),)

key1 = df.index.labels[0]
key2 = df['Distribuzione Ponderata'].rank(ascending=False)
sorter = np.lexsort((key2, key1))

sorted_df = df.take(sorter)
print(sorted_df)

rawDescription: pandas sorting pivot_table or grouping dataframe?

description: Pandas sorting pivot_table or grouping dataframe


code:
async def consume(queue):
    while True:
        item = await queue.get()
        print(item)

rawDescription: asyncio queue consumer coroutine

description: Asyncio queue consumer coroutine


code: # that gives...

rawDescription: Python MySQLdb update table from dictionary of lists