code:
from datetime import datetime
from pprint import pprint
text = '''\
#### 8/23/05
Defining the World (Hitchings)
#### 8/26/05
Lost Japan
#### 9/5/05
The Kite Runner
*The Dark Valley (Brendon)*
#### 9/9/05
Active Liberty
'''.splitlines(True)
current_date = None
results = []
for line in text:
    line = line.strip()
    if not line:
        continue
    if line.startswith('#'):
        current_date = datetime.strptime(line.strip('# '), '%m/%d/%y').date()
        continue
    entry = {'date': current_date, 'read': False}
    if line.startswith('*') and line.endswith('*'):
        # previously read
        line = line.strip('*')
        entry['read'] = True
    entry['title'] = line
    results.append(entry)

pprint(results)

rawDescription: Odd Behaviour of Loop in Python

description: Odd Behaviour of Loop in Python


code:
for x in range(0, len(xls.sheet_names)):
    a = xls.parse(x,header = 4, parse_cols = 'B:AJ')
    a["Sheet Name"] = [xls.sheet_names[x]] * len(a)
    df = df.append(a)

rawDescription: How to read Excel Workbook (pandas)

description: Read Excel Workbook (pandas)


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

class LineBuilder:
    def __init__(self, line,ax,color):
        self.line = line
        self.ax = ax
        self.color = color
        self.xs = []
        self.ys = []
        self.cid = line.figure.canvas.mpl_connect('button_press_event', self)
        self.counter = 0
        self.shape_counter = 0
        self.shape = {}
        self.precision = 10

    def __call__(self, event):
        if event.inaxes!=self.line.axes: return
        if self.counter == 0:
            self.xs.append(event.xdata)
            self.ys.append(event.ydata)
        if np.abs(event.xdata-self.xs[0])<=self.precision and np.abs(event.ydata-self.ys[0])<=self.precision and self.counter != 0:
            self.xs.append(self.xs[0])
            self.ys.append(self.ys[0])
            self.ax.scatter(self.xs,self.ys,s=120,color=self.color)
            self.ax.scatter(self.xs[0],self.ys[0],s=80,color='blue')
            self.ax.plot(self.xs,self.ys,color=self.color)
            self.line.figure.canvas.draw()
            self.shape[self.shape_counter] = [self.xs,self.ys]
            self.shape_counter = self.shape_counter + 1
            self.xs = []
            self.ys = []
            self.counter = 0
        else:
            if self.counter != 0:
                self.xs.append(event.xdata)
                self.ys.append(event.ydata)
            self.ax.scatter(self.xs,self.ys,s=120,color=self.color)
            self.ax.plot(self.xs,self.ys,color=self.color)
            self.line.figure.canvas.draw()
            self.counter = self.counter + 1

def create_shape_on_image(data,cmap='jet'):
    def change_shapes(shapes):
        new_shapes = {}
        for i in range(len(shapes)):
            l = len(shapes[i][1])
            new_shapes[i] = np.zeros((l,2),dtype='int')
            for j in range(l):
                new_shapes[i][j,0] = shapes[i][0][j]
                new_shapes[i][j,1] = shapes[i][1][j]
        return new_shapes
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_title('click to include shape markers (10 pixel precision to close the shape)')
    line = ax.imshow(data)
    ax.set_xlim(0,data[:,:,0].shape[1])
    ax.set_ylim(0,data[:,:,0].shape[0])
    linebuilder = LineBuilder(line,ax,'red')
    plt.gca().invert_yaxis()
    plt.show()
    new_shapes = change_shapes(linebuilder.shape)
    return new_shapes

img = np.zeros((100,100,3),dtype='uint')
shapes = create_shape_on_image(img)[0]
print(shapes)

rawDescription: Python : Mouse click coordinates as simply as possible


code:
import numpy
timeit(hugeequal1, hugeequal2, 10000)
timeit(numpy.array(hugeequal1), numpy.array(hugeequal2), 10000)

rawDescription: Is there a faster way to test if two lists have the exact same elements than Pythons built in == operator?


code: [elem for elem in root.findall('parent') if elem.find('child').text.startswith('foo')]

rawDescription: Find non-root parent node where child contains some text


code:
class Example:
    def __init__(self):
        self.var=0 # or you can directly give self.var=10
        self.example()
    def example(self):
        self.var=10

if __name__=='__main__':
    E=Example()
    # In this case, the attribute  var is not instantiated
    try:
        attr=getattr(E,"var")
        print(attr) # <-- it does not exist even if E instantiated Example class
    except AttributeError:
        print("Object not having this attribute")

rawDescription: Why object's attributes are not there when the class is instantiated?


rawDescription: understanding range in python for loop

description: Understanding range in python for loop


rawDescription: Python 2.7: get the size of a file just from its handle (and not its path)


rawDescription: python separating element in a list

description: Python separating element in a list


code:
regex = re.compile(r'''
    [\S]+:                # a key (any word followed by a colon)
    (?:
    \s                    # then a space in between
        (?!\S+:)\S+       # then a value (any word not followed by a colon)
    )+                    # match multiple values if present
    ''', re.VERBOSE)

matches = regex.findall(my_str)

rawDescription: Regex: How to match sequence of key-value pairs at end of string


code: np.dot(V_over_WH.T, W).T

rawDescription: non-negative matrix factorization failing to converge

description: Non-negative matrix factorization failing to converge


rawDescription: Setup POST HTTP Request to create variable .vnc file


code: csv2 = {int(n) for n in csv2}

rawDescription: Converting set of string values to numeric values


code:
response_results = [THEAD(TR(TH('Row #'), TH('Col 1'), TH('Col 2'), TH('Col 3')), _id=0)]

row_one = ['1', 'Col 11', 'Col 12', 'Col 13']
response_results.append(TR(row_one))

row_two = ['2', 'Col 21', 'Col 22', 'Col 23']
response_results.append(TR(row_two))

html = DIV(TABLE(response_results, _id='records_table', _class='table table-bordered'),
           _class='table-responsive')

rawDescription: Web2Py - using starred expression for rendering HTML table


code:
import lxml.etree as le
import io

content='''\
<foo><X><Y>skip this</Y><Y><Z name="apple"><W>not here</W></Z>
<Z name="bacon"><W>42b<C>c</C></W><W>256b<C>c</C></W></Z>
<Z name="bacon"><W>42b<C>c</C></W><W>256b<C>c</C></W></Z>
</Y></X></foo>
'''
doc=le.parse(io.BytesIO(content))
# print(le.tostring(doc, pretty_print=True))
result=[]
Zs=doc.xpath('//X/Y[2]/Z[@name="bacon"]')
for Z in Zs:
    Ws=Z.xpath('W')
    record=[]
    assert(len(Ws)==2)  #<--- Change to 9
    abc=Ws[0].xpath('descendant::text()')
    # print(abc)
    # ['42', 'b', 'c']
    assert(abc[0] == '42')
    record.append(' '.join(abc))
    abc=Ws[1].xpath('descendant::text()')
    assert(abc[0] == '256')
    result.append(record)
print(result)
# [['42 b c'], ['42 b c']]

rawDescription: Switching from amara to lxml in Python

description: Switching from amara to lxml in Python


code:
clf= SVR(C=1.0)
clf.fit(race_encoded, income)

rawDescription: Using Scikit-Learn's SVR, how do you combine categorical and continuous features in predicting the target?


rawDescription: Merging Two Outer Lists Based on Iterated Inner List Value


code:
def somefunc(a):
    a += 1
    a /= 15

a = numpy.random.random(10)
b = a
somefunc(a)
a
b

rawDescription: how to speed up enumerate for numpy array / how to enumerate over numpy array efficiently?

description: Speed up enumerate for numpy array / how to enumerate over numpy array efficiently


code:
import webbrowser

webbrowser.open('https://www.schwab.com/')

rawDescription: What is the proper way I can invoke firefox from a python3 program?


code:
class LoginForm(forms.Form):
    email = forms.CharField()
    password = forms.PasswordField()

    def clean(self):
        email = self.cleaned_data.get('email', None)
        password = self.cleaned_data.get('password', None)
        self.u = authenticate(email, password) # set the user as an instance variable
        if self.u is None:
            raise forms.ValidationError(ERROR_MSG)
        if not self.u.is_active:
            raise forms.ValidationError(ERROR_MSG)

rawDescription: Django User Authentication and Login with DRY


code: return machine_hand, player_hand, who_win

rawDescription: Accessing variables outside a function in Python


code:
def foo(func, iterable):
    return [func(i) for i in iterable]
import dis; dis.dis(foo)

rawDescription: Python 3: Most efficient way to create a [func(i) for i in range(N)] list comprehension


code:
import sys

def pattern(n):
    'prints the nth pattern'
    if n == 0:    # base case
        print(0, end=' ')
    else:    #recursive step: n > 0
        pattern(n-1)         # print n-1st pattern
        print(n, end=' ')    # print n
        pattern(n-1)         # print n-1st pattern
    sys.stdout.flush()

rawDescription: Using print() inside recursive functions in Python3


code:
f = open("test.json" , "w+")
f.seek(last_position)
f.read() # now this will start reading from last position

rawDescription: Parsing the json file after a specific time interval


code:
with open('example') as f:
    lists = [[], []]
    for i,line in enumerate(f):
        lists[i%2].append(line.strip())

print(lists[0])  # ['Item 1', 'Item 3', 'Item 5']
print(lists[1])  # ['Item 2', 'Item 4']

rawDescription: Append every other line from a text file? (Python)


code:
for ser in OpenPorts:
       ser.close()

rawDescription: Is it possible to make multiple instances of serial.Serial() in pyserial?


code:
def gen_tuples(m, n):
    if m == 0:
        yield ()
    else:
        for x in range(n, -1, -1):
            for sub_result in gen_tuples(m-1, n-x):
                yield (x,)+sub_result

rawDescription: Formulation of a recursive solution (variable for loops)


code:
from multiprocessing import Process

def run_server():
    app.run()

server = Process(target=app.run)
server.start()
# ...
server.terminate()
server.join()

rawDescription: How to stop flask application without using ctrl-c

description: Stop flask application without using ctrl-c


code:
import moviepy.editor as mp
messages = ["Dog", "Cat", "Duck", "Wolf"]
clips = [ mp.TextClip(txt, fontsize=170, color='green').set_duration(1)
          for txt in messages ]
concat_clip = mp.concatenate_videoclips(clips, method="compose")
concat_clip.write_videofile("texts.mp4")

rawDescription: How to concatenate videos in moviepy?

description: Concatenate videos in moviepy


code:
import random
import timeit

old_list = [ random.randint(0, 100000) for i in range(0, 100) ]

def floop(old_list):
    new_list = []
    for value in old_list:
        new_list.append(value)
    return new_list

def lcomp(old_list):
    new_list = [ value for value in old_list ]
    return new_list

if __name__=='__main__':
    results_floop = timeit.Timer('floop(old_list)', "from __main__ import floop, old_list").timeit()
    results_lcomp = timeit.Timer('lcomp(old_list)', "from __main__ import lcomp, old_list").timeit()
    print("Function\t\tSeconds elapsed")
    print("For loop\t\t{}".format(results_floop))
    print("List comp\t\t{}".format(results_lcomp))

rawDescription: Which method is faster for Python iterating?


code: numbers = list(range(k+1))   # For Python 2, it is just range(k+1).

rawDescription: python: how can i create a list of integers,to a number?

description: Python: how can i create a list of integers,to a number


code:
find_inside(10, 0)
find_inside(3456, 98)
find_inside(4589678, 58)
find_inside(10, 1)

rawDescription: Find a number in a another number

description: Find a number in a another number


code:
c = Control(0x1234)
hex(c.low)
hex(c.high)
c.low=56
hex(c.word)
c.low=0x56
hex(c.word)
c.high = 0x78
hex(c.word)
c.word = 0xFE0A
c.low
c.high

rawDescription: Creating pythonic objects that share memory


code:
t = np.arange(0, edges.shape[1], 1)
plt.figure(2, figsize=(8, 16))
ax1 = plt.subplot(211)
ax1.imshow(edges,cmap = 'gray')
ax2 = plt.subplot(212)
ax2.axis([0, edges.shape[1], edges.shape[0], 0])
ax2.plot(t, f(t))
plt.show()

rawDescription: OpenCV: fit the detected edges

description: OpenCV: fit the detected edges


code:
i = 8
for item in new_array:
    my_list[i] = item # you want to replace the value
    i += 1            # you forgot to increment the variable

rawDescription: Python - insert into list

description: Python - insert into list


rawDescription: How Do I Get Unique IDs Efficiently in Python?


code:
l = [1,2,3,4,5]
m = [1,2,3]
l = m[::-1]
l
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
m = l[:] #creates a shallow copy
l[0].pop(1) # a mutable object inside l is changed, it affects both l and m
l
m

rawDescription: What is the difference between a[:]=b and a=b[:]


code:
plt.scatter(df_pos.kipp_macht, df_pos.luftb_hydgr_add, 'b+', label='pos')
plt.scatter(df_neg.kipp_macht, df_neg.luftb_hydgr_add, 'rx', label='neg')

rawDescription: Ploting matrix in matplotlib, while taking indexed data for positive and negative values, returns wrong plot axis or data


rawDescription: Strip URL - Python

description: Strip URL - Python


rawDescription: Can the value of both the current and next item be accessed in a Python list comprehension?


code:
import pandas as pd

df = pd.read_csv('wordlist.csv')
words = list(df.word)
meaning = dict( zip( df.word, df.meaning ) )

rawDescription: Creating a dictionary

description: Creating a dictionary


code:
# group A
group_a = list()
for i in xrange(100):
    wid = random.randint(120,320)
    pos = [random.randint(0, WIDTH-wid), random.randint(build_lvl-20, build_lvl), wid]
    new_shelf = Shelf(pos[0], pos[1], pos[2])
    group_a.append(new_shelf)
    build_lvl = build_lvl - 60
all_shelfs.add(group_a)

rawDescription: Deleting/Removing the first N or last N from a sprites.Group()


code:
def nested_list(depth):
  return [nested_list(depth - 1)] if depth else []

rawDescription: Python: initialise list of list of list of ... etc


code:
now = datetime.datetime.utcnow()
now.strftime("%m/%d/%Y")

rawDescription: Can't seem to find success with datetime python2.7


rawDescription: Python Numpy: how to count the number of true elements in a bool array


rawDescription: How to use related fields (fields.related) in odoo-8?

description: Use related fields (fields.related) in odoo-8


code:
A = np.random.randn(100, 2)
B = np.array([2,0]) + 0.5 * np.random.randn(100, 2)
C = 0.5 * np.random.randn(100, 2)
D = np.array([5,0]) + 0.5 * np.random.randn(100, 2)

rawDescription: Finding a partial or complete inclusion of a set of points in convex hull of other set of points in 2D in python


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

rawDescription: How can I obtain the element-wise logical NOT of a pandas Series?

description: Obtain the element-wise logical NOT of a pandas Series


rawDescription: How to expose model methods to django-rest-framework

description: Expose model methods to django-rest-framework


code:
def __cmp__(self, other):
    return cmp(self.intAttribute, other.intAttribute)

rawDescription: How to make heapq evaluate the heap off of a specific attribute?

description: Make heapq evaluate the heap off of a specific attribute


code:
import ast
q = DBReports.objects.all().filter(name__contains = name1)
q = (q.values_list(columnName))
users_list = ast.literal_eval(q[0][0])

rawDescription: Placing 2D Array from PostgreSQL Database into 2d List Python using Django Interface


code:
dic1 = [{'Age': 8, 'Pets Name': 'Felix', 'Species': 'Cat'}, {'Age': 57, 'Pets Name': 'Michelangelo', 'Species': 'Tortoise'}, {'Age': 12, 'Pets Name': 'Rantanplan', 'Species': 'Dog'}, {'Age': '2', 'Pets Name': 'Nemo', 'Species': 'Fish'}, {'Age': '45', 'Pets Name': 'Leonardo', 'Species': 'Tortoise'}, {'Age': 9, 'Pets Name': 'Milo', 'Species': 'Dog'}, {'Age': 57, 'Pets Name': 'Raphael', 'Species': 'Tortoise'}, {'Age': '4', 'Pets Name': 'Dory', 'Species': 'Fish'}]
dic2 = [{'Pets Names': 'Michelangelo', "Owner's Names": 'Ana'}, {'Pets Names': 'Dory', "Owner's Names": 'Eva'}, {'Pets Names': 'Rantanplan', "Owner's Names": 'Ada'}, {'Pets Names': 'Leonardo', "Owner's Names": 'Ana'}, {'Pets Names': 'Felix', "Owner's Names": 'Eva'}, {'Pets Names': 'Raphael', "Owner's Names": 'Ana'}, {'Pets Names': 'Nemo', "Owner's Names": 'Eva'}]

def merge_dicts(dic1,dic2):
    dict3= {}
    result = []
    name = [li['Pets Name'] for li in dic1]
    age = [li['Age'] for li in dic1]
    owenrsName = [li["Owner's Names"] for li in dic2]

    for d2 in dic2:

       pname = d2['Pets Names']
       oname = d2["Owner's Names"]

       if oname not in dict3:
            dict3[oname] = []

       for d1 in dic1:
           if d1['Pets Name'] == pname:
               dict3[oname].append(d1['Age'])
    for key,value in dict3.items():
        result.append({key:value})

    print(result)

merge_dicts(dic1,dic2)

rawDescription: Merge to different dictionaries

description: Merge to different dictionaries


code: x = np.random.randint(0, 9, size=(4, 4, 3)).astype(np.uint8)

rawDescription: Scipy.misc.imread flatten argument -- converting to grey scale


code: random_flipped = np.array([img[flip] for img, flip in zip(a, flips)])

rawDescription: The most effective way to random flip every image in a numpy array


code:
text = "The quick brown fox jumps over the lazy dog."
print('\033[1;32m'+text+'\033[1;m')

rawDescription: Change The Colour Of Python Text

description: Change The Colour Of Python Text


code:
e1 = literal.escape('& < >')
e1
Out[3]: literal(u'& < >')

e2 = literal.escape(e1)
e2
Out[5]: literal(u'& < >')

s = ''.join(e1)
s
Out[7]: u'& < >'

rawDescription: Escaping characters in Python, but ignoring already escaped characters


code:
import re

soup.find_all(text=re.compile('^\s*Text Start:.*'))

rawDescription: Scraping webpage sentences beginning with certain word


code:
from itertools import islice
sum(islice(somelist, k))

rawDescription: Python oneliners: how to sum the first k elements of a list?


code:
import json

my_list = ["hello", "world"]

with open('file.txt', 'w') as f:
    json.dump(my_list, f)

rawDescription: how do i find and replace items in a text file in pyscripter?

description: Find and replace items in a text file in pyscripter


code:
import logging
import threading
import Queue

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG,
                    format='[%(asctime)s %(threadName)s] %(message)s',
                    datefmt='%H:%M:%S')
SENTINEL = object()

def worker(cond, queue):
    for line in iter(queue.get, SENTINEL):
        line = line.strip()
        logger.info(line)
        with cond:
            cond.notify()
            logger.info('notify')

def sprinkler(cond, queue, num_workers):
    with open("big_file") as f:
        for line in f:
            logger.info('advancing filehandle')
            with cond:
                queue.put(line)
                logger.info('waiting')
                cond.wait()
        for _ in range(num_workers):
            queue.put(SENTINEL)

num_workers = 4
cond = threading.Condition()
queue = Queue.Queue()
t = threading.Thread(target=sprinkler, args=[cond, queue, num_workers])
t.start()

threads = [threading.Thread(target=worker, args=[cond, queue])]
for t in threads:
    t.start()
for t in threads:
    t.join()

rawDescription: How to spawn future only if free worker is available

description: Spawn future only if free worker is available


code: from os import name as os_name

rawDescription: python cross platform testing: mocking os.name

description: Python cross platform testing: mocking os.name


code: ['blue', 'yellow', 'blue', 'yellow', 'blue', 'blue', 'yellow', 'yellow', 'blue', 'yellow', 'blue', 'yellow', 'blue']

rawDescription: Python, arranging sequences in 2 combined arrays


code:
import hello
hello.say_hello("World")

rawDescription: How to print to Python terminal with Boost::Python

description: Print to Python terminal with Boost::Python


code:
code_lookup = {'PL':0, 'FR':2, 'DE':3}
return code_lookup['PL']

rawDescription: Convert enum to int in python

description: Convert enum to int in python


code:
adjacencyList = {1: {1}, 2: {2, 3}, 3: {2, 3}}

class AdjacencyMatrix():

    def __init__(self, adjacencyList, label = ""):
        """
        Instanciation method of the class.
        Create an adjacency matrix from an adjacencyList.
        It is supposed that graph vertices are labeled with numbers from 1 to n.
        """

        self.matrix = []
        self.label = label

        #create an empty matrix
        for i in range(len(adjacencyList.keys())):
            self.matrix.append( [0]*(len(adjacencyList.keys())) )

        for key in adjacencyList.keys():
            for value in adjacencyList[key]:
                self[key-1][value-1] = 1

    def __str__(self):
        # return self.__repr__() is another possibility that just print the list of list
        # see python doc about difference between __str__ and __repr__

        #label first line
        string = self.label + "\t"
        for i in range(len(self.matrix)):
            string += str(i+1) + "\t"
        string += "\n"

        #for each matrix line :
        for row in range(len(self.matrix)):
            string += str(row+1) + "\t"
            for column in range(len(self.matrix)):
                string += str(self[row][column]) + "\t"
            string += "\n"

        return string

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

    def __getitem__(self, index):
        """ Allow to access matrix element using matrix[index][index] syntax """
        return self.matrix.__getitem__(index)

    def __setitem__(self, index, item):
        """ Allow to set matrix element using matrix[index][index] = value syntax """
        return self.matrix.__setitem__(index, item)

    def areAdjacent(self, i, j):
        return self[i-1][j-1] == 1

m = AdjacencyMatrix(adjacencyList, label="mbr")
print(m)
print("m.areAdjacent(1,2) :",m.areAdjacent(1,2))
print("m.areAdjacent(2,3) :",m.areAdjacent(2,3))

rawDescription: Create adjacency matrix in python from csv dataset


code: a == e

rawDescription: Three tiers of equality comparison in Python


code:
class Int4(int):
    def __new__(cls, i):
        return super(Int4, cls).__new__(cls, i & 0xf)

x, y = Int4(10), Int4(9)
x + y
type(x + y)

rawDescription: How to emulate 4-bit integer in Python 3?

description: Emulate 4-bit integer in Python 3


code: xy = np.vstack((X.flatten(), Y.flatten())).T

rawDescription: Is there a multi-dimensional version of arange/linspace in numpy?


code:
import itertools

class MyMeta(type):
    _counter = itertools.count()

    @classmethod
    def as_metaclass(meta, *bases):
        '''Create a base class with "this metaclass" as metaclass

        Meant to be used in the definition of classes for Py2/3 syntax equality

        Args:
          bases: a list of base classes to apply (object if none given)
        '''
        class metaclass(meta):
            def __new__(cls, name, this_bases, d):
                # subclass to ensure super works with our methods
                return meta(name, bases, d)
        return type.__new__(metaclass, str('tmpcls'), (), {})

    def __call__(cls, *args, **kwargs):
        obj = type.__call__(cls, *args, **kwargs)
        obj.name = '%s_%d' % (cls.__name__, next(cls._counter))
        return obj

class MyClass(MyMeta.as_metaclass()):
    pass

a = MyClass()
print('a.name:', a.name)

b = MyClass()
print('b.name:', b.name)

c = MyClass()
print('c.name:', c.name)

rawDescription: Ensure uniqueness of instance attribute in python


code:
for i in range(len(node)):
     options [i] = names

rawDescription: Python: Updating a list of values in a dictionary


code:
some_list = ["some", "values", "in", "a", "list", ]
func(*some_list)

rawDescription: Passing a list of parameters into a Python function


code:
df = pd.DataFrame()
for m in M:
   s = m['student']
   l = m['lecturer']
   Lecturer[l]['limit'] = Lecturer[l]['limit'] - 1
   id = m['projectid']
   p = Project[id]['title']
   c = Project[id]['sourceid']
   r = str(getRank("Single_Projects1copy.csv",s,c))

   print(s+","+l+","+p+","+c+","+r)

   dataPack = (s+","+l+","+p+","+c+","+r)

   df.append(pd.DataFrame.from_records([dataPack]))
df.to_csv('try.csv') # write all data once outside the loop

rawDescription: Using Pandas to export multiple rows of data to a csv


code:
from numpy import *

a='' #x-coordinates
b='' #y-coordinates

data = loadtxt("battri.node")

nodes=data[:,0]

x=data[:,1]
y=data[:,2]
flag=data[:,3]

crit1 = (x==-7.00) & (y>=58.1) & (y<63.5)
flag[crit1] = 2

savetxt('output_file_name', data)

rawDescription: Replace a value based on specific criteria


code:
class Calculator(object):
    def add(self, a, b):
        return a + b

rawDescription: Instantiating a python class in C#

description: Instantiating a python class in C#


code:
import pandas
collection=['1.csv','2.csv','3.csv','4.csv']

result = pandas.create_empty() # not sure how to do this
for i in collection:
  csv = pandas.read_csv(i)
  result = result.merge(csv, on='field1')

result.to_csv('output2.csv',index=False)

rawDescription: Python for loop to read csv using pandas


rawDescription: Vowel counter in a text file

description: Vowel counter in a text file


code:
root = RootLogger(WARNING)
Logger.root = root
Logger.manager = Manager(Logger.root)

rawDescription: importing python logging module settings

description: Importing python logging module settings


code:
from itertools import product, imap
def base3sequence(l=12, digits='012'):
    return imap(''.join, product(digits, repeat=l))

rawDescription: Improve efficiency of modules

description: Improve efficiency of modules


code:
import icu
collator = icu.Collator.createInstance(icu.Locale('de_DE.UTF-8'))
sorted(subjects, key=lambda x: collator.getSortKey(x.long_name.lower()))

rawDescription: Properly sorting lists of objects by attribute, with a twist


code: a.append == b.append

rawDescription: Python Lists and Equality

description: Python Lists and Equality


code:
tmp = A[a]
tmp[b] = B

rawDescription: Setting ndarray values with the flat iterator


rawDescription: Making a list of evenly spaced numbers in a certain range in python


code:
class LocalConfig(Configuration):
    MYSQL_DB = 'mycoolstuff'
    MYSQL_USER = 'root'
    MYSQL_PASS = 'rootpass'
    MYSQL_HOST = '172.17.42.1'  # Docker
    MYSQL_PORT = 3306

Config = LocalConfig()

rawDescription: How to implement compound configuration variables, or "module level properties?"

description: Implement compound configuration variables, or "module level properties?"


code:
from scipy.interpolate import InterpolatedUnivariateSpline

# cubic spline interpolation
itp_A_cdf = InterpolatedUnivariateSpline(quantiles[1:], A_cdf, k=3)
# the PPF is the inverse of the CDF, so we simply reverse the order of the
# x & y arguments to InterpolatedUnivariateSpline
itp_B_ppf = InterpolatedUnivariateSpline(B_cdf, quantiles[1:], k=3)

itp_corrected_quantiles = itp_B_ppf(itp_A_cdf(quantiles[1:]))

fig, ax = plt.subplots(1, 1)
ax.hold(True)
ax.plot(quantiles[1:], A_cdf, '-r', lw=3, label='A')
ax.plot(quantiles[1:], B_cdf, '-k', lw=3, label='B')
ax.plot(corrected_quantiles, A_cdf, '--xr', lw=3, ms=10, mew=2, label='exact')
ax.plot(itp_corrected_quantiles, A_cdf, '--+b', lw=3, ms=10, mew=2,
        label='interpolated')
ax.legend(loc=5)

rawDescription: How can I manipulate the CDF of a sample such that it matches that of a different sample?

description: Manipulate the CDF of a sample such that it matches that of a different sample


code:
poss = [(k,v) if v else (k,) for k,v in sorted(d.items())]
list(product(*poss))

rawDescription: Combinations of elements in Dictionary in Python


code:
class UniversityContact(models.Model):
    # as above, plus:
    def abbrev(self):
        return self.university.abbrev
    abbrev.admin_order_field = 'university__abbrev'

rawDescription: Python Django: join view on the admin interface


code: a[inf_ind] = f(x[inf_ind])

rawDescription: numpy: concise conditional syntax for array division

description: Numpy: concise conditional syntax for array division


rawDescription: What is a simple fuzzy string matching algorithm in Python?


rawDescription: pandas or numpy for multi column conditional averaging

description: Pandas or numpy for multi column conditional averaging


code:
form = InvoiceForm(request.POST)
if form.is_valid():
    field1 = form.cleaned_data['field1']
    field2 = form.cleaned_data['field2']
    tax_obj = form.cleaned_data['tax']
    # create your invoice here
    new_invoice = Invoice.objects.create(field1=field1,
                                         field2 = field2,
                                         tax=tax_obj.value)

rawDescription: How to customize a ModelForm with ChoiceField for a Model FloatField attribute Django

description: Customize a ModelForm with ChoiceField for a Model FloatField attribute Django


code:
df=pd.DataFrame( {'one':[0.1, .32, .2, 0.4, 0.8], 'two':[.23, .18, .56, .61, .12], 'three':[.9, .3, .6, .5, .3], 'four':[.34, .75, .91, .19, .21], 'zive': [0.1, .32, .2, 0.4, 0.8], 'six':[.9, .3, .6, .5, .3], 'drive':[.9, .3, .6, .5, .3]})

corrMatrix=df.corr()

corrMatrix.loc[:,:] =  np.tril(corrMatrix, k=-1) # borrowed from Karl D's answer

already_in = set()
result = []
for col in corrMatrix:
    perfect_corr = corrMatrix[col][corrMatrix[col] == 1].index.tolist()
    if perfect_corr and col not in already_in:
        already_in.update(set(perfect_corr))
        perfect_corr.append(col)
        result.append(perfect_corr)

rawDescription: Returning groups of correlated columns in pandas data frame


code:
def set_properties(instance, properties):
    for property in properties:
        setattr(instance, property, properties[property])

rawDescription: more convenient way to assign variables to class object properties

description: More convenient way to assign variables to class object properties


code:
from django import forms

from models import MyModel

class MyModelForm(forms.ModelForm):
    extra_file = forms.FileField()

    class Meta:
        model = MyModel

rawDescription: How include a filefield in a django admin model form that is not in the model


code: df

rawDescription: Find key from value for Pandas Series

description: Find key from value for Pandas Series


code:
def scriptB_function(x):
  return x*x

rawDescription: Limit the number of running instances of a python script


code:
def saveDirMeta(name, bases, dct):
    dct['saveDirectory'] = os.path.join(saveDir, name)
    return type(name, bases, dct)

class TestClass(object):
    __metaclass__ = saveDirMeta  # this adds the 'saveDirectory' attribute
    def __init__(self):
        pass # do something

rawDescription: Python get class name

description: Python get class name


code:
import numpy as np
from sklearn.linear_model import LogisticRegression

x1 = np.random.randn(100)
x2 = 4*np.random.randn(100)
x3 = 0.5*np.random.randn(100)
y = (3 + x1 + x2 + x3 + 0.2*np.random.randn()) > 0
X = np.column_stack([x1, x2, x3])

m = LogisticRegression()
m.fit(X, y)

# The estimated coefficients will all be around 1:
print(m.coef_)

# Those values, however, will show that the second parameter
# is more influential
print(np.std(X, 0)*m.coef_)

rawDescription: How to find the importance of the features for a logistic regression model?

description: Find the importance of the features for a logistic regression model


code:
server = LocalProxyServer((common.LISTEN_IP, common.LISTEN_PORT), GAEProxyHandler)
server.serve_forever()

rawDescription: Where is the do_CONNECT method in goagent being called?


code: alphaFadeLayer = ...

rawDescription: python: Keep entry in dict synced to the original?

description: Python: Keep entry in dict synced to the original


rawDescription: pythonic way of removing similar items from list

description: Pythonic way of removing similar items from list


code:
from celery.execute import send_task

result = send_task(args.task, task_args, task_kwargs)

rawDescription: Celery and routing

description: Celery and routing


code:
class Foo:

    def __init__(self):
        self._x_was_modified = False
        self._x = None

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x_was_modified = True
        self._x = value

foo = Foo()
print('x was modified by user: {}'.format(foo._x_was_modified))
foo.x = 42
print('x was modified by user: {}'.format(foo._x_was_modified))

rawDescription: How to check if an attribute has default value defined in __init__

description: Check if an attribute has default value defined in __init__


code:
def longest_path( paths ):
    key = lambda path:path.count('/')
    return max(paths, key=key)

rawDescription: Find deepest nested path?

description: Find deepest nested path


code:
import sublime, sublime_plugin, os, subprocess, glob, tempfile, plistlib
from zipfile import ZipFile

# This function gives array of scope names from the plist dictionary passed as argument
def scopes_inside(d):
    result = []
    for k in d.keys():
        if k == 'scopeName':
            result = result + [ s.strip() for s in d[k].split(',') ]
        elif isinstance(d[k], dict):
            result = result + scopes_inside(d[k])
    return result

# Using set to have unique values
scopes = set()
# Parsing all .tmLanguage files from the Packages directory
for x in os.walk(sublime.packages_path()):
    for f in glob.glob(os.path.join(x[0], '*.tmLanguage')):
        for s in scopes_inside(plistlib.readPlist(f)):
            scopes.add(s.strip())
# Parsing all .tmLanguage files inside .sublime-package files from the Installed Packages directory
for x in os.walk(sublime.installed_packages_path()):
    for f in glob.glob(os.path.join(x[0], '*.sublime-package')):
        input_zip = ZipFile(f)
        for name in input_zip.namelist():
            if name.endswith('.tmLanguage'):
                for s in self.get_scopes_from(plistlib.readPlistFromBytes(input_zip.read(name))):
                    scopes.add(s.strip())
# Parsing all .tmLanguage files inside .sublime-package files from the Installation directory
for x in os.walk(os.path.dirname(sublime.executable_path())):
    for f in glob.glob(os.path.join(x[0], '*.sublime-package')):
        input_zip = ZipFile(f)
        for name in input_zip.namelist():
            if name.endswith('.tmLanguage'):
                for s in self.get_scopes_from(plistlib.readPlistFromBytes(input_zip.read(name))):
                    scopes.add(s.strip())
scopes = list(scopes)

rawDescription: Get all scope names on Sublime Text 3

description: Get all scope names on Sublime Text 3


rawDescription: identify time point in data frame based on condition per time series

description: Identify time point in data frame based on condition per time series


code: gfunctions = {}

rawDescription: Can I restore a function whose closure contains cycles in Python?

description: Restore a function whose closure contains cycles in Python


code:
for client in dict_list:
    clientLabel = Label(...)
    contactLabel = Label(...)
    emailLabel = Label(...)

    clientLabel.grid(...)
    contactLabel.grid(...)
    emailLabel.grid(...)

rawDescription: Checkbox to determine if an action is completed or not


code:
a
c
d
r
e
2345
t
y

rawDescription: Python iterator behaviour

description: Python iterator behaviour


code:
flatten(myList)
flatten(myList + myList)

rawDescription: How to print list of list into one single list in python without using any for or while loop?

description: Print list of list into one single list in python without using any for or while loop


code:
def get_commonname(host,port=443):
    oid='\x06\x03U\x04\x03' # Object Identifier 2.5.4.3 (COMMON NAME)
    pem=ssl.get_server_certificate((host,port))
    der=ssl.PEM_cert_to_DER_cert(pem)
    i=der.find(oid) # find first common name (certificate authority)
    if i!=-1:
        i=der.find(oid,i+1) # skip and find second common name
        if i!=-1:
            begin=i+len(oid)+2
            end=begin+ord(der[begin-1])
            return der[begin:end]
    return None

rawDescription: Disable SSL certificate validation in Python


rawDescription: Index a numpy array with another array

description: Index a numpy array with another array


code:
#create random data with labels 0 to 39, then add 2 label case and one label case.
corpus=pd.DataFrame({'data':np.random.randn(49998),'label':np.random.randint(40,size=49998)})
corpus.loc[49998]=[random.random(),40]
corpus.loc[49999]=[random.random(),40]
corpus.loc[50000]=[random.random(),41]

rawDescription: How to split Test and Train data such that there is garenteed at least one of each Class in each

description: Split Test and Train data such that there is garenteed at least one of each Class in each


code:
DATABASE_USER = os.environ.get("MYAPP_DB_USER", '')
DATABASE_PASSWORD = os.environ.get("MYAPP_DB_PASSWORD", '')

rawDescription: Python/Django - Avoid saving passwords in source code


code:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from .models import Feat

class IndexView(generic.ListView):
    template_name = 'feature/index.html'
    context_object_name = 'latest_feats'

    def get_queryset(self):
        return Feat.objects.order_by('-created')

class DetailView(generic.DetailView):
    model = Feat
    template_name = 'feature/detail.html'
    context_object_name = 'feat'

rawDescription: Loops in django 1.8 views

description: Loops in django 1.8 views


rawDescription: Python: Using sympy.sympify to perform a safe eval() on mathematical functions


rawDescription: numpy array slicing with arbitrary dimension

description: Numpy array slicing with arbitrary dimension


code:
from BeautifulSoup import BeautifulSoup
html = '<a href="http://google.com"> Hello World! </a>'
soup = BeautifulSoup(html)
soup.a.string

rawDescription: How do I use regular expressions to parse HTML tags?

description: Use regular expressions to parse HTML tags


code:
import itertools as IT
import csv

inFile = 'curious.dat'
outFile = 'curious.out'

def mykey(row):
    return (row['mrn'], row['specimen_id'], row['lab_num'])

fieldnames = 'mrn specimen_id date    lab_num Bilirubin   Lipase  Calcium Magnesium   Phosphate'.split()

with open(inFile, 'rb') as ifd:
    reader = csv.DictReader(ifd, delimiter = '\t')
    with open(outFile, 'wb') as ofd:
        writer = csv.DictWriter(
            ofd, fieldnames, delimiter = '\t', lineterminator = '\n', )
        writer.writeheader()
        for key, group in IT.groupby(reader, key = mykey):
            new = {}
            row = next(group)
            for key in ('mrn', 'specimen_id', 'date', 'lab_num'):
                new[key] = row[key]
                new[row['labtest']] = row['result_val']
            for row in group:
                new[row['labtest']] = row['result_val']
            writer.writerow(new)

rawDescription: Rewind the file pointer to the beginning of the previous line


code:
class fileHandler:
    def __init__(self, dbf):
        self.logger = logging.getLogger('fileHandler')
        self.thefilename = dbf
    def __enter__(self):
        self.thefile = open(self.thefilename, 'rb')
        return self
    def __exit__(self, *args):
        self.thefile.close()

rawDescription: Class wrapper around file -- proper way to close file handle when no longer referenced


code:
df1
df2

rawDescription: Index of matching rows in Pandas DataFrame [Python]


code:
def getmax(lst):
    vals = [i.count(' ') for i in lst]
    maxel = lst[vals.index(max(vals))]
    return (vals,maxel)

rawDescription: Finding how many of a certain character in each element in a list


code:
def list(self):
    numbers = []
    for i in range(0, 5):
        numbers.append(random.randint(0, 90))
    for i in range(1, 5):
        for j in range(0, i - 1):
            if (numbers[i] == numbers[j]):
                return self.list()  # return
    return numbers

rawDescription: recursive function in class in python

description: Recursive function in class in python


code:
from collections import defaultdict  # available in Python 2.5 and newer

urls_d = defaultdict(int)
for url in list_of_urls:
    urls_d[url] += 1

rawDescription: Python : List of dict, if exists increment a dict value, if not append a new dict


code: ans.subs({k: 0})

rawDescription: Differentiation in python using Sympy

description: Differentiation in python using Sympy


code:
DU = []

for index, line in enumerate(oz):

   line = line.strip() if (index +1) % 15 != 0 else line.strip().split(' ')[0]

   for i in range(0,len(line)-3,3):

      DU.append(line[i:i+3])

rawDescription: Fill a list in a loop

description: Fill a list in a loop


code:
def coords_maker(num_x, num_y):

    num_x += 1
    num_y += 1
    coords = {}
    for i in range (0,num_y, 1):
        for n in range (0,num_x,1):
            coords['x'+str(n)+'y'+str(i)] = 0
    return coords

rawDescription: python3 string to variable

description: Python3 string to variable


rawDescription: How can I lookup based on multiple parameters?

description: Lookup based on multiple parameters


rawDescription: Is it possible to redefine reverse in a Django project?


code:
c = [[1, 2, 3], [4, 5, 6]]

# first method
res = [x for lst in c for x in lst]

# second method
from itertools import chain
res = list(chain(*c))

rawDescription: expanding arbitrary number of sublists within a list

description: Expanding arbitrary number of sublists within a list


code:
def find_max_var_amt(some_person):
    dct = patients[some_person].__dict__
    return max(len(dct[key]) for key in dct)

rawDescription: How to rewrite this Dictionary For Loop in Python?

description: Rewrite this Dictionary For Loop in Python


code:
# ...

# the edge pixels/voxels plus their immediate non-zero neighbours
erode2 = ndimage.binary_erosion(erode, struct)
candidate_neighbours = mask ^ erode2

nonzero_idx = np.vstack(np.where(candidate_neighbours)).T
nonzero_vals = B[candidate_neighbours]

# ...

rawDescription: border/edge operations on numpy arrays

description: Border/edge operations on numpy arrays


code:
def myreversed(seq):
    for i in range(len(x) - 1, -1, -1):
        yield seq[i]

rawDescription: How to reverse tuples in Python?

description: Reverse tuples in Python


code:
screen.blit(mouse_c.image, mouse_c.rect.topleft)
screen.blit(nPc.image, nPc.rect.topleft)

rawDescription: converting an image to a rect

description: Converting an image to a rect


code:
import zipfile
zip = zipfile.ZipFile('test.zip')
zip.namelist()

rawDescription: unzipping a file with Python and returning all the directories it creates

description: Unzipping a file with Python and returning all the directories it creates


code:
ts3[1] = 99
ts3
ts                #The january 10th value will be unchanged.

rawDescription: Selecting the first index after a certain timestamp with a pandas TimeSeries


code:
for myDict in [dict1, dict1, dict3]:
  myDict[key] = value

rawDescription: Editing multiple dictionaries with a single function:


code:
def detag(text,opentag='<',closetag='>'):
    t1 = regex.escape(opentag)
    t2 = regex.escape(closetag)
    re = regex.compile(t1 + '(?:[^' + t2 + t1 + ']|(?R))*' + t2)
    result = re.sub('',text)
    return result

rawDescription: Detagging with regex does not catch nested tags


code:
#!/usr/bin/env python
from subprocess import check_call as x

x("""pwd
cd /
pwd""", shell=True)

rawDescription: How to execute bash from within a python file?

description: Execute bash from within a python file


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

wait = WebDriverWait(browser.driver, 10)
wait.until(EC.visibility_of_element_located((By.TAG_NAME, "img")))

browser.driver.save_screenshot(str(step+1) + '.png')

rawDescription: saving inline image from splinter

description: Saving inline image from splinter


code:
x = enumerate([1,2])
help(x)

rawDescription: Does enumerate() produce a generator object?


rawDescription: How to generate this list from user entered number using python?

description: Generate this list from user entered number using python


rawDescription: Access the index of a pandas series

description: Access the index of a pandas series


code:
import os
data = "hello world"
os.system("echo '%s' | pbcopy" % data)

rawDescription: How to copy content inside of a txt file to clipboard?

description: Copy content inside of a txt file to clipboard


code:
addr_list.sort(key=lambda ip: map(int, reversed(ip.split('.'))))
addr_list

rawDescription: Sort on the last octet of an IP address in a Python list


code:
for i in range(4):
    yield [row[i] for row in matrix]

rawDescription: How to read aloud Python List Comprehensions?

description: Read aloud Python List Comprehensions


code:
for user in users:
    user.__eq__ = lambda self, other: self.id == other.id
    user.__hash__ = lambda self: hash(self.id)

unique_users = set(users)

# If you want to remove the attributes to leave them as they were:

unique_users = [delattr(usr, __hash__) for usr in unique_users]

rawDescription: python filtering list for duplicate objects

description: Python filtering list for duplicate objects


code:
int_add = int.__add__
int_add(1, 2)

rawDescription: How can I get the addition object for integers?

description: Get the addition object for integers


code:
#!/bin/sh
gnuplot << EOF

rawDescription: Can Gnuplot take different arguments at run time? maybe with Python?


code: colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

rawDescription: Setting a colour scale in ipython

description: Setting a colour scale in ipython


code: [d['key'] for d in l]

rawDescription: Get a list of values from a list of dictionaries in python


code:
f = open('your_file')
for line in f:
    for word in line.split():
        word = word.strip('.,?!')
        # do something

rawDescription: I have a text file of a paragraph of writing, and want to iterate through each word in Python


code:
import datetime
ticks = 52707330000
converted_ticks = datetime.datetime.now() + datetime.timedelta(microseconds = ticks/10)

rawDescription: How to convert ticks to datetime in Python?

description: Convert ticks to datetime in Python


rawDescription: GIven a set of strings, create a dictionary of dictionaries using them as keys to entries with default values


code:
from bs4 import BeautifulSoup

filename = "test.xml"
soup = BeautifulSoup(open(filename), "xml")

def chapterCount(volume_name):
    volume = soup.find("volume", attrs={"name": volume_name})
    chapter_count = len(volume.find_all("chapter", recursive=False))
    return chapter_count

def getChapter(volume_name, chapter_number):
    volume = soup.find("volume", {"name": volume_name})
    chapter = volume.find("chapter", {"n": chapter_number})
    items = [ content for content in chapter.contents if content != "\n" ]
    return "\n".join([ item.contents[0] for item in items ])

# from now on, it's the same as your original code

def render_default_values(template, **kwargs):
    chapter = getChapter(session['volume'],session['chapter'])
    count = chapterCount(session['volume'])
    return render_template(template, chapter=chapter, count=count, **kwargs)

@app.route('/<volume>/<int:chapter>')
def goto(volume, chapter):
    session['volume'] = volume
    session['chapter'] = chapter
    return render_default_values("index.html")

rawDescription: Python XML Parsing Algorithm Speed

description: Python XML Parsing Algorithm Speed


code:
while True:
   if not GPIO.input(22):
      print("Triggered")
      os.system('omxplayer -o hdmi cow.mp3')
      GPIO.wait_for_edge(22, GPIO.RISING)
   else:
      print ("Waiting to be triggered again")
      os.system('omxplayer -o hdmi sample.mp3')
      GPIO.wait_for_edge(22, GPIO.FALLING)

rawDescription: Pi run command and wait

description: Pi run command and wait


code:
threshold = 0.03
for col in df:
    counts = df[col].value_counts(normalize=True)
    df = df.loc[df[col].isin(counts[counts > threshold].index), :]

rawDescription: Pandas: Filter dataframe for values that are too frequent or too rare


code:
import dis
dis.dis(f3)

rawDescription: recursive closures (function generator)

description: Recursive closures (function generator)


rawDescription: Insert 0s into 2d array

description: Insert 0s into 2d array


code:
host_string = raw_input("enter hosts (separated by a comma):")
hosts = hosts_string.split(',')

rawDescription: How do you create multiple variables from raw input in python?

description: Create multiple variables from raw input in python


code: samples = [do_sampling() for _ in range(n_samples)]

rawDescription: More Compact List Comprehension Where Iteration Variable is Unused


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

nrows, ncols = 3, 3

x = np.linspace(0,10,100)

fig = plt.figure()
for i in range(1,10):
    ax = fig.add_subplot(nrows, ncols, i)
    if i < 7:
        ax.plot(x, x**i)

plt.show()

rawDescription: loop over 2d subplot as if it's a 1-D

description: Loop over 2d subplot as if it's a 1-D


code:
x=list('abc')
id(x)
yy=[x]*3                              # create a list with x, duplicated...
[id(i) for i in yy]
yy = [list('abc') for _ in range(3)]
[id(i) for i in yy]

rawDescription: Regarding python list with reference

description: Regarding python list with reference


code:
while not some_condition:
    do_something()

rawDescription: Pythonic way of doing this?

description: Pythonic way of doing this


code:
def gather_results(result_infos):
    results = []
    for i in xrange(len(result_infos)):
        result_infos[i][0].wait()
        results.append(result_infos[i][1])
    return results

rawDescription: Threading in Python for each item in list


code:
class Trivial(yaml.YAMLObject):
    yaml_tag = u'!Trivial'
    def __init__(self):
        self.a = 1
        self.b = 2
        self._ignore = 3
    @classmethod
    def to_yaml(cls, dumper, data):
        # ...
        my_ob = deepcopy(data)
        for item in dir(my_ob):
            if item.startswith("_") and not item.startswith("__"):
                del my_ob.__dict__[item]
        return dumper.represent_yaml_object(cls.yaml_tag, my_ob, cls,
                                                flow_style=cls.yaml_flow_style)

rawDescription: How can I ignore a member when serializing an object with PyYAML?

description: Ignore a member when serializing an object with PyYAML


rawDescription: Pandas: Change dates in dataframe to same date format


code:
def add_constraint(values, constraint):
    return values[constraint] < 99

def add_constraints(values, constraint_list):
    return [add_constraint(values, constraint) for constraint in constraint_list]

def gen_costraints(constraint_list):
    global constraints
    constraints = lambda values: (add_constraints(values, constraint_list))

rawDescription: How to solve 3D multi bin-packing with OpenOpt

description: Solve 3D multi bin-packing with OpenOpt


code:
g = "COPB2A"
f = "COPB2"
g.startswith(f)

rawDescription: Matching in Python lists when there are extra characters


rawDescription: Extract fields from the string in python


code:
import sys
sys.path.insert(0, '/location/of/subscripts')

import first_script
import second_script
import third_script

first_script.main('/location/of/files')
second_script.main('/location/of/files')
third_script.main('/location/of/files')

rawDescription: Python -- "Batch Processing" of multiple existing scripts


code:
with open('output.txt', 'w+b') as f1:
    all_files_as_one_string = ' '.join(file_contents)
    f1.write(all_files_as_one_string)

rawDescription: How to find the all text files from the path and combine all the lines in that text files to one text file

description: Find the all text files from the path and combine all the lines in that text files to one text file


code:
clean_list = []
for firm in firms:
    firm = firm.strip()
    if firm not in clean_list:
        clean_list.append(firm)
    clean_list.sort()

clean_list
['B Of A M L',
 'Cowen & Company',
 'Deutsche Bk Sec',
 'Dougherty & Co.',
 'Fbr Cap Markets',
 'Goldman Sachs',
 'J.P. Morgan',
 'Janney Mont.',
 'Jefferies & Co.',
 'Leerink Partner',
 'Raymond James',
 'Wedbush Securit',
 'Zacks Small Cap']

rawDescription: replacing quotes inside a pandas df to count unique terms

description: Replacing quotes inside a pandas df to count unique terms


code:
photos = [["Trip to Thailand", "IMG_001.jpg"], ["Latvia 2010", "IMG_001.jpg"]]
photo = ["Latvia 2010", "IMG_001.jpg"]
photo in photos

rawDescription: Check if list contains another list in python


code: dict(sorted(scores))

rawDescription: "group by" aggregate functions with dictionary comprehensions


code: ax.contourf(x, y, scalar_field, zdir='y', offset=y_dim/2+1, cmap=cm.coolwarm)

rawDescription: 3D plot with Matplotlib

description: 3D plot with Matplotlib


rawDescription: How to set significant figures in pyplot annotation

description: Set significant figures in pyplot annotation


code:
def sbo_extra_dwn(link, name):
    results = ()
    sbo_url_dwn = link + name + ".info"
    sbo_url_dwn = sbo_url_dwn.replace("repository", "slackbuilds")

    f = urllib2.urlopen(sbo_url_dwn)
    read_page = f.read()
    for line in read_page.splitlines():
            if line.startswith(' '):
                    line = line[10:-1]
            if line.startswith('http'):
                    results = results+(line,)
    return results

rawDescription: What is the difference between print and return in a function?


code: df["ratio"] = df.groupby(level=0)[3].transform(lambda x: x[0]/ x[1])

rawDescription: Calculation between groups in a Pandas multiindex dataframe


rawDescription: Scrapy RetryMiddleWare send signal to spider


rawDescription: python deleting older files that match an unknown pattern (tricky)

description: Python deleting older files that match an unknown pattern (tricky)


code:
f = TrackedFile('palindrome.txt', 'w')
f.size
f.write('A man a plan a canal ')
f.size
f.write('Panama')

rawDescription: How do I determine an open file's size in Python?

description: Determine an open file's size in Python


code:
import fileinput
import re
import sys

myfile = "Tset.cpp"

regx = re.compile(r'(.*?\.\./Config/)(.*?)(\.cfg.*?)')

for line in fileinput.FileInput(myfile, inplace=1):
    matchObj = regx.match(line, re.M|re.I)
    if matchObj:
        sys.stdout.write(regx.sub(r'\1AnotherConfig\3', line))
    else:
        sys.stdout.write(line)

rawDescription: Find text with regular expression and replace in file


code:
import collections
My_dict = collections.OrderedDict((('What is your name?','Emma'),('What is your age',34),('What color eyes do you have','Blue')))

x = iter(My_dict.keys())
for i in range(3):
    print(next (x))

rawDescription: Dictionary Query Python?

description: Dictionary Query Python


code: x = [[] for _ in xrange(7)]

rawDescription: Fast way to make list with same entry multiple times in Python?


code:
root = lxml.html.fromstring(html)
root.cssselect('span.some-class-name')

rawDescription: Lxml equivalent for BeautifulSoup find()


rawDescription: Unwanted behavior by Python List of Lists


rawDescription: Getting common keys from different dictionaries in python


rawDescription: Reindexing dataframes and joining columns


code:
import datetime as DT
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(2015)

x = [DT.date(2015,6,15)+DT.timedelta(days=i*7)
     for i in range(5)]
y = np.random.randint(25, size=(3,5)).astype(float)

fig, ax = plt.subplots()
color = ['blue', 'green', 'red']
for i in range(3):
    ax.plot(x, y[i], '.-', markersize=8, fillstyle='full', linewidth=1.5,
            clip_on=True, zorder=30)

    ax.fill_between(x, 0, y[i], alpha=0.5, color=color[i],
                    edgecolor="white", zorder=20)
ax.set_xlim(min(x), max(x)+DT.timedelta(days=7))
plt.show()

rawDescription: matplotlib/python: how to have an area with no values

description: Matplotlib/python: how to have an area with no values


code:
import re
hists = re.findall(r'(hist\[\s\d+\]).*?(\d+\.\d+).*?(\d+)',input)
sample_avg_etc = re.findall(r'(samples): (\d+); (avg): (\d+\.\d+); (min): (\d+\.\d+); (max): (\d+\.\d+)',input)

rawDescription: Extract parts of log in Python to import to Excel


code: AES.new(key, AES.MODE_CTR, IV = bytes(ivBytes), counter=ctr)

rawDescription: PHP substitute of python encryption code


code:
df2 = df1.copy()
last_column = 6
for i in map(str,range(3,last_column)):
    df2[i] = 0
df2 = df2[ map(str,range(1,last_column))+['first','offset']]

rawDescription: Python - Pandas - Dataframe: Row Specific Conditional Column Offset


code: dimensions = [i, i]

rawDescription: Python: short coordinate function unexpectedly changes incoming argument value


code:
'a' in mylist
'foo' in mylist

rawDescription: Python3 - How can I determine the existence of element values?


code: [dict(zip(d, vals)) for vals in zip(*d.values())]

rawDescription: How do I turn a dictionary with lists as values into a list of dictionaries with single values?

description: Turn a dictionary with lists as values into a list of dictionaries with single values


code:
request = urllib.request.Request(url, data.encode('utf8'))
request.add_header('content-type', 'application/json')
response = urllib.request.urlopen(request)

rawDescription: JSON query in a post request from Python and save result as csv file


code:
from pprint import pprint
pprint(t)
node = find(t, "key3")
pprint(node)

rawDescription: how to traverse this tree?

description: Traverse this tree


code:
if var in myDictionary:              # loops over the KEYS of myDictionary
    myDictionary[var] += 1
else:
    myDictionary[var] = 1

rawDescription: Dictionary that counts occurrences of its items


code:
from allauth.account.forms import SignupForm
from django.core.validators import ValidationError

class AllauthSignupForm(SignupForm):

    def clean_username(self):
        # check for duplicates here and then
        if duplicate:
             raise ValidationError("Username is not allowed")

    return org

rawDescription: Django All-Auth - Validate against linked object on account creation?


code:
import tkinter as tk

class Application(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.title('Hello world!')

        self.quitButton = tk.Button(self, width=12, text='Quit', bg='tan',
                    command=self.close_app)
        self.quitButton.grid(row=0, column=0, padx=8, pady=8)

        self.helloButton = tk.Button(self, width=12, text='Hello',
                    command=self.say_hi)
        self.helloButton.grid(row=0, column=1, padx=8, pady=8)

    def say_hi(self):
        print('Hello world?!')

    def close_app(self):
        self.destroy()

app = Application()
app.mainloop()

rawDescription: Tkinter - RuntimeError: maximum recursion depth exceeded


rawDescription: Numpy 3D array transposed when indexed in single step vs two steps


code: result = dict((key, sum(key in inputDict[nodes] for nodes in digraph)) for key in inputDict)

rawDescription: how to re-write for loop to list comprehension

description: Re-write for loop to list comprehension


code: ':'.join('{:02x}'.format(ord(ch)) for ch in '\x0a\xfa')

rawDescription: How to reformat a string that represents a big-endian into a MAC-Address format?

description: Reformat a string that represents a big-endian into a MAC-Address format


rawDescription: Click a checkbox with selenium-webdriver


code:
class HypotheticalBranch(object):
  def __init__(self, r, p, c):
    self.r=r
    self.p=p
    self.c=c
  def __repr__(self):
    return "HypotheticalBranch(%d,%d,%d)" % (self.r,self.p,self.c)

rawDescription: Python Combinatorics, part 2

description: Python Combinatorics, part 2


code:
def sum(request, allargs):
    args = map( int, allargs.split('/') )
    # Compute sum

rawDescription: Optional number of wildcards in URL patterns in Django


code:
@patch("builtins.print",autospec=True,side_effect=print)
def test_somethingelse(self,mock_print):
    mock_print_module.print_something()
    mock_print.assert_called_with("print something")

rawDescription: Mocking print but allow using it in tests


code:
# make dummy data
N = 10**4
df = pd.DataFrame({"Col": np.random.randint(1, 10, N), "IsBuy": np.random.choice([True, False], N)})
df.head()
df.groupby("Col")["IsBuy"].mean()

rawDescription: How to copy unique keys and values from another dictionary in Python

description: Copy unique keys and values from another dictionary in Python


rawDescription: python regular expression: script to change "frame_20" to "frame_0020"

description: Python regular expression: script to change "frame_20" to "frame_0020"


code:
from itertools import cycle
class Whatever:
    fnames = cycle(["im1.gif","im2.gif","im3.gif"])
    def on_button(self,*args,**kwargs):
        if self.sender().objectName() == "next_button":
           next_path = os.path.join("data", "images", next(self.fname))
           myPixMap = QtGui.QPixmap(next_path)
           ...

rawDescription: Loop Increment for every click in python/ pyqt


code:
def __call__(self, *args, **kwargs):
    # [...]
    try:
        self.f(*args, **kwargs)
    except:
        t, v, tb = sys.exc_info()
        if sys.version_info[0] <= 2:
            exec("raise v, None, tb.tb_next")
        else:
            raise v.with_traceback(tb.tb_next)

rawDescription: Python 2 and 3 compatible way of hiding a decorator from stacktrace


rawDescription: How to erase letters at any position in a string in python?

description: Erase letters at any position in a string in python


code: {v: k for k,v in enumerate(calendar.month_abbr)}

rawDescription: month name to month number and vice versa in python

description: Month name to month number and vice versa in python


code: start_urls = ['http://www.dmoz.org/%s' % category for category in settings.CATEGORIES]

rawDescription: Separate output file for every url given in start_urls list of spider in scrapy


code:
x2
y2

rawDescription: Matplotlib wont join data points when the x axis isn't equally spaced


code: factory_one[day_0:day_10+1] = time[day_0:day_10+1] * 2

rawDescription: How to set limits to specific components of an equation when plotting them?

description: Set limits to specific components of an equation when plotting them


Logging.handlers.SMTPHandler raises smtplib.SMTPAuthenticationError


code:
from datetime import datetime
import pytz # pip install pytz

fmt = '%Y-%m-%d %H:%M:%S %Z%z'
tz = pytz.timezone("America/New_York") # supply client's timezone here

# Get correct date for the midnight using given timezone.

# due to we are interested only in midnight we can:

# 1. ignore ambiguity when local time repeats itself during DST change e.g.,
# 2012-04-01 02:30:00 EST+1100 and
# 2012-04-01 02:30:00 EST+1000
# otherwise we should have started with UTC time

# 2. rely on .now(tz) to choose timezone correctly (dst/no dst)
now = datetime.now(tz)
print(now.strftime(fmt))

# Get midnight in the correct timezone (taking into account DST)
midnight = tz.localize(now.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None),
                       is_dst=None)
print(midnight.strftime(fmt))

# Convert to UTC (no need to call `tz.normalize()` due to UTC has no DST transitions)
dt = midnight.astimezone(pytz.utc)
print(dt.strftime(fmt))

# Get POSIX timestamp
print((dt - datetime(1970,1,1, tzinfo=pytz.utc)).total_seconds())

rawDescription: find Last mid-night time stamp in python

description: Find Last mid-night time stamp in python


code: for x in tree.walk(): print(x.payload)

rawDescription: represent binary search trees in python

description: Represent binary search trees in python


code:
s = 'datediff(varchar(30),timestamp(3),timestamp(3))'
s.partition("(")
s.partition("(")[2]
s.partition("(")[2].rpartition(")")
s.partition("(")[2].rpartition(")")[0]

rawDescription: String splitting python

description: String splitting python


code:
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')

# initialize a plot to determine the distance between the data points in pixel:
x = [1, 2, 3, 4, 2, 3, 3]
y = [0, 0, 0, 0, 1, 1, 2]
s = 0.0
points = ax.scatter(x,y,s=s,marker='s')
ax.axis([min(x)-1., max(x)+1., min(y)-1., max(y)+1.])

# retrieve the pixel information:
xy_pixels = ax.transData.transform(np.vstack([x,y]).T)
xpix, ypix = xy_pixels.T

# In matplotlib, 0,0 is the lower left corner, whereas it's usually the upper
# right for most image software, so we'll flip the y-coords
width, height = fig.canvas.get_width_height()
ypix = height - ypix

# this assumes that your data-points are equally spaced
s1 = xpix[1]-xpix[0]

points = ax.scatter(x,y,s=s1**2.,marker='s',edgecolors='none')
ax.axis([min(x)-1., max(x)+1., min(y)-1., max(y)+1.])

fig.savefig('test.png', dpi=fig.dpi)

rawDescription: Choosing marker size in Matplotlib

description: Choosing marker size in Matplotlib


code:
ans1 = original_loop(seed=0)
ans2 = new_vec(seed=0)
np.allclose(ans1, ans2)

rawDescription: performance loss after vectorization in numpy

description: Performance loss after vectorization in numpy


code: object_dict = dict((id(x), x) for x in object_list)

rawDescription: reduce python list of objects to dict object.id -> object

description: Reduce python list of objects to dict object.id -> object


code:
data = {"data" : "24.3"}
data_json = json.dumps(data)
headers = {'Content-type': 'application/json'}

response = requests.post(url, data=data_json, headers=headers)

rawDescription: REST post using Python-Request

description: REST post using Python-Request


code:
from decimal import Decimal

Decimal.__repr__ = lambda self: "{0:.2f}".format(self)

rawDescription: Python: Making Dollars make Sense

description: Python: Making Dollars make Sense


code:
class SomeClass(object):
    __metaclass__ = MyMeta

    attribute = SomeAttribute()

rawDescription: Best practice way for linking object attributes to class or object


code: first_cut_final = (first_cut_depth <= min_value+150)[...,None]*(first_cut-res)

rawDescription: Combining steps

description: Combining steps


code:
L = [9, 2, 8, 2, 3, 4, 2]
minL = min(L)
[i for i, x in enumerate(L) if x == minL]

rawDescription: Get the index of the minimium N elements of a list in Python


rawDescription: Learning loops and lists

description: Learning loops and lists


rawDescription: Reduce a key-value pair into a key-list pair with Apache Spark


code: s = "#big and #small, #big-red, #big-red-car and #big"

rawDescription: python: Replace/substitute all whole-word match in a string

description: Python: Replace/substitute all whole-word match in a string


rawDescription: python comprehension for loop with if statement and other actions following that

description: Python comprehension for loop with if statement and other actions following that


code:
from mydbfields import EuDateField
class Person(models.Model):
    ...
    birthday   = EuDateField("Birthday", null=True, blank=True, help_text="")

rawDescription: European date input in Django Admin

description: European date input in Django Admin


code:
class Dealer(object):
    def __init__(self, name, deck):
        self.name = name
        self.deck = deck
    def shuffle(self):
        self.deck.shuffle()
    def deal(self):
        return self.deck.takecard()

rawDescription: calling one class's method inside another in python

description: Calling one class's method inside another in python


code:
import mimetypes

class StaticFileHandler(webapp2.RequestHandler):
    def get(self, path):
        # edit the next line to change the static files directory
        abs_path = os.path.join(os.path.dirname(__file__), path)
        try:
            f = open(abs_path, 'r')
            self.response.headers.add_header('Content-Type', mimetypes.guess_type(abs_path)[0])
            self.response.out.write(f.read())
            f.close()
        except IOError: # file doesn't exist
            self.response.set_status(404)

rawDescription: cannot access webserver resources using virtualenv and webapp2

description: Cannot access webserver resources using virtualenv and webapp2


rawDescription: Set value for particular cell in pandas DataFrame


code:
easydiff1 = [10]*30000
easydiff2 = [10]*30000
easydiff2[0] = 0
timeit(easydiff1, easydiff2, 10000)
timeit(easydiff1, easydiff2, 1000000)

rawDescription: Is there a faster way to test if two lists have the exact same elements than Pythons built in == operator?


code: matches = [myresults for myresults in dict_matcher(dict1, dict2 , 2, 6)]

rawDescription: Help using *args in tuple matching Python function


code:
[dict_values(['s', 'sarah'])]
[(dict_values(['s', 'sarah']), dict_values(['s', 'sarah']))]

rawDescription: set custom node equality comparison in networkx

description: Set custom node equality comparison in networkx


code: f2.write(struct.pack('B', int(byte,2))) # unsigned 8 bit int

rawDescription: python literal binary to hex conversion

description: Python literal binary to hex conversion


code:
def float_cast(item):
    try:
        return float(item)
    except ValueError:
        return item

result_lst = [float_cast(item) for item in lst] #`lst` is your original list

rawDescription: Casting a list of strings into float if possible. - python


code:
listA = [0,1,2,1,2,1,2,3,4,5,2,1,3,4,5,2,1,6,0]
listB = [0,1,2,1,2,1,0]

def get_repeated_seq(seq, start, length):
    ref = seq[start:start+length]
    #print("Ref", ref)
    for pos in range(start+length, len(seq)-length):
        compare = seq[pos:pos+length]
        #print("Pos", pos, compare)
        if compare == ref:
            #print("Found", ref, "at", pos)
            return pos, length
    return False

def get_repeated_seqs(seq):
    reps = []
    for size in reversed(range(2, len(seq)/2)):
        for pos in range(0, len(seq)-size):
            #print("Check rep starting at pos %s for size %s" % (pos, size))
            rep = get_repeated_seq(seq, pos, size)
            if rep:
                reps.append(rep)
    return reps

def remove_repeated_seqs(seq, reps):
    # need to backup seq ?
    for rep in reps:
        overlaps = False
        for pos in range(rep[0], rep[0]+rep[1]):
            if seq[pos] == "*":
                overlaps = True
        if not overlaps:
            for pos in range(rep[0], rep[0]+rep[1]):
                seq[pos] = "*"
    out = []
    for item in seq:
        if item != "*":
            out.append(item)
    return out

reps = get_repeated_seqs(listB)
rem = remove_repeated_seqs(listB, reps)
#print(rem)
print(rem==[0,1,2,1,0])

reps = get_repeated_seqs(listA)
rem = remove_repeated_seqs(listA, reps)
#print(rem)
print(rem==[0,1,2,3,4,5,6,0])

rawDescription: Remove repeated sequence of integers from list in Python


code:
import dill
dill.detect.trace(True)
dill.pickles(work)

rawDescription: multiprocess initializer and pickling

description: Multiprocess initializer and pickling


code:
import datetime as dt

a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)

(b-a).total_seconds()

rawDescription: How do I check the difference, in seconds, between two dates?

description: Check the difference, in seconds, between two dates


rawDescription: Magic Squares - Siamese Method

description: Magic Squares - Siamese Method


code:
offset_x = +1 if scroll_x >= 0 else 0
offset_y = +1 if scroll_y >= 0 else 0
self.canvas.xview_moveto(float(scroll_x + offset_x)/new_width)
self.canvas.yview_moveto(float(scroll_y + offset_y)/new_height)

rawDescription: How to scroll a tkinter canvas to an absolute position?

description: Scroll a tkinter canvas to an absolute position


code:
def optfunc():
    x = array1
    y = array2

    x0 = x[:, 0]
    x1 = x[:, 1]
    x2 = x[:, 2]
    x3 = x[:, 3]

    y0 = y[:, 0]
    y1 = y[:, 1]

    A = 1./(x0 * x1)
    Bfactors = -0.5 * (1 / x0**2)
    Cfactors = -0.5 * (1 / x1**2)

    B = (np.transpose([x2]) - y0)**2 * np.transpose([Bfactors])
    C = (np.transpose([x3]) - y1)**2 * np.transpose([Cfactors])

    return np.transpose([A]) * np.exp(B + C)

rawDescription: Improve performance of function without parallelization


code: {{ field_with_errors(form.foo, placeholder='bar') }}

rawDescription: flask and wtf - how can I direct tag attributes for fields?

description: Flask and wtf - how can I direct tag attributes for fields


code:
class DetailView(LatestArticleMixin, generic.DetailView):
    model = Entertainmentblog
    template_name = 'entertainment/article.html'

rawDescription: how to use ListView class for two different templates

description: Use ListView class for two different templates


rawDescription: Xenserver API - Create VM's with local storage?


code:
from openerp import models, api

class FooterlessNotification(models.Model):
    _inherit = 'mail.notification'

    @api.model
    def get_signature_footer(self, user_id, res_model=None, res_id=None, context=None, user_signature=True):
        return ""

rawDescription: how to remove email footer in odoo?

description: Remove email footer in odoo


rawDescription: find all files indirectory and sub-directories and provide the path from directory

description: Find all files indirectory and sub-directories and provide the path from directory


rawDescription: Can't extract a value out of HTML with lxml


code:
for k, v  in d.items():
    if k == arg:
        if arg not in v:
            do_something(arg)
        break
else:
    do_something_else(arg)

rawDescription: Shorten/DRY this python if statement?

description: Shorten/DRY this python if statement


code:
# Set the contact's postal address.
new_contact.structured_postal_address.append(
  rel=gdata.data.WORK_REL, primary='true',
  street=gdata.data.Street(text='1600 Amphitheatre Pkwy'),
  city=gdata.data.City(text='Mountain View'),
  region=gdata.data.Region(text='CA'),
  postcode=gdata.data.Postcode(text='94043'),
  country=gdata.data.Country(text='United States'))

rawDescription: How to authorise a gdata contacts client in python

description: Authorise a gdata contacts client in python


code:
counts = {}
for n in G.nodes(): counts[n] = 0

rawDescription: Python: how to optimize the count of all possible shortest paths?


rawDescription: OrderedDict won't sort within a class

description: OrderedDict won't sort within a class


code:
md5list = ['9e107d9d372bb6826bd81d3542a419d6',
           'e4d909c290d0fb1ca068ffaddf22cbd0']
params = [[int(h, 16)] for h in md5list]
cursor.executemany("insert into hashes (md5) values (%s)", params)

rawDescription: insert binary(16) with executemany

description: Insert binary(16) with executemany


rawDescription: Inserting optparse input into a function call


code: nodes = nodes.sort_values('is_published', ascending=False).drop_duplicates(subset=['author_id'])

rawDescription: How to efficiently generate a special co-author network in python pandas?

description: Efficiently generate a special co-author network in python pandas


code:
with open('stack33655641.txt') as f:a=f.read()
print(a)
a=a.splitlines()
a

rawDescription: 'b' character added when using numpy loadtxt


code:
class SampleClass(object):

    PROTOCOLS = {'ip': do_this_to_ip,
                 'tcp': but_this_to_tcp}

    def __init__(self, indexed=False, action=None, protocol=None):
        self.indexed = indexed
        self.action = action
        self.protocol = protocol

    @property
    def valid(self):
        return self.protocol in self.PROTOCOLS

    @classmethod
    def from_string(cls, filter_): # avoid shadowing the built-in
        filter_ = filter_.split()
        if not filter_[0].isdigit():
            return cls()
        return cls(True, filter_[1], filter_[2])

rawDescription: In Practice, Should all the objects of a class be made to have same number of attributes?


code:
if 10 < a < 20:
    whatever

rawDescription: Is there a greater than but less than function in python?


rawDescription: Django - Model field define unicode

description: Django - Model field define unicode


code:
def decrementList(words):
    words_remaining = words[:]
    while words_remaining:
        url = 'http://ws.spotify.com/search/1/track.json?q='
        request = requests.get(url + '%20'.join(words_remaining))

        json_dict = json.loads(request.content)
        if json_dict['info']['num_results'] > 0:
            num_words_taken = len(words) - len(words_remaining)
            return num_words_taken, json_dict

        words_remaining.pop()

rawDescription: How to decrement a list index in a loop

description: Decrement a list index in a loop


rawDescription: Histogram of common string prefixes

description: Histogram of common string prefixes


code:
kernel3 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
kernel5 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
kernel7 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7))
t_lo = 136
t_hi = 224

blured = cv2.pyrMeanShiftFiltering(img, 3, 9)
#blured = cv2.bilateralFilter(img, 9, 32, 72)

clahe = cv2.createCLAHE(clipLimit=128.0, tileGridSize=(64, 64))
cl1 = clahe.apply(blured)
cl1 = 255 - cl1

ret, thresh_hi = cv2.threshold(cl1, t_hi, 255, cv2.THRESH_TOZERO)
ret, thresh_lo = cv2.threshold(cl1, t_lo, 255, cv2.THRESH_TOZERO)

rawDescription: Image processing issues with blood vessels


code:
import queue
q = queue.PriorityQueue()
class Foo(object):
    def __init__(self, bar):
        self.bar = bar
    def __eq__(self, other):
        return self.bar == other.bar
    def __ne__(self, other):
        return self.bar != other.bar
    def __lt__(self, other):
        return self.bar < other.bar
    def __gt__(self, other):
        return self.bar > other.bar
    def __le__(self, other):
        return self.bar <= other.bar
    def __ge__(self, other):
        return self.bar >= other.bar
f1 = Foo('foo')
f2 = Foo('bar')
f3 = Foo('baz')
f4 = Foo('baa')
f5 = Foo('baz')
q.put(f1)
q.put(f2)
q.put(f3)
q.put(f4)
q.put(f5)

rawDescription: Python equivalent of Java Comparator

description: Python equivalent of Java Comparator


code: df['ts'] = pd.to_datetime(df.date)

rawDescription: Pandas group by several values in a single column


code:
def poss_comb(coord):
    yield sorted(coord, key=lambda k: random.random())

rawDescription: Python: How to append generator iteration values to a list


code:
#one time init
os.environ['A_CONFIG_PATH'] = threading.local()

# set the value
def task(**kw):
    os.environ['A_CONFIG_PATH'].value = '/home/me/current/task/config/path'
    A.do_some_stuff(kw)

# read the value
config_path = os.environ['A_CONFIG_PATH'].value

rawDescription: What is a safe way to "bound" environment variable in python?


code:
import sys
del sys.modules['somemodule']
sys.modules['somemodule'] = __import__('somefakemodule')

from CustomModule import f

rawDescription: Replacing an imported module dependency

description: Replacing an imported module dependency


code:
#!/usr/bin/env python
import sys
def handle_ref(old, new, ref):
    with open('/tmp/out','w') as f:
        f.write(old,new,ref)
if __name__ == '__main__':
    with open('/tmp/out','w') as f:
        f.write('post-commit running')
    for line in sys.stdin:
        handle_ref(*line.split())
        with open('/tmp/out','w') as f:
            f.write('Got here')

rawDescription: git error: cannot spawn .git/hooks/post-commit: No such file or directory

description: Git error: cannot spawn .git/hooks/post-commit: No such file or directory


code:
def read_in_chunks(file_object, chunk_size=1024):
    """Lazy function (generator) to read a file piece by piece.
    Default chunk size: 1k."""
    while True:
        data = file_object.read(chunk_size)
        if not data:
            break
        yield data

f = open('really_big_file.dat')
for piece in read_in_chunks(f):
    process_data(piece)

rawDescription: Lazy Method for Reading Big File in Python?


code:
def make_children(df, levels):
    if len(levels) == 1:
        name, prefix = levels[0]
        level_cols = [name] + [c for c in df if c.startswith(prefix)]
        df = df[level_cols]
        key_names = ['name'] + [c.strip(prefix) for c in level_cols[1:]]
        return dict(zip(key_names, df.values[0]))
    else:
        h, tail = levels[0], levels[1:]
        name, prefix = h
        level_cols = [name] + [c for c in df if c.startswith(prefix)]

        data = []
        for keys, df_gb in df.groupby(level_cols):
            key_names = ['name'] + [c.strip(prefix) for c in level_cols[1:]]
            d = dict(zip(key_names, keys))
            d['children'] = make_children(df_gb, tail)
            data.append(d)
        return data

rawDescription: pandas df into nested json

description: Pandas df into nested json


code: new_list = old_list[:]

rawDescription: How to clone or copy a list in Python?

description: Clone or copy a list in Python


code:
WebDriverWait(browser, timeout=100).until(
      lambda x: x.find_element_by_id('audioplayer'))

rawDescription: Scraping the mp3 file from flash player after the conversion


code:
import re
soup.findAll('a', href=re.compile('^http://www.nhl.com/ice/boxscore.htm\?id='))

rawDescription: Find specific link w/ beautifulsoup

description: Find specific link w/ beautifulsoup


code:
import numpy
x = 1
y = 1
y = 1
v = numpy.array((x, y, z), dtype=float)

rawDescription: Biopython PDB: calculate distance between an atom and a point


rawDescription: How to test how many times a function has been called

description: Test how many times a function has been called


code:
# file 2: test_other.py, put this under same directory
import unittest
import test_me

suite = unittest.TestLoader().loadTestsFromModule(test_me)
unittest.TextTestRunner(verbosity=2).run(suite)

rawDescription: Run unittests from a different file

description: Run unittests from a different file


code:
from pandas import *
import numpy as np
from libraries.settings import *
from scipy.stats.stats import pearsonr
import itertools

rawDescription: Calculating pairwise correlation among all columns


code:
files = []
for (dirpath, dirnames, filenames) in walk(path):
    files.extend(filenames)
    files = [file.strip(".txt") for file in files]
    print(files)

rawDescription: Why is python not stripping?

description: Why is python not stripping


code:
'This is a first guid: {} and this is a second one: {}'.format(*(uuid.uuid4()
                                                               for _ in range(2)))

rawDescription: Call GUID function more than once in print formatting in python


code:
df
df.groupby(lambda x: re.match("[A-Z]+", x).group(), axis=1)
grouped = df.groupby(lambda x: re.match("[A-Z]+", x).group(), axis=1)

rawDescription: take a subset of a pandas data frame based on the column names

description: Take a subset of a pandas data frame based on the column names


code:
for row, data in enumerate(fileData):
    if conditionToAbortTheLoop:
        break

rawDescription: Loop thru a list and stop when the first string is found


code: Numbers = set([1,2,3])

rawDescription: Fastest and pythonic way of deletion of objects in this code


code:
import lxml.html as LH

code = '''some text here <c><d>Hi</d></c> and here'''

root = LH.fromstring(code)
print(root.text_content())
# some text here Hi and here

for elt in root:
    root.remove(elt)

print(LH.tostring(root))

rawDescription: lxml -- how to isolate element from children

description: Lxml -- how to isolate element from children


code: filtered_dict = {k:v for (k,v) in d.items() if filter_string in k}

rawDescription: filter items in a python dictionary where keys contain a specific string

description: Filter items in a python dictionary where keys contain a specific string


code:
import matplotlib.pyplot as plt
import numpy as np
x = np.genfromtxt('debug.dat')
plt.plot(x)
plt.show()

rawDescription: Python: memory problems in a script

description: Python: memory problems in a script


code:
from django.contrib.admin.views.main import ChangeList
class NewTitleChangeList(ChangeList):
    def __init__(self, *args, **kwargs):
        super(NewTitleChangeList, self).__init__(*args, **kwargs)
        self.title = "<New Title Here>"

class YourAdmin(admin.ModelAdmin):
    def get_changelist(self, request, **kwargs):
        return NewTitleChangeList

rawDescription: django changelist_view and changeform_view customizing

description: Django changelist_view and changeform_view customizing


code:
import os
import sys
path = os.environ['MY_IRONPYTHON_EXTRA_PATH']
sys.path.append(path)
import urllib
import httplib

rawDescription: Importing Python Librarys over C#?

description: Importing Python Librarys over C#


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

def generate_data(N = 20):
    data = [random.randrange(3) for x in range(N)]
    A = [i for i, x in enumerate(data) if x == 0]
    B = [i for i, x in enumerate(data) if x == 1]
    C = [i for i, x in enumerate(data) if x == 2]
    return A,B,C

def to_xy(*events):
    x, y = [], []
    for i,event in enumerate(events):
        y.extend([i]*len(event))
        x.extend(event)
    x, y = np.array(x), np.array(y)
    return x,y

def event_string(x,y):
    labels = np.array(list(string.uppercase))
    seq = labels[y[np.argsort(x)]]
    return seq.tostring()

def plot_events(x,y):
    labels = np.array(list(string.uppercase))
    plt.hlines(y, x, x+1, lw = 2, color = 'red')
    plt.ylim(max(y)+0.5, min(y)-0.5)
    plt.yticks(range(y.max()+1), labels)
    plt.show()

A,B,C = generate_data(20)
x,y = to_xy(A,B,C)
print(event_string(x,y))
plot_events(x,y)

rawDescription: How to plot events on time on using matplotlib

description: Plot events on time on using matplotlib


code:
urls = defaultdict(lambda: defaultdict(list))
with open('links.txt') as f:
    for url in f:
        parsed_url = urlparse(url.strip())
        params = parse_qsl(parsed_url.query, keep_blank_values=True)
        for key, value in params:
            urls[parsed_url.path][key].append(quote(value))

rawDescription: Determing variance in length

description: Determing variance in length


code:
twodates = Set(Couplet('firstdate', date(2014, 1, 1)), Couplet('seconddate', date(2016, 1, 1)))

def between_two_dates(rel):
    return twodates('firstdate').value < rel('col2').value < twodates('seconddate').value

only_in_range = sets.restrict(data_clan, between_two_dates)
print(only_in_range)

rawDescription: Comparing date object in a Couplet between two dates


code:
ans = ''
while not ans: # While the input given is an empty string
    ans = raw_input('Enter: ')

rawDescription: How to check for a necessary input of raw_input?

description: Check for a necessary input of raw_input


code:
class Game(models.Model):
    def __init__(self):
        self.moves = Moves()

class Moves():
    def __init__(self):
        self.moves = []

Game().moves
Game().moves
Game().moves

rawDescription: (For all instances of) Django model field 'moves', it maps to the same Move class instance


code: d = { 'foo': forms.CharField(max_length=100) }

rawDescription: Storing dynamic form in a model

description: Storing dynamic form in a model


code: filename = cmd.split(' ')[1]

rawDescription: Using part of input as a filename

description: Using part of input as a filename


rawDescription: How do I set remote server TimeZone via Fabric?

description: Set remote server TimeZone via Fabric


code: "...[t]he sender of the signal. Either a specific object or None."

rawDescription: If I send a python 'Signal' object from a function, what should the "sender" argument be?


rawDescription: Python 2.7 List of Lists Manipulation

description: Python 2.7 List of Lists Manipulation


rawDescription: Python : generating random numbers from a power law distribution


code:
if cid in report_v1.cache:
    report_v1.cache[cid] += 1
else:
    report_v1.cache[cid] = 1

rawDescription: Can I batch incrementing values in order to reduce database writes?

description: Batch incrementing values in order to reduce database writes


code: req = urllib2.Request('http://www.google.fr', None, headers)

rawDescription: Problem making a GET request and spoof User-Agent in urllib2


code: placeholder = sum(map(int, string_dict.values()))

rawDescription: Calculating the value of integers in list


code: return condition

rawDescription: Writing string comparing function in python


code: hash(str(d))

rawDescription: Python, checksum of a dict

description: Python, checksum of a dict


code:
from collections import defaultdict
from threading import Lock
import time

class UserBalancedJobQueue(object):

    def __init__(self):
        self._user_jobs = defaultdict(list)
        self._user_last_run = defaultdict(lambda: 0.0)
        self._lock = Lock()

    def pop_user_job(self):

        with self._lock:
            if not self._user_jobs:
                raise ValueError("No jobs to run")

            user = min(
                self._user_jobs.keys(),
                key=lambda u: self._user_last_run[u]
            )
            self._user_last_run[user] = time.time()

            jobs = self._user_jobs[user]
            job = jobs.pop(0)

            if not jobs:
                del self._user_jobs[user]

            return user, job

    def add_user_job(self, user, job):
        with self._lock:
            self._user_jobs[user].append(job)

rawDescription: Creating a thread-safe queue balancer

description: Creating a thread-safe queue balancer


code: [sorted(item, key=priority.get) for item in my_lists]

rawDescription: how to sort lists within list in user defined order?

description: Sort lists within list in user defined order


code:
import thirdparty

def MyFunc(some_arg):
    result = thirdparty.go()
    return result

rawDescription: Python embedded in CPP: how to get data back to CPP


rawDescription: Python - Addings nulls

description: Python - Addings nulls


code:
["".join([c for c in x if c not in punctuation])  for x in lis]
"".join([c for c in strs if c not in punctuation])

rawDescription: How to remove the punctuation in the middle of a word or numbers?

description: Remove the punctuation in the middle of a word or numbers


code:
for function, params in zip(functions, parameters):
    function(*params)

rawDescription: Python: Passing a list of function names and parameters to a class instance


code:
TERMINAL = None # Marks the end of a word

def build(words, trie=None): # bugs fixed
    if trie is None:
        trie = {}
    for word in words:
        if not word: continue # bug fixed
        pt = trie # bug fixed
        for ch in word:
            pt = pt.setdefault(ch, {})
        pt[TERMINAL] = True
    return trie

def find(input, trie):
    len_input = len(input)
    results = []
    for i in xrange(len_input):
        pt = trie
        for j in xrange(i, len_input + 1):
            if TERMINAL in pt:
                results.append(input[i:j])
            if j >= len_input or input[j] not in pt:
                break
            pt = pt[input[j]]
    return results

rawDescription: How can I improve my Trie implementation in terms of initialization?

description: Improve my Trie implementation in terms of initialization


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from numpy import linalg as LA
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d

class Arrow3D(FancyArrowPatch):

    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
        FancyArrowPatch.draw(self, renderer)
##########################################################################
# here i start with drawing the actual polyhedron and the vector
##########################################################################
# generate num random points in 3d
num = 5
# coord = 10*np.random.rand(3,num)#num points in 3D #first axis is x, second = y, third = z
#xcod = np.array([1,2,3,2.7,2.4,1])
xcod = np.array([1, 1, 1, 1, 1, 1])
ycod = np.array([1, 1, 4.5, 5., 6, 1])
zcod = np.array([1, -2, 0, 2, 3, 1])
#coord = np.concatenate(coord,coord[0])
# plotting in 3d
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# plotting all the points
ax.plot(xcod, ycod, zcod, 'x-')
# adding labels for vertice
for i in range(num):
    ax.text(xcod[i], ycod[i], zcod[i], '%d(%.2f,%.2f,%.2f)' %
            (i, xcod[i], ycod[i], zcod[i]))
# supposed centroid
centroid = np.array([np.mean(xcod), np.mean(ycod), np.mean(zcod)])
ax.scatter(centroid[0], centroid[1], centroid[2], marker='o', color='r')
# labelling the axes
ax.set_xlabel("x axis")
ax.set_ylabel("y axis")
ax.set_zlabel("z axis")
# getting a stack of all vertices, while removing last repeat vertex
cod = np.vstack(
    (np.delete(xcod, -1), np.delete(ycod, -1), np.delete(zcod, -1)))
# caculating covariance matrix
# ddof = 0 is using simple averages or normalising with N ; ddof = 1 means
# normalising with N-1
covmat = np.cov(cod, ddof=0)
# computing eigen values and eigen vectors
eigval, eigvec = LA.eig(covmat)
# multiplying eigen value and eigen vec
# for counter in range(len(eigval)):
#    eigvec[counter]= eigval[counter]*eigvec[counter]
##########################################################################
# plotting Eigen vectors
##########################################################################
for vec in eigvec.T:  # fetching one vector from list of eigvecs
    # drawing the vec, basically drawing a arrow form centroid to the end
    # point of vec
    vec += centroid
    drawvec = Arrow3D([centroid[0], vec[0]], [centroid[1], vec[1]], [centroid[2], vec[2]],
                      mutation_scale=20, lw=3, arrowstyle="-|>", color='r')
    # adding the arrow to the plot
    ax.add_artist(drawvec)
# plot show
plt.show()

rawDescription: plotting the eigenvector of covariance matrix using matplotlib and np.linalg

description: Plotting the eigenvector of covariance matrix using matplotlib and np.linalg


code: [(user, max(date for u, date in myList if u == user)) for user, _ in myList]

rawDescription: Complex python list processing

description: Complex python list processing


rawDescription: Pandas: how to concisely detrend subset of columns


code:
result = defaultdict(set)
for key, value in zip(keys, values):
    result[key].add(value)

rawDescription: Find same elements in a list, and then change these elemens to tuple (f.e. 2 to (2,1))


rawDescription: Divide one column in array by another numpy


code: accuracy = num_tokens_correct / total_num_tokens_from_gold

rawDescription: IOB Accuracy on NLTK named entity recognition


rawDescription: Perform Numpy operation on matrix of user-defined type items


rawDescription: Wrapping Selenium "Expected Conditions" Python


code:
import json
from scrapy.spider import Spider
from scrapy.http import Request
from nba.items import LineupItem
from urllib import urlencode

class StatsSpider(Spider):
    name = "stats"
    allowed_domains = ["stats.nba.com"]
    start_urls = (
        'http://stats.nba.com/',
        )

    def parse(self, response):
        return self.get_lineup('1610612739','2008-09')

    def get_lineup(self, team_id, season):
        params = {
            'Season':         season,
            'SeasonType':     'Regular Season',
            'LeagueID':       '00',
            'TeamID':         team_id,
            'MeasureType':    'Base',
            'PerMode':        'Per48',
            'PlusMinus':      'N',
            'PaceAdjust':     'N',
            'Rank':           'N',
            'Outcome':        '',
            'Location':       '',
            'Month':          '0',
            'SeasonSegment':  '',
            'DateFrom':       '',
            'DateTo':         '',
            'OpponentTeamID': '0',
            'VsConference':   '',
            'VsDivision':     '',
            'GameSegment':    '',
            'Period':         '0',
            'LastNGames':     '0',
            'GroupQuantity':  '5',
            'GameScope':      '',
            'GameID':         '',
            'pageNo':         '1',
            'rowsPerPage':    '100',
            'sortField':      'MIN',
            'sortOrder':      'DES'
        }
        return Request(
            url="http://stats.nba.com/stats/teamdashlineups?" + urlencode(params),
            dont_filter=True,
            callback=self.parse_lineup
        )

    def parse_lineup(self,response):
        data = json.loads(response.body)
        for lineup in data['resultSets'][1]['rowSet']:
            item = LineupItem()
            item['group_set'] = lineup[0]
            item['group_id'] = lineup[1]
            item['group_name'] = lineup[2]
            item['gp'] = lineup[3]
            item['w'] = lineup[4]
            item['l'] = lineup[5]
            item['w_pct'] = lineup[6]
            item['min'] = lineup[7]
            item['fgm'] = lineup[8]
            item['fga'] = lineup[9]
            item['fg_pct'] = lineup[10]
            item['fg3m'] = lineup[11]
            item['fg3a'] = lineup[12]
            item['fg3_pct'] = lineup[13]
            item['ftm'] = lineup[14]
            item['fta'] = lineup[15]
            item['ft_pct'] = lineup[16]
            item['oreb'] = lineup[17]
            item['dreb'] = lineup[18]
            item['reb'] = lineup[19]
            item['ast'] = lineup[20]
            item['tov'] = lineup[21]
            item['stl'] = lineup[22]
            item['blk'] = lineup[23]
            item['blka'] = lineup[24]
            item['pf'] = lineup[25]
            item['pfd'] = lineup[26]
            item['pts'] = lineup[27]
            item['plus_minus'] = lineup[28]
            yield item

rawDescription: crawl dynamic webpage for data using scrapy

description: Crawl dynamic webpage for data using scrapy


rawDescription: Python native parsing of path names with unknown path separators


code:
iter(range(10))
result=_
result
list(result)

rawDescription: Python - reference object in memory by address


code:
mass = 1
radius = 14
inertia = pymunk.moment_for_circle(mass, 0, radius, (0,0))
body = pymunk.Body(mass, inertia)
x, y = random.randint(0, 200), random.randint(0, 200)
body.position = x, 550
shape = pymunk.Circle(body, radius, (0,0))
shape.sensor = True
space.add(body, shape)

rawDescription: Simulating a simple physics related scenario


code:
def __str__(self):
    return ''.join([i for i in vars(self).values() if isinstance(i, A)])

rawDescription: Filter attributes of a class based on the type


code:
df = pd.read_csv('data', dtype=object, encoding='utf-8')
df = df.set_index('Contract')

rawDescription: Numbers used as string in Pandas index

description: Numbers used as string in Pandas index