code:
IfcFile = open('ifc2.ifc', 'r')

#defines the string
IfcColourData = re.compile('ifccolourrgb', re.IGNORECASE)

f = open('IFC2RAD.txt', 'w')    # opne file to write here

for RadColourData in IfcFile:
    if re.search(IfcColourData, RadColourData):
        print(RadColourData)
        f.write(RadColourData)      # write here to file
IfcFile.close()
f.close()

rawDescription: Writing Regular Expressions to a file Python


code:
import urlparse
urlparse.parse_qsl(entry)
urlparse.parse_qsl(entry)[0][1][:3]

rawDescription: Extracting text in the middle of a string - python


code:
from PySide import QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.widgetObject = QtGui.QTextEdit(self)
        self.button = QtGui.QPushButton('Hide Widget', self)
        self.button.clicked.connect(self.hideAndShowWidget)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)
        layout.addWidget(self.widgetObject)
        self.setFixedSize(300, 200)

    def hideAndShowWidget(self):
        height = self.height()
        if self.widgetObject.isVisible():
            height -= self.widgetObject.height()
            self.widgetObject.setVisible(False)
            self.button.setText('Show Widget')
        else:
            height += self.widgetObject.height()
            self.widgetObject.setVisible(True)
            self.button.setText('Hide Widget')
        self.setFixedSize(self.width(), height)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: How to resize the main window again after setFixedSize()?

description: Resize the main window again after setFixedSize()


rawDescription: Python extract sentence containing word

description: Python extract sentence containing word


code:
import Image
im = Image.open('1_tree.jpg')
im = im.convert('RGB')
r, g, b = im.split()
r = r.point(lambda i: i * 1.5)
out = Image.merge('RGB', (r, g, b))
out.show()

rawDescription: Multiply each pixel in an image by a factor


code:
lines1 = [i.split() for i in open('tmp.txt').readlines()]
values,keys = zip(*lines1)
dict1 = dict( zip(keys,values) )
lines2 = [i.split() for i in open('tmp2.txt').readlines()]
values,keys = zip(*lines2)
dict2 = dict( zip(keys,values) )
dict3 = {}
for k1,v1 in dict1.items():
    v2 = dict2.get(k1)
    if v2:
        dict3[k1] = str(float(v1)/float(v2))
    else:
        dict3[k1] = v1
for k2,v2 in dict2.items():
    if not dict3.get(k2):
        dict3[k2] = v2
out = open('output.txt','w')
out.writelines(['%s\t%s\n' %\
    (k[0],dict3[k[0]]) for k in sorted(dict3.items(), key=lambda x:x[1])])
out.close()

rawDescription: python program to combine two files (that have wordcount) and issue a ratio

description: Python program to combine two files (that have wordcount) and issue a ratio


rawDescription: Where am I in a chain of indexing?

description: Where am I in a chain of indexing


code:
btnAlignX = cmds.button(label='X', c=lambda *_:self.TakeAction('X'))
btnAlignY = cmds.button(label='Y', c=lambda *_:self.TakeAction('Y'))
btnAlignZ = cmds.button(label='Z', c=lambda *_:self.TakeAction('Z'))

rawDescription: maya python + Pass variable on button press

description: Maya python + Pass variable on button press


code:
from tkinter import *

root = Tk()
canvas = Canvas(root, width=200, height=200, bd=0,
                highlightthickness=0)
canvas.pack()

mask = PhotoImage(width=200, height=200)
cx,cy = 100,100 # image & circle center point
r = 100         # circle radius
r_squared = r*r
for y in range(200):
    for x in range(200):
        # using the formula for a circle:
        # (x - h)^2 + (y - k)^2 = r^2
        # any pixel outside our circle gets filled
        if (x - cx)**2 + (y - cy)**2 > r_squared:
            mask.put('blue', (x,y))

canvas.create_image(100,100, image=mask, anchor='c')

myimage = PhotoImage(file='bigpython.gif')
item = canvas.create_image(100,100, image=myimage, anchor='c')
canvas.lower(item)

root.mainloop()

rawDescription: Filling a Tkinter Canvas Element with an Image


code: tf.select(array < 50, tf.zeros_like(array), array)

rawDescription: Tensorflow equivalent for Numpy indexed assignment


code:
import decimal
myothercontext = decimal.Context(rounding=decimal.ROUND_HALF_UP)
decimal.setcontext(myothercontext)
TWOPLACES = decimal.Decimal(10) ** -2
decimal.Decimal('111.175').quantize(TWOPLACES)
decimal.Decimal('1.175').quantize(TWOPLACES)
decimal.Decimal('11.175').quantize(TWOPLACES)

rawDescription: workaround for an error-looking rouding

description: Workaround for an error-looking rouding


code:
from scipy import linalg as la
e = la.eigvals(my_matrix)
hist,xedges,yedges = np.histogram2d(e.real,e.imag,bins=40,normed=False)

rawDescription: Find density of points from their scatter plot in python


code:
CWD = "/my/other/dir/"
files = map(lambda x: x[len(CWD):], glob.glob(CWD + "*.txt"))
subprocess.call(['ls'] + files, cwd=CWD)

rawDescription: Python, using glob with cwd argument to subprocess.call


code:
import time

for i in range(5):
    time.sleep(1)
    print('Now it is: ' + str(i), end='\r')

rawDescription: How to update a number in the python shell without showing a list

description: Update a number in the python shell without showing a list


code:
from Tkinter import Tk, Text
from tkFont import Font

class BlockyCursorText(Text):

    def __init__(self, parent):
        Text.__init__(self, parent, bg='black', fg='green', insertwidth=0,
                      font=Font(family='Courier', size=10))

        # initialize the cursor position and the color of the cursor
        self.cursor = '1.0'
        self.switch = 'green'

        self._blink_cursor()
        self._place_cursor()

    def _place_cursor(self):
        '''check the position of the cursor against the last known position
        every 15ms and update the cursorblock tag as needed'''

        current_index = self.index('insert')

        if self.cursor != current_index:  # if the insertcursor moved
            self.cursor = current_index   # store the new index
            self.tag_delete('cursorblock')# delete the cursorblock tag

            start = self.index('insert')  # get the start
            end = self.index('insert+1c') # and stop indices

            if start[0] != end[0]:         # this handles an index that
                self.insert(start, ' ')    # reaches the end of the line
                end = self.index('insert') # by inserting a space

            self.tag_add('cursorblock', start, end) # add the tag back in
            self.mark_set('insert', self.cursor)    # move the insertcursor

        self.after(15, self._place_cursor)

    def _blink_cursor(self):
        '''alternate the background color of the cursorblock tagged text
        every 600 milliseconds'''

        if self.switch == 'green':
            self.switch = 'black'
        else:
            self.switch = 'green'

        self.tag_config('cursorblock', background=self.switch)

        self.after(600, self._blink_cursor)

if __name__ == '__main__':

    root = Tk()

    text = BlockyCursorText(root)
    text.pack()
    text.insert('1.0', 'hello world')

    root.mainloop()

rawDescription: Is there an easy way to make a blocky insert cursor for the Tkinter Text widget?


rawDescription: python Decimal - checking if integer

description: Python Decimal - checking if integer


code:
import glob
glob.glob('./[0-9].*')
glob.glob('*.gif')
glob.glob('?.gif')

rawDescription: Search a folder for files like "/*tmp*.log" in Python


code:
for idx in range(len(versionSplit)-1, -1, -1):
    i = versionSplit[idx]
    if chunk.isdigit():
        digit = '%0'+str(len(i))+'d'
        i = int(i) + 1
        i = digit % i
        versionSplit[idx]=str(i)
        break

rawDescription: String manipulation weirdness when incrementing trailing digit


code:
import pymysql
from bottle import Bottle,run

app = Bottle()

@app.route('/conn')
def conn():
    yield "Trying to connect to database..."
    try:
        conn = pymysql.connect(user="X",passwd="X",host="X",port=X,database="X")
        yield "Connection succeded"
    except:
        yield "Oops...connection failed"

run(app, host='localhost',port = 8080)

rawDescription: Using bottle.py to print on browser

description: Using bottle.py to print on browser


code:
L = [2,4,8,9,4,2]
[sum(i) for i in itertools.zip_longest(*[iter(L)]*2, fillvalue=0)]

rawDescription: Python: Can I add every other integer in a list?


code:
import mock

@mock.patch("os.listdir")
def test_mod1(mock_dont_call):
    import mod1
    assert mod1.bar()=='foo'

if __name__=="__main__":
    test_mod1()

rawDescription: Mock function called on import

description: Mock function called on import


code:
def lol(a):
    a[:] = [1]
    return a

k = [2, 3]
lol(k) # now k is equal to [1]

rawDescription: global/inner variable conflict? (python)

description: Global/inner variable conflict? (python)


rawDescription: writing a 1024 bits length decimal number in a binary file with python

description: Writing a 1024 bits length decimal number in a binary file with python


code:
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure( figsize=(5.5,7.5) )

gs1 = GridSpec(1, 1)
gs1.update(left=0.05, right=0.95, top=0.95, bottom=0.85, wspace=0.05)
ax1 = plt.subplot(gs1[0])
ax1.set_xticks([])
ax1.set_yticks([])

gs2 = GridSpec(5, 2)
gs2.update(top=0.75, hspace=0.05)

for i in gs2:
    ax = plt.subplot(i)
    ax.set_xticks([])
    ax.set_yticks([])

ax1.set_xlabel('Text Text Text',fontsize=8)
fig.text(0.03,0.45,'some label',rotation='vertical')

plt.show()

rawDescription: Subplot-specific spacing and Single axis label


code:
from suds.sax.element import Element

ns_mod = ('mod', 'http://models.ws.common.abc.com')

header = Element('adtwsHeader', ns=ns_mod)
container = Element('adtwss', parent=header)

username = Element('userName', parent=container)
username.setText('usernameGoesHere')

password = Element('password', parent=container)
password.setText('myPassword123')

client.set_options(soapheaders=header)

rawDescription: How to script SOAP based web service using SUDS python package

description: Script SOAP based web service using SUDS python package


code: print("ASD", end="\r\n")

rawDescription: Python in raw mode stdin print adds spaces


code:
from itertools import imap
from operator import mul
def sumsquared(arr):
    return sum(imap(mul, arr, arr))

rawDescription: Optimising a simple mathematical calculation over list


code:
import urllib2
myip = urllib2.urlopen("http://myip.dnsdynamic.org/").read()

rawDescription: What is the best way to get the external IP of a machine in python?


code:
def delta_format(days, hours):
    if days > 0 and hours > 0:
        return "{0:.0f} d, {1:.0f} h".format(days, hours)
    elif days > 0:
        return "{0:.0f} d".format(days)
    else:
        return "{0:.0f} h".format(hours)

days = time_delta.astype("timedelta64[D]")
hours = time_delta.astype("timedelta64[h]") % 24
return [delta_format(d, h) for (d, h) in izip(days, hours)]

rawDescription: Format timedelta64 string output

description: Format timedelta64 string output


code:
string = "Article One News"
words = string.split()

i = 0
while i < len(words):
    word = words[i]
    # Do whatever you want with this word
    i += 1

rawDescription: Using a while loop instead of for to count words and locate instances in string


code: filtered = list(filter(any, a))

rawDescription: How can I remove None elements from list of lists

description: Remove None elements from list of lists


code:
from functools import partial

def evaluate(match, mappings):
    return str(eval(match.group(0)[2:-1], mappings))

mappings = {'A': 1, 'B': 2}  # Or whatever ...

newstring = sub(r'\#\{([^#]+)\}', partial(evaluate, mappings=mappings), string)

rawDescription: How to pass a variable to a re.sub callback?

description: Pass a variable to a re.sub callback


code:
import rpy2.robjects as robjects
from  rpy2.robjects.packages import importr

def length_(s):
    stringi = importr("stringi")
    return stringi.stri_length(s)[0]

sc.parallelize(["foo", "bar", "foobar"]).map(length_)

rawDescription: Can I connect an external (R) process to each pyspark worker during setup

description: Connect an external (R) process to each pyspark worker during setup


code:
from sqlalchemy.ext.hybrid import hybrid_method

class Foo(base):
    foo_id = Column(Integer, primary_key=True)
    foo_data = Column(String(255))

    @hybrid_method
    def check_foo(self):
        return self.foo_data == 'foo'

    @check_foo.expression
    def check_foo(cls):
        return cls.foo_data == 'foo'

session.query(Foo).filter(Foo.check_foo()).all()

rawDescription: SQLAlchemy: Use a function to determine what results a query returns


code: s = set(e[1] for e in l)

rawDescription: Find unique elements in tuples in a python list


rawDescription: remove elements from an list and then choose two random elements for a new list

description: Remove elements from an list and then choose two random elements for a new list


code:
a, *b, c = range(5)
a
c
b

rawDescription: Python - Store varying number of elements in a list?


code:
import os
import sys
def gtime(nam):
    return os.path.getmtime('./'+nam)
files = os.listdir('.')
files.remove(str(sys.argv[0])[2:])
files = sorted(files, key=gtime)
for fi, file in enumerate(files):
    os.rename(file, str(fi+1)+".tmp")
for fi in range(len(files)):
    os.rename(str(fi+1)+".tmp", str(fi+1))

rawDescription: Python Script to sort and rename files - Removes duplicates


code:
MailList = ["email1@gmail.com", "email2@gmail.com", "email3@gmail.com"]

for index, value in enumerate(MailList):
    print('user {} is {}'.format(index, value.split("@")[0]))

rawDescription: Index of element from the list

description: Index of element from the list


rawDescription: How to hide vertical/horizontal lines in QTableWidget

description: Hide vertical/horizontal lines in QTableWidget


code: my_table = [elem for elem in my_table if elem[1:] != ('bananas', 1)]

rawDescription: How do I delete a tuple in a list based on a value in the tuple?

description: Delete a tuple in a list based on a value in the tuple


code:
import jinja2
t = jinja2.Template("{% for i in items[:3] %}{{ i }}\n{% endfor %}")
items = range(10)
print(t.render(items=items))

rawDescription: Looping over subset in Jinja

description: Looping over subset in Jinja


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import matplotlib.patches as mpatches

def add_arrow_to_line2D(
    axes, line, arrow_locs=[0.2, 0.4, 0.6, 0.8],
    arrowstyle='-|>', arrowsize=1, transform=None):
    """
    Add arrows to a matplotlib.lines.Line2D at selected locations.

    Parameters:
    -----------
    axes:
    line: list of 1 Line2D obbject as returned by plot command
    arrow_locs: list of locations where to insert arrows, % of total length
    arrowstyle: style of the arrow
    arrowsize: size of the arrow
    transform: a matplotlib transform instance, default to data coordinates

    Returns:
    --------
    arrows: list of arrows
    """
    if (not(isinstance(line, list)) or not(isinstance(line[0],
                                           mlines.Line2D))):
        raise ValueError("expected a matplotlib.lines.Line2D object")
    x, y = line[0].get_xdata(), line[0].get_ydata()

    arrow_kw = dict(arrowstyle=arrowstyle, mutation_scale=10 * arrowsize)

    color = line[0].get_color()
    use_multicolor_lines = isinstance(color, np.ndarray)
    if use_multicolor_lines:
        raise NotImplementedError("multicolor lines not supported")
    else:
        arrow_kw['color'] = color

    linewidth = line[0].get_linewidth()
    if isinstance(linewidth, np.ndarray):
        raise NotImplementedError("multiwidth lines not supported")
    else:
        arrow_kw['linewidth'] = linewidth

    if transform is None:
        transform = axes.transData

    arrows = []
    for loc in arrow_locs:
        s = np.cumsum(np.sqrt(np.diff(x) ** 2 + np.diff(y) ** 2))
        n = np.searchsorted(s, s[-1] * loc)
        arrow_tail = (x[n], y[n])
        arrow_head = (np.mean(x[n:n + 2]), np.mean(y[n:n + 2]))
        p = mpatches.FancyArrowPatch(
            arrow_tail, arrow_head, transform=transform,
            **arrow_kw)
        axes.add_patch(p)
        arrows.append(p)
    return arrows

y = np.linspace(0, 100, 200)
x = np.cos(y/5.)

fig, ax = plt.subplots(1, 1)
# print the line and the markers in seperate steps
line = ax.plot(x, y, 'k-')
add_arrow_to_line2D(ax, line, arrow_locs=np.linspace(0., 1., 200),
                    arrowstyle='->')

plt.show()

rawDescription: Matplotlib curve with arrow ticks

description: Matplotlib curve with arrow ticks


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup("""

    Some text that I have to wrap in figcaption

""")
for figure in soup.find_all("figure"):
    img = figure.find("img")
    if img is not None:
        figcaption = soup.new_tag("figcaption")
        for el in list(img.next_siblings):
            figcaption.append(el)
        img.insert_after(figcaption)

soup

rawDescription: Wrap all next_elements in BeautifulSoup

description: Wrap all next_elements in BeautifulSoup


code:
import dbus
bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.NetworkManager',
                       '/org/freedesktop/NetworkManager/Devices/eth0')
# proxy is a dbus.proxies.ProxyObject

rawDescription: Handling Multiple Network Interfaces in Python


code:
from itertools import product
Dists = [list(p) for p in product(Grid, repeat=3) if sum(p) == 1]

rawDescription: Python nesting list comprehensions with variable depth


code:
import numpy as np
import re

r = re.compile('[Ab]')
vmatch = np.vectorize(lambda x:bool(r.match(x)))

A = np.array(list('abc abc abc'))
sel = vmatch(A)

rawDescription: Selecting elements in numpy array using regular expressions


code:
for c in colors[:]:
    if c == 'green':
        colors.remove(c)

rawDescription: Remove elements as you traverse a list in Python


code:
names = [foo, fooooo, bar, baaar]
a, b = i.index(max(name, key=len)), -1
i[b], i[a] = i[a], i[b]

rawDescription: Python names in a list

description: Python names in a list


code:
import sys

print("idlelib" in sys.modules)

rawDescription: find out if a python script is running in idle or terminal/command prompt

description: Find out if a python script is running in idle or terminal/command prompt


code:
def get_repr(value):
    if callable(value):
        return '%s' % value()
    return value

def get_field(instance, field):
    field_path = field.split('.')
    attr = instance
    for elem in field_path:
        try:
            attr = getattr(attr, elem)
        except AttributeError:
            return None
    return attr

for field in fields:
    context['project'][field] = get_repr(get_field(project, field))

rawDescription: How to get foreign key values with getattr from models

description: Get foreign key values with getattr from models


code:
import decimal

def float_to_decimal(f):
    # http://docs.python.org/library/decimal.html#decimal-faq
    "Convert a floating point number to a Decimal with no loss of information"
    n, d = f.as_integer_ratio()
    numerator, denominator = decimal.Decimal(n), decimal.Decimal(d)
    ctx = decimal.Context(prec=60)
    result = ctx.divide(numerator, denominator)
    while ctx.flags[decimal.Inexact]:
        ctx.flags[decimal.Inexact] = False
        ctx.prec *= 2
        result = ctx.divide(numerator, denominator)
    return result

def f(number, sigfig):
    # http://stackoverflow.com/questions/2663612/nicely-representing-a-floating-point-number-in-python/2663623#2663623
    assert(sigfig>0)
    try:
        d=decimal.Decimal(number)
    except TypeError:
        d=float_to_decimal(float(number))
    sign,digits,exponent=d.as_tuple()
    if len(digits) < sigfig:
        digits = list(digits)
        digits.extend([0] * (sigfig - len(digits)))
    shift=d.adjusted()
    result=int(''.join(map(str,digits[:sigfig])))
    # Round the result
    if len(digits)>sigfig and digits[sigfig]>=5: result+=1
    result=list(str(result))
    # Rounding can change the length of result
    # If so, adjust shift
    shift+=len(result)-sigfig
    # reset len of result to sigfig
    result=result[:sigfig]
    if shift >= sigfig-1:
        # Tack more zeros on the end
        result+=['0']*(shift-sigfig+1)
    elif 0<=shift:
        # Place the decimal point in between digits
        result.insert(shift+1,'.')
    else:
        # Tack zeros on the front
        assert(shift<0)
        result=['0.']+['0']*(-shift-1)+result
    if sign:
        result.insert(0,'-')
    return ''.join(result)

if __name__=='__main__':
    tests=[
        (0.1, 1, '0.1'),
        (0.0000000000368568, 2,'0.000000000037'),
        (0.00000000000000000000368568, 2,'0.0000000000000000000037'),
        (756867, 3, '757000'),
        (-756867, 3, '-757000'),
        (-756867, 1, '-800000'),
        (0.0999999999999,1,'0.1'),
        (0.00999999999999,1,'0.01'),
        (0.00999999999999,2,'0.010'),
        (0.0099,2,'0.0099'),
        (1.999999999999,1,'2'),
        (1.999999999999,2,'2.0'),
        (34500000000000000000000, 17, '34500000000000000000000'),
        ('34500000000000000000000', 17, '34500000000000000000000'),
        (756867, 7, '756867.0'),
        ]

    for number,sigfig,answer in tests:
        try:
            result=f(number,sigfig)
            assert(result==answer)
            print(result)
        except AssertionError:
            print('Error',number,sigfig,result,answer)

rawDescription: Nicely representing a floating-point number in python


code:
import timeit

class A:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

class B:
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

class C:
    def __init__(self, name, age):
        self.name = name
        self.age = age

def initialize_class_a():
    a = A(name="J Smith", age=20)
    b = A(name="B Jones", age=40)
    return a.name, b.name

def initialise_class_b():
    a = B(name="J Smith", age=20)
    b = B(name="B Jones", age=40)
    return a.name, b.name

def initialise_class_c():
    a = C(name="J Smith", age=20)
    b = C(name="B Jones", age=40)
    return a.name, b.name

print(initialize_class_a())
# ('J Smith', 'B Jones')
print(initialise_class_b())
# ('J Smith', 'B Jones')
print(initialise_class_c())
# ('J Smith', 'B Jones')

print(timeit.timeit("initialize_class_a()", "from __main__ import initialize_class_a"))
# 1.93
print(timeit.timeit("initialise_class_b()", "from __main__ import initialise_class_b"))
# 2.19
print(timeit.timeit("initialise_class_c()", "from __main__ import initialise_class_c"))
# 1.03

rawDescription: Python initialising objects with kwargs

description: Python initialising objects with kwargs


code:
for line in soup.find_all("a"):
    print(line.text.strip())

rawDescription: Python beautifulsoup how to get the line after 'href'


code:
import pandas as pd
df = pd.DataFrame(data).T
df.columns = [c[0] for c in characteristics]
df
colors = [c[1] for c in characteristics]
df.sort_index(ascending=False).plot(kind='barh', color=colors)

rawDescription: Multidimensional data and plot legends

description: Multidimensional data and plot legends


code:
import urllib2
from StringIO import StringIO

url = urllib2.urlopen('http://example.com/foo.jpg')
f = StringIO()
zip = zipfile.ZipFile(f, 'w')
zip.writestr('foo.jpg', url.read())
response = HttpResponse(f.getvalue(), content_type="application/zip")
response['Content-Disposition'] = 'attachment; filename=foobar.zip'
return response

rawDescription: Downloading images from url in memory and creating zip archive in memory to send to the browser


code: self.menuBar.EnableTop(0, False)

rawDescription: wxPython - Disable a whole menu

description: WxPython - Disable a whole menu


code:
def dot_product(v, w):
    return np.einsum('...j,...j->...', v, w)

def matrix_vector_product(M, v):
    return np.einsum('...jk,...k->...j', M, v)

def matrix_matrix_product(A, B):
    return np.einsum('...jk,...kl->...jl', A, B)

rawDescription: numpy dot product and matrix product

description: Numpy dot product and matrix product


code:
SEX = [
    ("M","guy"),
    ("F","girl")
]
SEX_DICT = dict(SEX)

rawDescription: django (but really python) curio about tuples

description: Django (but really python) curio about tuples


code:
def init_service(cls):
    class InitService(cls):
        def __init__(self, port='ignored'):
            super(InitService).__init__(5432)

    return InitService

rawDescription: How can I decorate a "callable" class with a class decorator?

description: Decorate a "callable" class with a class decorator


code:
from subprocess import Popen,PIPE

def subprocess_cmd(dr,cmd1,cmd2):
    p1 = Popen(cmd1.split(),stdout=PIPE,cwd=dr)
    p2 = Popen(cmd2.split(),stdin=p1.stdout,stdout=PIPE,cwd=dr)
    p1.stdout.close()
    return p2.communicate()[0]

subprocess_cmd('/Users/aakashshah/documents/python/','open -a Terminal','python test.py')

rawDescription: python - subprocess - Open terminal with a file

description: Python - subprocess - Open terminal with a file


code:
def view2(request):
    if request.method == 'POST':
        page_list=request.POST.values()
    else:
        HttpResponseRedirect('/urls/')

rawDescription: how to pass a list between views in django

description: Pass a list between views in django


code:
class TextFormatter:
    def __init__(self,lynx='/usr/bin/lynx'):
        self.lynx = lynx

    def html2text(self, unicode_html_source):
        "Expects unicode; returns unicode"
        return Popen([self.lynx,
                      '-assume-charset=UTF-8',
                      '-display-charset=UTF-8',
                      '-dump',
                      '-stdin'],
                      stdin=PIPE,
                      stdout=PIPE).communicate(input=unicode_html_source.encode('utf-8'))[0].decode('utf-8')

rawDescription: Python strategy for extracting text from malformed html pages


code:
location = re.search(r".*foreign\s*currenc(y|ies)(.*)", f5)
location.group(2)

rawDescription: Using regex to extract string position Python


rawDescription: python: list append - each time create a new list?

description: Python: list append - each time create a new list


code:
class cars(object):
    def chassis(self):
        pass  # Do cars stuff

class automobile(cars):
    def chassis(self):
        super().chassis()  # Call super class's chassis
        # Do automobile stuff

class truck(cars):
    def chassis(self):
        super().chassis()
        # Do truck stuff

rawDescription: Python OOP different method names

description: Python OOP different method names


code:
import csv

def import_text(filename, separator):
  for line in csv.reader(open(filename), delimiter=separator, skipinitialspace=True):
    if line[19]:
      for elt in line[19].split(separator):
        yield elt.strip()

for data in import_text('filename.csv', ','):
  print (data)

rawDescription: Parse CSV and seperate fields with multiple values


code:
import argparse
parser=argparse.ArgumentParser()
parser.add_argument("cubefile",nargs="?",default=False)
#'nargs="?"' makes the argument optional
#-meaning an error will not be thrown if no file is parsed on execution
args=parser.parse_args()
if args.universefile != False:
    init_defaultcube = cubetools.getCubeFromCubeFileDir(args.universefile)
    #cubetools is my class and getCubeFromCubeFileDir just interprets the text in the file

rawDescription: Opening custom file types in cxFreeze complied python executable on opening file


code:
import codecs

original_document_encoding = "shift-jis" # common japanese encoding.
with codecs.open("rshmn10j.txt", 'r', encoding=original_document_encoding) as in_f:
    unicode_content = in_f.read()

with codecs.open("rshmn10j.out.txt", 'w', encoding='utf-8') as out_f:
    out_f.write(unicode_content)

rawDescription: How to use codecs to convert from one language to a utf-8 encoded document?

description: Use codecs to convert from one language to a utf-8 encoded document


code:
class DbBase:
    table = None
    @property
    def t(self):
        return self.table

class Articles(DbBase):
    table = {} # for demo purposes

A = Articles()
A.t # returns {}

rawDescription: Python - Automatically update base class attribute (alias) in inherited class


code:
import os

save_filename = asksaveasfilename()
save_filename_split = os.path.split(save_filename)
save_filename_length = os.path.join(save_filename_split[0],
                                     'length'+save_filename_split[-1])

rawDescription: Writing Another Text File based on Saved File from Tkinter


code:
df2 = df.set_index('month_year')
df2 = df2.sort_index()
df2
df2.reindex(pd.period_range(df2.index[0],df2.index[-1],freq='M'))
df2['customer_id'] = 12
df2.fillna(0.0)

rawDescription: Pandas: Add data for missing months

description: Pandas: Add data for missing months


code:
params = { 'test[key1]' : 'val1', 'test[key2]' : 'val42' }
r = requests.post('http://httpbin.org/post', data=params)
json.loads(r.text)['form']

rawDescription: python-requests - Sending via POST form with square brackets names doesn't work

description: Python-requests - Sending via POST form with square brackets names doesn't work


code:
def delete_images(image_id):
    ImagenAvaluo.objects.filter(image_id=image_id).delete()

rawDescription: How do I return to the calling view in django?

description: Return to the calling view in django


code:
def get_location_summary(location_name):
    output = "This is my output stored in a variable. My location is: " + location_name
    """ return the output to the caller """
    return output

def main():
    """Prompts for user input to a location name"""
    location_name = input('Please enter a location name: ')
    """print below calls the function which returns the value that was stored in the output variable inside get_location_summary. This value is then printed"""
    print(get_location_summary(location_name))

if __name__ == "__main__":
    main()

rawDescription: how to print results of function as the result of a input function?

description: Print results of function as the result of a input function


code:
def testStatic(self, request):
    assert isinstance(request, TestRequest)
    ...

rawDescription: Doing a static type checking at method level, python


code:
G = nx.erdos_renyi_graph(8,0.4)
p = nx.shortest_path(G,0,3)
# Set all edge color attribute to black
for e in G.edges():
    G[e[0]][e[1]]['color'] = 'black'
# Set color of edges of the shortest path to green
for i in xrange(len(p)-1):
    G[p[i]][p[i+1]]['color'] = 'blue'
# Store in a list to use for drawing
edge_color_list = [ G[e[0]][e[1]]['color'] for e in G.edges() ]
nx.draw(G,edge_color = edge_color_list, with_labels = True)
plt.show()

rawDescription: python networkx - mark edges by coloring for graph drawing

description: Python networkx - mark edges by coloring for graph drawing


code:
import json

class Event(object):
    __slots__= 'itemName'

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

    def to_dict(self):
        obj = {}
        obj['itemName'] = self.itemName
        return obj

    @classmethod
    def from_dict(cls, obj):
        e = cls(obj['itemName'])
        return e

class EventPacket(object):
    __slots__= 'pID', 'eventData'

    def __init__(self, pID, eventData):
        self.pID = pID
        self.eventData = eventData

    def to_dict(self):
        obj = {}
        obj['pID'] = int(self.pID)
        obj['eventData'] = self.eventData.to_dict()

        return obj

    @classmethod
    def from_dict(cls, obj):
        ep = cls(obj['pID'])
        ep.eventData = Event.from_dict(obj['eventData'])
        return ep

example_event = Event('Dflt')
example_packet = EventPacket(1, example_event)

json_string = json.dumps(example_packet.to_dict())

recovered_example_packet = EventPacket.from_dict(json.loads(json_string))

rawDescription: Python JSON quoted data for sub class info


code:
from itertools import combinations
with open("rand.txt","w") as f:
    combs = [x for x in combinations(range(16),3) if sum(x ) == 15 ][:10]
    for a,b,c in combs:
        f.write("{} {} {}\n".format(a,b,c))

rawDescription: "Slice" a number into three random numbers


code:
git = repo.git
git.clean('-xdf')

rawDescription: git-clean with GitPython

description: Git-clean with GitPython


rawDescription: How To Suppress Display of ObjectIDs when Inserting Documents into MongoDB Through IDLE


rawDescription: django list of unicode string to pure string

description: Django list of unicode string to pure string


code:
#first collect all files that start with a number and end with .png
my_files = [f for f in os.listdir(some_directory) if f[0].isdigit() and f.endswith(".png")]
#sort them based on the number
sorted_files = sorted(my_files,key=lambda x:int(x.split(".")[0])) # sort the file names by starting number
#rename them sequentially
for i,fn in enumerate(sorted_files,1): #thanks wim
    os.rename(sorted_files[i],"{0:04d}.png".format(i))

rawDescription: Renaming sequential image files with gaps


code:
import uuid
def foo():
    uuid = uuid.uuid4()

foo()
def bar():
    uuidValue = uuid.uuid4()

bar()

someGlobal = 10
def baz():
    someGlobal = someGlobal + 1

baz()
def quux():
    someLocal = someGlobal + 1

quux()

rawDescription: local variable 'uuid' referenced before assignment

description: Local variable 'uuid' referenced before assignment


code:
buffer = io.BytesIO()
df.to_msgpack(buffer, append=False, compress='zlib')

rawDescription: How to serialise Pandas to MessagePack format as a python buffer / memoryview?

description: Serialise Pandas to MessagePack format as a python buffer / memoryview


code: chunk_split = lambda s: '\r\n'.join(s[i:min(i+76, len(s))] for i in xrange(0, len(s), 76))

rawDescription: chunk_split in python

description: Chunk_split in python


code:
email_one=Mock()
email_two=Mock()

func_call_count = 0
def my_func_mock():
    global func_call_count
    func_call_count += 1

    if func_call_count == 1:
        do_invocation_1()

    if func_call_count == 2:
        do_invocation_2()

def do_invocation_1():
    return [email_one, email_two]

def do_invocation_2():
    return [email_one, email_two]

@mock.patch('app.foo.class_to_mock')
@mock.patch('app.foo.func', new=my_func_mock)
def test_render_and_send_email(self, func_mock, mock_to_class):
    render_method = mock.Mock()
    render_method.return_value = mock.Mock()

    class_method = mock.Mock()
    class_method.return_value = mock.Mock()

    func_mock.return_value = mock.MagicMock(render=render_method)
    mock_to_class.return_value = mock.Magic(method_for_class=class_method)
    function_to_test('context goes heres')
    self.assertEqual(func_call_count, 2) # Use the func_call_count instead
    self.assertEqual(render_method.call_count, 2)
    mock_to_class.assert_called_once_With(email_one, email_two) # Now you can assert it is called once with email_one & two
    self.assertEqual(method_class.call_count,1)

rawDescription: Mocking a function that is invoked twice with different arguements


code:
mypath = customerbulk.objects.get(pk=1).fileup.path
o = open(mypath,'rU')
mydata = csv.reader(o)

rawDescription: Open the file in universal-newline mode using the CSV Django module


code:
obj = AES.new('blablablablablab', AES.MODE_CBC, 'a' * 16)
obj.encrypt('z' * 16)
obj.encrypt('z' * 16)
obj.encrypt('z' * 16)

rawDescription: Encrypting large files with Pycrypto by streaming the file rather than one big string


code:
import os
dirname = os.path.dirname
PROJECT_PATH = dirname(dirname(dirname(os.path.abspath(__file__))))
TEMPLATE_DIRS = (
  os.path.join(PROJECT_PATH, 'templates'),
)

rawDescription: Django settings module and relative paths


code:
def straightCheck(playerHand):
    playerHand.sort()
    tally = 1
    for i in range(len(playerHand)-1):
        if playerHand[i] != playerHand [i+1] - 1:
            tally = 0
        tally += 1
        if tally >= 5:
            return True
    return False

rawDescription: How to identify if only a certain amount of numbers in an array are consecutive

description: Identify if only a certain amount of numbers in an array are consecutive


code:
import pygame, sys
from pygame.locals import *

pygame.init()

BLACK = (0, 0, 0)

WIDTH = 1280
HEIGHT = 1024
windowSurface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)

while True:
    windowSurface.fill(BLACK)
    pygame.display.flip()

rawDescription: Black background gui for raspberry pi

description: Black background gui for raspberry pi


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

# given 2 arrays arr1, arr2
arr1 = np.linspace(0, 1, 100).reshape(10,10)
arr2 = np.linspace(1, 0, 100).reshape(10,10)

# rejoin arr1, arr2 into a single array of shape (2, 10, 10)
arr = np.r_['0,3', arr1, arr2]

# define the grid coordinates where you want to interpolate
X, Y = np.meshgrid(np.arange(10), np.arange(10))
# 0.5 corresponds to half way between arr1 and arr2
coordinates = np.ones((10,10))*0.5, X, Y

# given arr interpolate at coordinates
newarr = ndimage.map_coordinates(arr, coordinates, order=2).T
fig, ax = plt.subplots(ncols=3)
cmap = plt.get_cmap('Greys')

vmin = np.min([arr1.min(), newarr.min(), arr2.min()])
vmax = np.max([arr1.max(), newarr.max(), arr2.max()])
ax[0].imshow(arr1, interpolation='nearest', cmap=cmap, vmin=vmin, vmax=vmax)
ax[1].imshow(newarr, interpolation='nearest', cmap=cmap, vmin=vmin, vmax=vmax)
ax[2].imshow(arr2, interpolation='nearest', cmap=cmap, vmin=vmin, vmax=vmax)
ax[0].set_xlabel('arr1')
ax[1].set_xlabel('interpolated')
ax[2].set_xlabel('arr2')
plt.show()

rawDescription: Interpolation between two matrices

description: Interpolation between two matrices


code:
class FloatProperty(Property):
    def get_default(self):
        return 0.0

    def to_neo(self, value):
        return float(value)

rawDescription: how to store a float value on a neo4django model

description: Store a float value on a neo4django model


code:
PATTERNS = {'pattern1': re.compile('foo.*baz'),
            'snake': re.compile('python'),
            'knight': re.compile('[Aa]rthur|[Bb]edevere|[Ll]auncelot')}

rawDescription: Python regular expression style

description: Python regular expression style


code: map(int, ','.join(l).split(','))

rawDescription: Extract integer from a list

description: Extract integer from a list


code:
import pandas as pd

pd.options.display.max_rows = 1000

rawDescription: Python & Pandas: display all rows without omitting


code:
def worker(row):
    n = np.array(row['weights'])
    i = (row.notnull()) & (row.index != 'weights')
    row[i] = n[row[i].astype('int').values - 1]
    return row
df.apply(worker, axis=1)

rawDescription: Pandas dataframe : assigning values according to ranks at row-level


code:
from gevent.event import Event
stopper = Event()

server = SocketIOServer(('localhost', 2345), app, resource='socket.io')
server.start()
gevent.spawn(send_queued_messages_loop)

try:
    stopper.wait()
except KeyboardInterrupt:
    print

rawDescription: How to stop a Flask server running gevent-socketio

description: Stop a Flask server running gevent-socketio


code:
from sympy import symbols, Piecewise, ccode
x, y, z = symbols('x y z')
e1 = x + 2
e2 = y - 5
rel = e1 < e2
pw = Piecewise((0, rel), (1, True))
print(ccode(pw, assign_to=z))

rawDescription: Generate C code for sympy expression "e1 op e2" where op is an arithmetic comparison operator


code:
from icu import UnicodeString, Locale
tr = Locale("TR")
s = UnicodeString("i")
print(unicode(s.toUpper(tr)))
s = UnicodeString("I")
print(unicode(s.toLower(tr)))

rawDescription: Python and Turkish capitalization

description: Python and Turkish capitalization


code:
ascending = sorted(GNR, key=lambda x: len(GNR[x]))
# ascending is ['billy', 'cilla', 'dan', 'anna']

for key in ascending:
    li = GNR[key]
    # print them etc.

rawDescription: Dictionary that has lists in keys, how to print so that the KEY with the least values in the list gets printed first?


code:
class Page:
    cm = None

    def __init__(self, title, content):
        self.title = title
        self.content = content

class ContentManager:
    def __init__(self, root_url):
        class PerContentManagerPage(Page):
            cm = self

        self.Page = PerContentManagerPage

page0 = Page(title='Test Page', content='hello world!')

cm = ContentManager(root_url='//localhost')
page = cm.Page(title='Test Page', content='hello world!')

cm2 = ContentManager(root_url='//localhost')
page2 = cm2.Page(title='Test Page 2', content='hello world!')

assert page0.cm is None
assert page.cm == cm
assert page2.cm == cm2

rawDescription: Contextually injecting static class properties in Python


code:
def find_root(G,node):
    if G.predecessors(node):  #True if there is a predecessor, False otherwise
        root = find_root(G,G.predecessors(node)[0])
    else:
        root = node
    return root

rawDescription: NetworkX find root_node for a particular node in a directed graph


code:
axs = df_month.plot(secondary_y=['C'], mark_right=False)

for ax in axs:
    ax.right_ax.set_ylim((0,50)) # Set the y limits to 0 to 50

rawDescription: Secondary_y range in a Pandas groupby function


code:
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

UserAdmin.list_display = ('email', 'first_name', 'last_name', 'is_active', 'date_joined', 'is_staff')

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

rawDescription: How to customize the auth.User Admin page in Django CRUD?

description: Customize the auth.User Admin page in Django CRUD


code:
B = B.set_index('Date')
B = B.stack()
res = merge(A,B,on='Date')

rawDescription: Use result from one dataframe to find data in another dataframe in pandas


code:
from nltk.corpus import stopwords
sw = set(stopwords.words('english'))
sentence = "a long sentence that contains a for instance"
[w for w in sentence.split() if w not in sw]

rawDescription: Extracting only meaningful text from webpages


code:
class Image:

    def __init__(self, image):
        self.image = image
        self.init_others()

    @classmethod
    def from_data(cls, data, header):
        return cls(lib.from_data(data, header))

    @classmethod
    def from_filename(cls, filename):
        return cls(lib.load(filename))

    def init_others(self):
        # initialise some other variables
        self.something = numpy.matrix(4, 4)

rawDescription: calling private methods for class method: python

description: Calling private methods for class method: python


code:
class Store:

    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.items = {}

    # rest of your code here. . .

    def additem(self, item, price):
        self.items[str(item)] = float(price)

    def delitem(self, item):
        del self.items[str(item)]

    def displayinventory(self):
        return self.items

rawDescription: global dictionary within a class python

description: Global dictionary within a class python


code:
import re

# Replace multiple consecutive spaces with a single space
# Example: "One Two  Three    Four!" -> "One Two Three Four!"
sentence = re.sub(' +', ' ', sentence)

# Surround each instance ; : ( ) ‘ and " with spaces
# Example: '"Hello;(w)o:r‘ld"' -> " Hello ;  ( w ) o : r ‘ ld "
sentence = re.sub('([;:()‘"])', ' \\1 ', sentence)

# Insert a space before each instance of , 's 're and 'll
# Example: "you'll they're, we're" -> "you 'll they 're , we 're"
sentence = re.sub("(,|'s|'re|'ll)", ' \\1', sentence)

return sentence

rawDescription: How to do multiple string replacements in a cleaner manner? - Python

description: Do multiple string replacements in a cleaner manner? - Python


code:
import timeit
import sys
del timeit  # remove local reference to the timeit module
del sys.modules['timeit']  # remove module

rawDescription: Unloading an Unused Module in Python (A Very Specific Case)


code:
class LenDict(dict):
  @property
  def len(self):
    return len(self)
d=LenDict()
d.len
d[1]=2
d.len

rawDescription: Variable who's reference is always to len(dict)


code:
import re

while True:
    user = input('Enter a number: ')
    match = re.search(r'\d+',user)
    if match:
        value = int(match.group(0))
        break
    else:
        print("I didn't see a number in that response.")

print(value)

rawDescription: Python3x Integer and String Input

description: Python3x Integer and String Input


code:
csvr = csv.reader(file)
csvr = list(csvr)
csvr[2]     # The 3rd row
csvr[2][3]  # The 4th column on the 3rd row.
csvr[-4][-3]# The 3rd column from the right on the 4th row from the end

rawDescription: How to find specific row in Python CSV module

description: Find specific row in Python CSV module


code:
from datetime import date

min_age = 24
max_date = date.today()
try:
    max_date = max_date.replace(year=max_date.year - min_age)
except ValueError: # 29th of february and not a leap year
    assert max_date.month == 2 and max_date.day == 29
    max_date = max_date.replace(year=max_date.year - min_age, month=2, day=28)
people = People.objects.filter(birth_date__lte=max_date)

rawDescription: Filter people from Django model using birth date


code:
import ast
ast.literal_eval(a[1])

rawDescription: How to Convert Tuple to Dictionary?

description: Convert Tuple to Dictionary


code:
import threading

def takeInput():
    """This function will be executed via thread"""
    value = raw_input("what you want:")
    return

#initialize how you want
value = 0
t = threading.Thread(target=takeInput)
t.start()
time.sleep(5)

rawDescription: Python: Accept input while waiting

description: Python: Accept input while waiting


code:
import requests
url = 'http://edmonton.en.craigslist.ca/kid/'
headers = {'User-Agent': 'Mozilla/5.0'}
request = requests.get(url, headers=headers)
request.ok
request.text  # content in string, similar to .read() in question

rawDescription: Python urllib2 - cannot read a page

description: Python urllib2 - cannot read a page


code:
import os
import multiprocessing

def worker(num):
    with open(num, 'w') as f:
        f.write("This is my first text file written in python\n")

if __name__ == '__main__':
    number_of_workers = 4
    pool = multiprocessing.Pool(processes=number_of_workers)
    pool.map(worker, [os.path.join(inDir, i) for i in inTxtList])
    pool.close()
    pool.join()

rawDescription: Parallel independent processes

description: Parallel independent processes


code:
with open(path3 + 'extend.csv', 'w') as fw:
    fw.write(",".join(d.values()))
    fw.write('\n')
fw.close()

rawDescription: create a new csv file using python

description: Create a new csv file using python


rawDescription: Fill the elements close to the region of the image


code:
import Tkinter
t = Tkinter.Tk()
t.configure(cursor=('@/usr/include/X11/bitmaps/star', '/usr/include/X11/bitmaps/starMask', 'black', 'white'))
t.mainloop()

rawDescription: Is it possible to make a custom mouse cursor with Python Tkinter? (Using matplotlib with the TkAgg backend)


code:
from django.db.models import Q

def related(self):
    'returns all related Fences'
    return FenceShip.objects.filter(fence_group=self)

def non_related(self):
    'returns all non-related Fences'
    return FenceShip.objects.filter(~Q(fence_group=self))

def fences(self):
    'returns a list of pairs: (fence, related) where related is True/False'
    return [(fence, bool(fence.fence_group==self)) for fence in FenceShip.objects.all()]

rawDescription: Django Related and NoRelated on a ManyToMany


code:
import networkx as nx
g2 = nx.Graph()
g2.add_path([1,2,3,5,4,3,1,4,3,7,2])
g2.node[2]['weight']=7
g2.node
nx.adjacency_matrix(g2).todense()
g2.edge[1][2]['weight'] = 42
nx.adjacency_matrix(g2).todense()

rawDescription: NetworkX : When I add 'weight' to some node I can not generatee adjacecy_matrix()?


rawDescription: Parallelly started Processes in Python executing serially?


code:
class myHandler(webapp2.RequestHandler):
    def get(self):
        # somehow get account uiod
        type =  Account.check_user_role_by_uid(uid)
        if type == 'SkilledPerson':
            self.render('index_farm.html')
        elif type == 'FarmCompany':
            self.render('index_farmcompany.html')

rawDescription: Google Appengine + Jinja2: Output different templates depending on 'user role'


code:
import numpy as np
import operator

names = [str(x) for x in xrange(10000)]
values = [float(x) for x in xrange(10000)]
tuples = zip(names, values)
dic = dict(tuples)
npvalues = np.fromiter(values, np.float)

def fa():
    return names[npvalues.argmax()]

def fb():
    return max(tuples, key=operator.itemgetter(1))[0]

def fc():
    return max(dic, key=dic.get)

def fd():
    v = np.fromiter((x[1] for x in tuples), np.float)
    return tuples[v.argmax()][0]

rawDescription: Performance for finding the maximum value in a dictionary versus numpy array


code:
import  catName

n [3]: [v for k,v in catName.__dict__.items() if not k.startswith("__")]
Out[3]: ['toby', 'sally', 'bill']

rawDescription: Python - populate a list containing variables from another module


code:
class my_class:
    def GET(self,id=None):
        if id is None:
            return "..."
        else:
            return "other..."

rawDescription: RESTful GET and GET(all) URLs in web.py

description: RESTful GET and GET(all) URLs in web.py


code:
class A():
    lockZ = threading.RLock()
    lockY = threading.RLock()

    @staticmethod
    @synchroized(lockZ)
    def doZStuff():
        a = A()
        a.doStuff('Z')

    @staticmethod
    @synchroized(lockY)
    def doYStuff():
        a = A()
        a.doStuff('Y')

    def doStuff(self, type):
        if type == 'Z':
            otherstuff()
        elif type == 'B':
            evenmorestuff()

rawDescription: thread Locking/unlocking in constructor/destructor in python

description: Thread Locking/unlocking in constructor/destructor in python


code:
return next(encod for value in response.values()
                      for encod in encodings
                          if encod.lower() in value.lower())

rawDescription: pythonic way of handling nested for loop

description: Pythonic way of handling nested for loop


code:
from django.core.cache import get_cache

CACHE_KEY_MOST_VIEWED_CATEGORIES = 'most_viewed_categories'
cache = get_cache('default')

def _get_most_viewed_categories():
    raise NotImplemented("Haven't figured out how to collect the value and cache it")

def most_viewed_categories(request):
    '''Provides the most viewed categories for every template context.'''

    return {
        'most_viewed_categories': cache.get(CACHE_KEY_MOST_VIEWED_CATEGORIES,
                                            _get_most_viewed_categories)
    }

rawDescription: Global variable/Variable caching in Django


code:
uncertainty = plt.cm.jet(data_property.data)
uncertainty[..., 3] = data_uncertainty.data

rawDescription: Show "Heat Map" image with alpha values - Matplotlib / Python


code:
class MyRequestHandler(web.RequestHandler):
    @web.asynchronous
    def get(self):
       http = httpclient.AsyncHTTPClient()
       http.fetch("http://friendfeed.com/", self._on_download)

    def _on_download(self, response):
       self.write("Downloaded!")
       self.finish()

rawDescription: What is the benefit of adding a @tornado.web.asynchronous decorator?


code: self.tree = wx.TreeCtrl(self, style=wx.TR_HAS_BUTTONS + wx.TR_HIDE_ROOT)

rawDescription: wxPython TreeCtrl without showing root while still showing arrows

description: WxPython TreeCtrl without showing root while still showing arrows


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

result = graph.cypher.execute(myquery)

# Pandas DataFrame
df = pd.DataFrame(result.records, columns=result.columns)

# numpy matrix
matrix = np.matrix(result.records)

rawDescription: Py2Neo - how to get around iterating the record object returned from cypher queries to access the query data


code:
import itertools

def combine(*args):
    lists = [arg if isinstance(arg, list) else [arg] for arg in args]
    for a, b, c in itertools.product(*lists):
        Function(a, b, c)

Var1=["a","b"]
Var2=["c","d"]
Var3="e"

combine(Var1, Var2, Var3)

rawDescription: How to use all the dynamic input recursively with a dynamic function in python?

description: Use all the dynamic input recursively with a dynamic function in python


code:
p = soup.findAll('p')
while len(p) > 3:
    last_p = p.pop()
    last_p.extract()

rawDescription: Delete rest of HTML file after some text


code:
from elasticsearch import Elasticsearch
es = Elasticsearch()

text = 'ra'
suggDoc = {
           "entity-suggest" : {
                'text' : text,
                "completion" : {
                    "field" : "suggest"
                }
            }
        }

res = es.suggest(body=suggDoc, index="auto_sugg", params=None)
print(res)

rawDescription: How to use "suggest" in elasticsearch pyes?

description: Use "suggest" in elasticsearch pyes


code:
UNES_HARD_COAL_BR = UNES_HARD_COAL_BR.iloc[:, [0,1,2,17]]
UNES_HARD_COAL_BR.head()

rawDescription: How to select specific columns from a DataFrame pandas object?

description: Select specific columns from a DataFrame pandas object


code:
import csv
your_dict = {}
with open('eggs.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in spamreader:
        your_dict[row[0]] = row[1:]

rawDescription: Extracting the data from a csv file amd making dictionary of it using python


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

np.random.seed(6)
kinds = ('nearest', 'zero', 'linear', 'slinear', 'quadratic', 'cubic')

N = 10
x = np.linspace(0, 1, N)
y = np.random.randint(10, size=(N,))

new_x = np.linspace(0, 1, 28)
fig, axs = plt.subplots(nrows=len(kinds)+1, sharex=True)
axs[0].plot(x, y, 'bo-')
axs[0].set_title('raw')
for ax, kind in zip(axs[1:], kinds):
    new_y = interpolate.interp1d(x, y, kind=kind)(new_x)
    ax.plot(new_x, new_y, 'ro-')
    ax.set_title(kind)

plt.show()

rawDescription: What do the different values of the kind argument mean in scipy.interpolate.interp1d?


code:
import collections

result = collections.defaultdict(list)

for d in dict_list:
    result[d['event']].append(d)

result_list = result.values()

rawDescription: Splitting a list of dictionaries into several lists of dictionaries


code:
from collections import defaultdict
from operator import itemgetter

entries = [(1,3),(1,4),(2,5),(2,6)]

counters = defaultdict(lambda: [0, 0])
for a, b in entries:
    # if a was not in dictionary yet, it will get
    # initialized to a list [0, 0]
    counts = counters[a]
    counts[0] += 1  # count the a's
    counts[1] -= b  # count the 0 - sum(b's)

# items will be `[(1, [2, -7]), (2, [2, -11])]`;
# we take the [1] of them for key, thus we select maximum of
# [2, -7] and [2, -11]; then we take the [0] of the item
# tuple to get the key, i.e. a.
max_a = max(counters.items(), key=itemgetter(1))[0]
print(max_a)

rawDescription: Get "a" value with highest frequency in (a,b) pairs, using sum(b) with smallest value as tie breaker


code:
from werkzeug.security import generate_password_hash
generate_password_hash("test")
len(generate_password_hash("test"))

rawDescription: hashed password never desalts

description: Hashed password never desalts


code:
# By Armin Moser

from mpl_toolkits.mplot3d import Axes3D
import matplotlib
import numpy as np
from matplotlib import cm
from matplotlib import pyplot as plt
step = 0.04
maxval = 1.0
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# create supporting points in polar coordinates
r = np.linspace(0,1.25,50)
p = np.linspace(0,2*np.pi,50)
R,P = np.meshgrid(r,p)
# transform them to cartesian system
X,Y = R*np.cos(P),R*np.sin(P)

#Z = ((R**2 - 1)**2)
Z = (X**2 + 0.2*Y**2 -1)**2   # <------- edit

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet)
#ax.set_zlim3d(0, 1)
ax.set_xlabel(r'$\phi_\mathrm{real}$')
ax.set_ylabel(r'$\phi_\mathrm{im}$')
ax.set_zlabel(r'$V(\phi)$')
plt.show()

rawDescription: Plotting a 2D Array with Matplotlib

description: Plotting a 2D Array with Matplotlib


code:
match = re.match(r'^([\w ]+)(?:\s-((?:\s\w+)+))?$', input)
if match:
    text = match.group(1)
    if match.group(2):
        options = [m.group(0) for m in re.finditer(r'\w+', match.group(2))]
    else:
        options = []

rawDescription: How do the regular expression capture infinite groups?


code:
import matplotlib.pyplot as plt
from StringIO import StringIO

s = StringIO()

plt.imsave(s, img)

rawDescription: scikit-image save image to a bytestring

description: Scikit-image save image to a bytestring


code: management.call_command('create_db_matviews', 'test', 'test', 'test', verbosity=0)

rawDescription: Running Django management command from tests?


code:
from django.utils.safestring import mark_safe
from django.db import models
class Test(models.Model):
    area = models.FloatField(choices=((0, mark_safe('0 mm²')), (0.5, mark_safe('0.5 mm²'))), default=0)

rawDescription: django: rendering a template field containing html in selector choices

description: Django: rendering a template field containing html in selector choices


code: result = commands.getoutput("/usr/lib/cgi-bin/test.sh %s" % name)

rawDescription: How to use cgi form input as variable in call to system command in Python script?

description: Use cgi form input as variable in call to system command in Python script


code:
from lxml import html
t = html.fromstring(text)
tds = t.xpath("table/tbody/tr[2]/td")
for td in tds:
    if tds.text.startswith("0."):
        td.getparent().remove(td)
text = html.tostring(t)

rawDescription: python string replace digits

description: Python string replace digits


code:
import clr
clr.AddReference("System.Drawing")

from System.Drawing import Image
from System.Drawing.Imaging import FrameDimension
from System.IO import Path

# sourceFilePath - The full path to the tif image on disk (e.g path = r"C:\files\multipage.tif")
# outputDir - The directory to store the individual files.  Each output file is suffixed with its page number.
def splitImage(sourceFilePath, outputDir):
     img = Image.FromFile(sourceFilePath)

     for i in range(0, img.GetFrameCount(FrameDimension.Page)):

         name = Path.GetFileNameWithoutExtension(sourceFilePath)
         ext = Path.GetExtension(sourceFilePath)
         outputFilePath = Path.Combine(outputDir, name + "_" + str(i+1) + ext)

         frameDimensionId = img.FrameDimensionsList[0]
         frameDimension = FrameDimension(frameDimensionId)

         img.SelectActiveFrame(frameDimension, i)
         img.Save(outputFilePath, ImageFormat.Tiff)

rawDescription: Splitting a multipage TIFF image - With .NET and IronPython


code: a_send = dict((k[0], v) for k,v in a.items())

rawDescription: Efficiently change a key of a Python dict


code:
log = open('/dev/shm/access_log', 'a')
with daemon.DaemonContext(stderr=log):
  run(host='0.0.0.0', port=8080)

rawDescription: How do I make python-bottle log send its stdout to a file?

description: Make python-bottle log send its stdout to a file


code:
a = np.array([  1.,  -1.,   np.nan,  0.,  np.nan], dtype=np.float32)
sa = np.sort(a)[::-1]
np.roll(sa,-np.count_nonzero(np.isnan(a)))

array([  1.,   0.,  -1.,  nan,  nan], dtype=float32)

rawDescription: Reverse sort of Numpy array with NaN values


code:
import re

def checkPassword(password):
    """
    Validate the password
    """
    if len(password) < 8:
        # Password to short
        print("Your password must be 8 characters long.")
        return False
    elif not re.findall(r'\d+', password):
        # Missing a number
        print("You need a number in your password.")
        return False
    elif not re.findall(r'[A-Z]+', password):
        # Missing at least one capital letter
        print("You need a capital letter in your password.")
        return False
    else:
        # All good
        print("All good")
        return True

# Promt user to enter valid password
passwordValid = False
while not passwordValid:
    password = input("Type in your password: ")
    passwordValid = checkPassword(password)

rawDescription: Making a Secure Password Program in python 3.4 using while loops


code:
def calc(N, m):
    x = 1.0
    y = 2.0
    container = np.zeros((N, 2))
    nm = N*m
    gamma_vals = np.random.gamma(3, 1, size=(nm,))
    norm_vals = np.random.normal(0, 1, size=(nm,))
    for i in xrange(N):
        for j in xrange(m):
            ij = i*j
            x = gamma_vals[ij] / (y*y+4)
            y = norm_vals[ij]/np.sqrt(x+1) + 1/(x+1)
        container[i, 0] = x
        container[i, 1] = y
    return container

rawDescription: Speed up double loop in Python

description: Speed up double loop in Python


code:
string = "a quake-prone area- (aujourd'hui-"
RE_WORDS = re.compile(r'[a-z]+(?:[-\'][a-z]+)?')
RE_WORDS.findall(string)

rawDescription: How to change a quantifier in a Regex based on a condition?

description: Change a quantifier in a Regex based on a condition


code: Xtrain_set = np.concatenate([X_train[:i*subset_size], X_train[(i+1)*subset_size:]])

rawDescription: ValueError: operands could not be broadcast together with different shapes in numpy?


code:
from sklearn import linear_model
X = [[1, 2, 3, 4, 5, 6]]
Y = [[1, 2, 3]]
lr = linear_model.LinearRegression()
model = lr.fit(X, Y)
model.predict([[1,2,3,4,5,6]])

rawDescription: Multivariate Linear Regression in Python - analog of mvregress in MATLAB?


code:
lineedit = QtGui.QLineEdit()
lineedit.setStyleSheet("""QLineEdit {
     background-image: url(:/images/magnifier.png);
     background-repeat: no-repeat;
     background-position: right;
     background-clip: padding;
     padding-right: 16px;
}""")

rawDescription: Custom/Owner draw control in PyQt?

description: Custom/Owner draw control in PyQt


code:
def sanitize(mystring):
  for word in mystring.split(" "):
    if valid_url(word):
      mystring = mystring.replace(word, get_title(word))
  return mystring

rawDescription: Python: replace urls with title names from a string


code:
import multiprocessing as mp
import time

def is_odd(n):
    return bool(n%2)

def hailstone(n):
    """
    Compute the Hailstone sequence, as described in:
    http://en.wikipedia.org/wiki/Collatz_conjecture
    """
    steps = 0
    while n > 1:
        steps += 1
        if is_odd(n):
            n = 3*n + 1
        else:
            n = n//2
    return steps

def slow(limit):
    steps = sum(hailstone(n) for n in range(limit))
    #print("n: {}  steps: {}".format(n, steps))
    return (limit, steps)

LIMIT = 2000

start = time.time()
results0 = [slow(n) for n in range(LIMIT)]
stop = time.time()
elapsed0 = stop - start

print("Single-threaded time: {:.2f} seconds".format(elapsed0))

# note we are including time to set up the Pool() in the elapsed time
start = time.time()
p = mp.Pool()
results1 = p.map(slow, range(LIMIT))
stop = time.time()
elapsed1 = stop - start

results1.sort()

print("Multiprocessing time: {:.2f} seconds".format(elapsed1))

assert results0 == results1

rawDescription: about multiprocessing process

description: About multiprocessing process


code:
import subprocess
foo = subprocess.Popen('test.exe',stdout=subprocess.PIPE,stderr=subprocess.PIPE)

rawDescription: Python 2.6: reading data from a Windows Console application. (os.system?)


code:
import datetime
import random
import matplotlib.pyplot as plt

data1 = (1163557.14, 1137578.47, 1139094.66)
times1_raw = ('23:04:17', '23:04:27', '23:04:37')
times1 = [datetime.datetime.strptime(s, '%H:%M:%S') for s in times1_raw]

data2 = (1011000.00, 1011000.00, 1011000.00)
times2_raw = ('23:04:21', '23:04:31', '23:04:41')
times2 = [datetime.datetime.strptime(s, '%H:%M:%S') for s in times2_raw]

fig = plt.figure(figsize=(8,6))

plt.plot(times1, data1, label='data1', lw=2, marker='o')
plt.plot(times2, data2, label='data2', lw=2, marker='s')
plt.xlabel('time in seconds')
plt.ylabel('speed in bps')
plt.grid()
plt.legend(loc='upper right')

plt.gcf().autofmt_xdate()

plt.show()

rawDescription: Plotting multiple Y values against multiple X values which are different timestamps in matplotlib in the same graph?


code:
db = ReplicaSetConnection("morton.local:27017", replicaSet='foo').test
from pymongo import ReadPreference
db.read_preference = ReadPreference.SECONDARY

rawDescription: pymongo replication secondary readreference not work

description: Pymongo replication secondary readreference not work


code:
def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

rawDescription: Bundling data files with PyInstaller (--onefile)


code:
if __name__ == '__main__':
    manager = Manager()
    flag = manager.list([True])
    for taskSize in taskSizes:
        flag[0] = True
        processes = [] # a list to store the process handles
        for i in range(1,TASK_LAUNCHERS):
            p = Process(target=backgroundTaskLauncher, args=(taskSize,flag))
            p.start()
            processes.append(p) # save process handle
        # Experiment goes here (I think it goes here (unindented(?)))
        flag[0] = False
        # after you are done with your experiment, join all child processes
        for p in processes:
            p.join()

rawDescription: Toggle a loop on and off in a multi-processed program in Python


code:
def execute(channel, command):
    command = 'echo $$; exec ' + command
    stdin, stdout, stderr = channel.exec_command(command)
    pid = int(stdout.readline())
    return pid, stdin, stdout, stderr

rawDescription: get PID from paramiko

description: Get PID from paramiko


rawDescription: Python pandas- Remove all elements of one dataframe that aren't included in another


code:
id_list = [film['id'] for film in film_hc]
objects = Film.objects.only('name').in_bulk(id_list)
for film in film_hc:
    film['name'] = objects[film['id']].name

rawDescription: Combine model data with list of objects

description: Combine model data with list of objects


code:
answer = input('Pick a card:\n')
guess = random.choice(card)
guesses = 1
while guess != answer:
    if guess != card:
        guess = random.choice(card)
        card.remove(guess)
    guesses += 1
print('\nWhoopy, I guessed right!\n')
print('It only took me %s guesses to guess %s.' % (guesses, answer))

rawDescription: Making the while loop del guess from card[list]


code:
bigbuf = "\1\0\0\0\2\0\0\0"
fromstring(bigbuf, dtype=np.int32)

rawDescription: Convert string to ndarray in python

description: Convert string to ndarray in python


code:
import time

for i in range(30):
    print("-",end='', flush=True)
    time.sleep(.5)

rawDescription: Python - Slowly type each character

description: Python - Slowly type each character


code:
import os

def doc_to_text_catdoc(filename):
    (fi, fo, fe) = os.popen3('catdoc -w "%s"' % filename)
    fi.close()
    retval = fo.read()
    erroroutput = fe.read()
    fo.close()
    fe.close()
    if not erroroutput:
        return retval
    else:
        raise OSError("Executing the command caused an error: %s" % erroroutput)

# similar doc_to_text_antiword()

rawDescription: Best way to extract text from a Word doc without using COM/automation?

description: Extract text from a Word doc without using COM/automation


rawDescription: python syntax for formatting integer

description: Python syntax for formatting integer


code:
profits = []

for NP in range(MP, MaxP+1, 10):

    CostofTicket = TP - (((NP - MP)/10)*.5)
    Gross = NP * CostofTicket
    Profit = (NP * CostofTicket) - FixedCost

    profits.append((Profit, TP, NP, MP))

    print (NP, end="          ")
    print ("$", format(CostofTicket, "3,.2f"), end="          ")
    print ("$", format(Gross, "3,.2f"), end="          ")
    print ("$", format(FixedCost, "3,.2f"), end="          ")
    print ("$", format(Profit, "3,.2f"))

# find max profits tuple and unpack its values
Profit, TP, NP, MP = max(profits)
# etc...

rawDescription: Values related to a max value in a for loop python


code:
def my_login_required(function):
    def wrapper(request, *args, **kw):
        user=request.user
        if not (user.id and request.session.get('code_success')):
            return HttpResponseRedirect('/splash/')
        else:
            return function(request, *args, **kw)
    return wrapper

rawDescription: Django: Tweaking @login_required decorator


code:
a = ['hello', 'banana', 'apple']
my_dict = {}
for x in range(len(a)):
    my_dict[x] = a[x]

my_dict
my_dict[1]

rawDescription: Python dynamically create variable names


code:
def SetX(value):
  self.x = value
  self.values[0] = value

rawDescription: Python class variable dependencies

description: Python class variable dependencies


code:
import threading

# Callable that stores the result of calling the given callable f.
class ResultCatcher:
    def __init__(self, f):
        self.f = f
        self.val = None

    def __call__(self, *args, **kwargs):
        self.val = self.f(*args, **kwargs)

def threaded(f):
    def decorator(*args,**kargs):
        # Encapsulate f so that the return value can be extracted.
        retVal = ResultCatcher(f)

        th = threading.Thread(target=retVal, args=args)
        th.start()
        th.join()

        # Extract and return the result of executing f.
        return retVal.val

    decorator.__name__ = f.__name__
    return decorator

@threaded
def add_item(a, b):
    return a + b

print(add_item(2, 2))

rawDescription: How to return a function value with decorator and thread

description: Return a function value with decorator and thread


code: print('.'.join(str(x) for x in deints))

rawDescription: convert list into string in python3

description: Convert list into string in python3


code:
cached_records = Record.objects.all()
list(cached_records) # by using list() we force Django load all data into memory

rawDescription: Load static Django database into memory

description: Load static Django database into memory


code:
s = 1
def func(x):
    global s
    s=2

rawDescription: Python import loops and top level program structure


code:
# 80 is default width of console in characters
print("Vovels: %s".center(80) % vcount)

rawDescription: How to center python print

description: Center python print


code:
with open('myfile.txt') as infp:
    files = [open('%d.txt' % i, 'w') for i in range(number_of_files)]
    for i, line in enumerate(infp):
        files[i % number_of_files].write(line)
    for f in files:
        f.close()

rawDescription: Python Split files into multiple smaller files


code:
from base64 import standard_b64encode
import http.client
from urllib.request import (HTTPBasicAuthHandler, Request, HTTPSHandler,
                            build_opener, HTTPPasswordMgrWithDefaultRealm)
import json
import os
from configparser import ConfigParser
http.client.HTTPConnection.debuglevel = 1

class HTTPBasicPriorAuthHandler(HTTPBasicAuthHandler):
    handler_order = 400

    def http_request(self, req):
        if not req.has_header('Authorization'):
            user, passwd = self.passwd.find_user_password(None,
                                                          req.get_host())
            credentials = '{0}:{1}'.format(user, passwd).encode()
            auth_str = standard_b64encode(credentials).decode()
            req.add_unredirected_header('Authorization',
                                        'Basic {}'.format(auth_str.strip()))
        return req

    https_request = http_request

cp = ConfigParser()
cp.read(os.path.expanduser('~/.githubrc'))

# That configuration file should look something like
# [github]
# user=mylogin
# password=myveryverysecretpassword

gh_user = cp.get('github', 'user')
gh_passw = cp.get('github', 'password')
repo = 'reponame'

pwd_manager = HTTPPasswordMgrWithDefaultRealm()
pwd_manager.add_password(None, 'https://api.github.com', gh_user, gh_passw)
auth_prior_handler = HTTPBasicPriorAuthHandler(pwd_manager)
verbose_handler = HTTPSHandler(debuglevel=2)

opener = build_opener(verbose_handler, auth_prior_handler)

# Be careful that there is no slash in the end of the URL
gh_url = "https://api.github.com/repos/{0}/{1}/issues".format(gh_user, repo)

create_data = {
    'title': 'Testing bug summary',
    'body': '''This is a testing bug. I am writing here this stuff,
            just to have some text for body.''',
    'labels': ['somelabel']
}

gh_req = Request(gh_url, json.dumps(create_data).encode('utf8'))

handler = opener.open(gh_req)

print(handler.getcode())
print(handler)

rawDescription: urllib2: correct way how to add a header to the *initial* request via AuthHandler?

description: Urllib2: correct way how to add a header to the *initial* request via AuthHandler


rawDescription: python map string split list

description: Python map string split list


code:
from ast import literal_eval

cns = literal_eval(raw_input("Please enter the data: "))

rawDescription: How to input a list of tuples

description: Input a list of tuples


code: line = sum([[y.strip('"') for y in x.split(", ")] for x in lineList], [])

rawDescription: more then one expression in list comprehension?

description: More then one expression in list comprehension


code:
def wmean_grouped2 (group, var_name_in, var_name_weight):
    d = group[var_name_in]
    w = group[var_name_weight]
    return (d * w).sum() / w.sum()

FUNCS = { "mean"  : np.mean ,
          "sum"   : np.sum ,
          "count" : np.count_nonzero }

def my_summary2 (
        data ,
        var_names_in ,
        var_names_out ,
        var_functions ,
        var_name_weight = None ,
        var_names_group = None ):

    result = pd.DataFrame()

    if var_names_group is None:
        grouped = data.groupby (lambda x: True)
    else:
        grouped = data.groupby (var_names_group)

    for var_name_in, var_name_out, var_function in \
            zip(var_names_in,var_names_out,var_functions):
        if var_function == "wmean":
            func = lambda x : wmean_grouped2 (x, var_name_in, var_name_weight)
            result[var_name_out] = pd.Series(grouped.apply(func))
        else:
            func = FUNCS[var_function]
            result[var_name_out] = grouped[var_name_in].apply(func)

    return result

rawDescription: Creating a partial SAS PROC SUMMARY replacement in Python/Pandas


code:
text=""
for p in lxml_tree.findall('para'):   #iterate over paragraphs
    text+= " "                        #add spaces
    for r in p.findall("Run"):        #iterate over each run in para
         for a in r.findall("break"):  #search for break tag in it and add space if found
            text+= " "
         for b in r.findall('.//highlight[@val="red"]/../..//text'): #search for red highlight in that run and return text
             text+=''.join(b.text) # append text to main string

rawDescription: Iterating Over Xml using findall , Lxml

description: Iterating Over Xml using findall , Lxml


code:
import itertools
s=[ [ 'a', 'b', 'c'], ['d'], ['e', 'f'] ]
list(itertools.product(*s))

rawDescription: All possible permutations of a set of lists in Python


code:
led_map = {
    # This maps each "bit" of your input string to the correct ID for GPIO.
    0 : 11,
    1 : 12,
    2 : 13,
    3 : 15
}

for i in xrange(len(y)):
    bit = y[i]
    GPIO.output(led_map[i], int(bit))

rawDescription: Trouble coding an LED selector in Python


code:
def obj_delete(self, bundle, **kwargs):
    # Get the object and raise NotFound if couldn't find
    try:
        bundle.obj = self.obj_get(bundle=bundle, **kwargs)
    except ObjectDoesNotExist:
        raise NotFound("A model instance matching the provided arguments could not be found.")

    #Here you should do any kind of validation before deleting

    # And then remove using the parameter you passed (for example user_id)
    bundle.obj.favourited_by.remove(User.objects.get(id=bundle.data['user_id']))  #pass in the user_id
    return

rawDescription: Django Tastypie: permissions for ManyToManyFields


code:
if hasattr(arg1, 'splitlines'):
    arg1 = arg1.splitlines()
if hasattr(arg2, 'splitlines'):
    arg2 = arg2.splitlines()
# now arg1 and arg2 are presumed to be lists.

rawDescription: How implement a python function with different parameter types


code:
import matlab.engine
eng = matlab.engine.start_matlab()
x, y, z = 3, 5, 8
r = eng.compute(x, y, z)

rawDescription: Run Matlab Code in Python

description: Run Matlab Code in Python


code:
data = [[.25 for numData in range(4)] for numSecs in range(86400)]
length_line=0

def write_line(f, sec, data):
    line="{:6d}".format(sec) + " " +" ".join(
            ["{:.2f}".format(dd) for dd in data])+"\n"
    f.write(line)
    return len(line)

with open('output', 'w') as of:
    for i,d in enumerate(data):
        length_line=write_line(of, i, d)

with open('output', 'rb+') as of:
    # modify the 2nd line:
    n = 2
    of.seek(n*length_line)
    write_line(of, n, [0.10,0.10,0.10,0.10])
    # modify the 10th line:
    n = 10
    of.seek(n*length_line)
    write_line(of, n, [0.10,0.10,0.10,0.10])

rawDescription: Editing a single line in a large text file


code:
def save(self, *args, **kwargs):
    if not self.id:
        super(Project, self).save(*args, **kwargs)
        year = datetime.datetime.now().year
        self.jobNumber = '{}{:04d}'.format(year, self.id)
    super(Project, self).save(*args, **kwargs)

rawDescription: How to combine the current year with the next Model Id and save it in a field

description: Combine the current year with the next Model Id and save it in a field


code: f_first_layer = theano.function([x], first_layer)

rawDescription: How to print values from inside a theano function?

description: Print values from inside a theano function


code:
import Tkinter as tk

root = tk.Tk()
mylist = ['a','b','c','d','e']

for i, x in enumerate(mylist):
    label = tk.Label(root, text="Label "+str(i))
    label.grid(row=i+1, column=1)
    label.bind("<Enter>", lambda e, x=x: e.widget.config(text=x))
    label.bind("<Leave>", lambda e, i=i: e.widget.config(text="Label "+str(i)))

root.mainloop()

rawDescription: Python tkinter label widget mouse over

description: Python tkinter label widget mouse over


code:
states = [gtk.STATE_NORMAL, gtk.STATE_ACTIVE, gtk.STATE_PRELIGHT,
          gtk.STATE_SELECTED, gtk.STATE_INSENSITIVE]

for state in states:
    button.modify_bg(state, gtk.gdk.color_parse("Green"))

rawDescription: Wildcard for PyGTK States

description: Wildcard for PyGTK States


code:
import os,sys
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
sys.path.append(PROJECT_ROOT, 'to', 'my', 'apps')
sys.path.append(os.path.join('path', 'to', 'satchmo', 'apps'))

rawDescription: Can you pass multiple paths to the Django runserver --pythonpath directive?

description: Pass multiple paths to the Django runserver --pythonpath directive


rawDescription: python csv headers

description: Python csv headers


code:
c = itertools.count()
next(c)
next(c)
next(c)

rawDescription: An autoincrementing callable?

description: An autoincrementing callable


code: output = subprocess.check_output("java MyJavaClass", cwd="../../bin/")

rawDescription: Run a Java main class using its relative path? (Python)


code:
import os
if os.fork() == 0: exit()

rawDescription: Display objects within a function, how to NOT terminate the program after close the display?


code: [x for ele in a for x in b if x in ele]

rawDescription: Python intersection with substrings

description: Python intersection with substrings


code:
def to_xml(parent, xpath, value):
    """
    parent: lxml.etree.Element
    xpath: string like 'x/y/z', anything more complex is likely to break
    value: anything, if is False - means delete node
    """
    # find the node to proceed further
    nodes = parent.xpath(xpath)
    if nodes:
        node = nodes[0]
    else:
        parts = xpath.split('/')
        p = parent
        for part in parts:
            nodes = p.xpath(part)
            if not nodes:
                n = etree.XML("<%s/>" % part)
                p.append(n)
                p = n
            else:
                p = nodes[0]
        node = p
    # do whatever is specified vy value
    if value is False:
        node.getparent().remove(node)
    else:
        node.text = str(value)

rawDescription: How to handle adding elements and their parents using xpath

description: Handle adding elements and their parents using xpath


code:
X = np.random.randn(1e3, 5)
X[np.abs(X)< .1]= 0 # some zeros
X = np.ma.masked_equal(X,0)
plt.boxplot(X) #masked values are not plotted

#other functionalities of masked arrays
X.compressed() # get normal array with masked values removed
X.mask # get a boolean array of the mask
X.mean() # it automatically discards masked values

rawDescription: removing data from a numpy.array

description: Removing data from a numpy.array


code:
from requests import Request, Session

s = Session()
req = Request('POST', url, data=data)
prepped = req.prepare()
del prepped.headers['content-length']
response = s.send(prepped)

rawDescription: Python requests remove the Content-Length header from POST


code:
import ROOT as r
r.gSystem.Load('libGenVector')

# ...

r.Math.VectorUtil.DeltaR(jets[i],partons[i])

rawDescription: Accessing Math functions from rootpy

description: Accessing Math functions from rootpy


code:
from nltk import word_tokenize
from nltk.stem import SnowballStemmer
stemmer = SnowballStemmer('spanish')

stemmer.stem('cuando')
stemmer.stem('apprenderla')

text = 'En su parte de arriba encontramos la ";zona de mandos";, donde se puede echar el detergente, aunque en nuestro caso lo al ser gel lo ponemos directamente junto con la ropa.'
stemmed_text = [stemmer.stem(i) for i in word_tokenize(text)]
stemmed_text

rawDescription: How to stem a list of words in spanish with nltk?

description: Stem a list of words in spanish with nltk


code:
def set_data_pipe_poll(self, data_pipe_poll):
    self.epoll = select.epoll()
    for p in data_pipe_poll:
        self.epoll.register(p, select.EPOLLIN)
    self.data_pipe_poll = data_pipe_poll

def recv_data(self):
    data = []
    events = self.epoll.poll(timeout = 0)
    for fileno, _ in events:
        p = filter(lambda x: x.fileno() == fileno, self.data_pipe_poll)[0]
        data.append(p.recv())
    return data

rawDescription: Handle out of range in select

description: Handle out of range in select


code:
from sympy.printing import ccode
from sympy.parsing.sympy_parser import parse_expr

s = "8*pi**3*sin(x3)*sin(pi*z)**2"
exp = parse_expr(s)

In [55]: ccode(exp)
Out[55]: '8*pow(M_PI, 3)*sin(x3)*pow(sin(M_PI*z), 2)'

rawDescription: Match mathematical expression with regex in python


code:
from pyramid.paster import bootstrap
env = bootstrap('/path/to/my/development.ini#another')

rawDescription: Share Pyramid configuration with a CLI script


rawDescription: Python how to remove the first set of a character in a string?


code: self.encode = Button(frame,command=lambda : rsa.encode (self.parameter) )

rawDescription: python transfer parameter to function

description: Python transfer parameter to function


code:
import requests, json

def getTaxonomy(title):
    r = requests.get('https://en.wikipedia.org/w/api.php?action=query&titles=' + title  + '&prop=revisions&rvprop=content&rvsection=0&format=json')

    #https://en.wikipedia.org/wiki/Special:ApiSandbox#action=query&prop=revisions&format=json&rvprop=content&rvsection=0&rvcontentformat=text%2Fx-wiki&titles=Foraminifera

    a = ''
    t = json.loads(r.text)
    for i in t['query']['pages']:
        a = t['query']['pages'][ i ]['revisions'][0]['*']

    taxobox = axobox = a[a.upper().index('{{TAXOBOX') + len('{{taxobox'):]
    taxobox = taxobox[taxobox.index("\n[["):]
    taxobox = taxobox[:taxobox.index("}}")]

    taxobox = taxobox.replace('[[','')
    taxobox = taxobox.replace(']]','')
    taxobox = taxobox.replace('<br>','')
    taxobox = taxobox.replace("''",'')
    taxobox = taxobox.replace(" ",' ')

    t = []
    for i in taxobox.split("\n"):
        if len(i) > 0:
            if '|' in i:                    # for href titles
                t.append( i.split('|')[1] ) # for href titles
            else:
                t.append( i )

    return "\n".join(t)

print(getTaxonomy('Foraminifera'))
print(getTaxonomy('Fusulinida'))

rawDescription: How to use Wikipedia API to get section of sidebar?

description: Use Wikipedia API to get section of sidebar


code:
import threading
import weakref
_mainlock = threading.RLock()
_job_locks = weakref.WeakValueDictionary()

def do_thing(job_id):
    with _mainlock:
        _job_locks.setdefault(job_id, threading.RLock())
    with _job_locks[job_id]:
        one_time_init(job_id)

rawDescription: Python: Thread safe dictionary with short lived keys, is this correct?


code:
['Obsol\xe8te', 'Code terrain', 'Toponyme', 'Type', 'Date creation', 'Derni\xe8re modification', 'Date validation', 'Position', 'Latitude', 'Longitude', 'Altitude', 'Consignes', 'Nombre de pistes', 'Nature premi\xe8re piste', 'Axe pr\xe9f\xe9rentiel premi\xe8re piste', 'Largeur premi\xe8re piste', 'Longueur premi\xe8re piste', 'Orientation premi\xe8re piste', 'Nature deuxi\xe8me piste', 'Axe pr\xe9f\xe9rentiel deuxi\xe8me piste', 'Largeur deuxi\xe8me piste', 'Longueur deuxi\xe8me piste', 'Orientation deuxi\xe8me piste', 'Radio', 'Carburant', 'Facilit\xe9s', 'Facilit\xe9s en clair', 'Email de contact', 'T\xe9l\xe9phone', 'Informations compl\xe9mentaires']
['', 'LF0121', 'La Trancli\xe8re', 'Base ULM Acc\xe8s priv\xe9', '8/03/2011', '6/09/2015', '12/09/2015', '46.095556, 5.286667', 'N 46 05 44', 'E 005 17 12', '820 ft', 'Tour de piste imp\xe9ratif du c\xf4t\xe9 autoroute. Ne pas voler au dessus du village de la Trancli\xe8re. Presque toujours d\xe9gag\xe9.', '1', 'herbe', "'36", '40', '640', "'18-36", 'herbe', '', '', '', "'Inconnue", '123.5', '', '', '', 'roger.emeriat@wanadoo.fr', '+33 4 74 46 84 34', "Village le plus proche : essence , hotels, etc = Pont D'ain \xe0 4, 5 km. En cas de brume : altiport de Corlier a environ 15 km\r\r\r\n\r\nInfos suppl\xe9mentaires : Laurent Pradel St\xe9 Vectral. repr\xe9sentant appareil savannah dans la r\xe9gion. Possibilit\xe9 essai de l'appareil en vol. T\xe9l : 04 74 35 60 00 email vectral@wanadoo.fr", '']
['', 'LF0125', 'Lavours', 'Base ULM Autorisation OBLIGATOIRE ', '8/03/2011', '24/06/2015', '25/06/2015', '45.795, 5.77361099999996', 'N 45 47 42', 'E 005 46 25', '768 ft', "TDP \xe0 l'est\r\r\nEviter les villages en rouge sur la photo, faire la vent-arri\xe8re sur le Rh\xf4ne.\r\r\nattention aux rouleaux par vent de travers", '1', 'herbe', "'01", '20', '450', "'01-19", 'herbe', '', '', '', "'Inconnue", '123.5', '', '', '', '', '+33 4 79 42 11 57', 'attention, base Hydro ULM club de Lavours \xe0 proximit\xe9 ', '']
['', 'LF0151', 'Corbonod Seyssel', 'A\xe9rodrome Priv\xe9 Avec Restrictions Autorisation OBLIGATOIRE ', '6/09/2011', '10/01/2015', '11/01/2015', '45.960629840733, 5.817818641662598', 'N 45 57 38', 'E 005 49 04', '1175 ft', 'Arriv\xe9e dans axe de la piste puis, du centre vent arri\xe8re main gauche \r\r\nSuivre le plan imperatif (photo jointe)', '1', 'dur', "'01", '15', '400', "'01-19", 'herbe', '', '', '', "'Inconnue", '123.5', '', '6', 'Restauration \xe0 proximit\xe9', 'dudunoyer@yahoo.fr', '+33 6 07 38 20 15', "PPR obligatoire pour tous,ULM et avion (arr\xeat\xe9 pr\xe9fectoral). Contacter le Pdt de l'AAC gestionnaire.\r\r\nRadio obligatoire pour tous + qualif montagne souhait\xe9e pour avion. Interdit ULM classe 1\r\r\nSurvol interdit \xe0 l'Est du Rh\xf4ne entre Seyssel et Culoz: Zone Biotope Natura 2000\r\r\n\xc9colage et  TDP interdit\r\r\nRadio 123.5 car piste l\xe9g\xe8rement convexe.\r\r\r\n\r\nCamping 1.5 KM\r\r\nResto + h\xf4tel : 2Km", '']

rawDescription: csv.reader fooled by line terminators inside data fields

description: Csv.reader fooled by line terminators inside data fields


code:
class Foo(object):
   pass
@property
def bar(self):
    print("bar is called")

Foo.bar = bar
f = Foo()
f.bar

rawDescription: Add @property method to a class

description: Add @property method to a class


code:
x_set = set((i['Name'], i['Type'], i['measure1'], i['measure2']) for i in x['Items'])
items = [{'Name': i[0], 'Type': i[1], 'measure1': i[2], 'measure2': i[3]} for i in sorted(x_set)]
new_x = {'Items': items}

rawDescription: Creating permuations of a list of dictionaries


code:
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.cm as cm
import numpy as np
import io
import Image

xmin, xmax, ymin, ymax = -3, 6, -2, 3
delta = 0.025
x = np.arange(xmin, xmax, delta)
y = np.arange(ymin, ymax, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)

def f(a, b):
    return 10.*(a*Z2 - b*Z1)

def fill_contour(cs):
    v = cs.collections[0].get_paths()[0].vertices
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.fill(v[:,0], v[:,1], 'k')
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    buf = io.BytesIO()
    fig.savefig(buf, format = 'png')
    buf.seek(0)
    im = Image.open(buf).convert('L')
    r = np.asarray(im).astype(np.int)
    r/=max(r.flat)
    return r

figc = plt.figure()
axc = figc.add_subplot(111)
c0 = .07
cs1 = axc.contour(X, Y, f(.6 ,.7), [c0], colors='r')
cs2 = axc.contour(X, Y, f(.8, 1.2), [c0], colors='g')

figd = plt.figure()
axd = figd.add_subplot(111)
d1 = fill_contour(cs1)
d2 = fill_contour(cs2)
d = abs(d1-d2)
im = axd.imshow(d, cmap=cm.gray)
figd.colorbar(im)
axd.set_title( "sum = %i" % np.sum(d.flat))

figc.show()
figd.show()

rawDescription: How to compare if two contour paths are visually similar - Python / Matplotlib

description: Compare if two contour paths are visually similar - Python / Matplotlib


code:
from django.db import models

class TimeStampedModel(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class content(TimeStampedModel):
    content_name = models.CharField(max_length = 100)
    content = models.ImageField(upload_to = 'photos', blank=False,null=True)
    approved = models.BooleanField(default = False)

rawDescription: Django Set Date against a Boolean Field

description: Django Set Date against a Boolean Field


code:
import glob

globtexts = ('*_some.text', '*_other.text')
files = [glob.glob(globtext) for globtext in globtexts]
# try saying that line out loud five times fast....
for file in files:
    try:
        os.remove(file)
    except Exception as e:
        print("There was a problem removing {}: {!r}".format(file, e))

rawDescription: Remove files by using placeholder

description: Remove files by using placeholder


code:
from numpy import linspace
from numpy.random import normal
from pylab import hexbin,show

n = 2**6

x = linspace(-1,1,n)
y = normal(0,1,n)

h = hexbin(x,y,gridsize=10,mincnt=0)

rawDescription: Zero-value colour in matplotlib hexbin

description: Zero-value colour in matplotlib hexbin


code:
my_entries_list.sort(key=lambda v:
                           datetime.datetime.combine(v.created_date, v.created_time))

rawDescription: sorting python list based on key

description: Sorting python list based on key


code:
class PopenThread(threading.Thread):

    def __init__(self, port):
        threading.Thread.__init__(self)
        self.port=port

    def run(self):
        Popen('ant -Dport='+str(self.port)+ ' -Dhost='+GetIP()+
                ' -DhubURL=http://192.168.1.113:4444'
                ' -Denvironment=*firefox launch-remote-control'
                ' $HOME/selenium-grid-1.0.8', shell=True)

if '__main__'==__name__:
    PopenThread(5555).start()
    PopenThread(5556).start()
    PopenThread(5557).start()

rawDescription: Launching multiple processes of shell

description: Launching multiple processes of shell


code:
import termios
attr = termios.tcgetattr(1)
attr[3] = attr[3] | termios.ECHO
termios.tcsetattr(1, termios.TCSANOW, attr)

rawDescription: Interactive Python Interpreter Run in Background


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

# Big (100,000 rows) test dataset
df = pd.DataFrame({'a': np.random.randint(1, 10, 100000),
                   'b': [np.random.choice(['A', 'B', 'C']) for i in range(100000)]})

def check_pandas(df):
    return ~ ((df['a'] == 1) & (df['b'] == 'A'))

def check_list(df):
    return [not i for i in ((df['b'] == 'A') & (df['a'] == 1))]

def check_numpy(df):
   return np.invert((df['a'] == 1) & (df['b'] == 'A'))

sizes = []
pandas_times = []
list_times = []
np_times = []

for df_size in range(1, 100001, 1000):
    sizes.append(df_size)

    current_df = df.iloc[:df_size, :]
    pandas_before = time.time()
    check_pandas(current_df)
    pandas_after = time.time()
    pandas_times.append(float(pandas_after - pandas_before))

    before = time.time()
    check_list(current_df)
    after = time.time()
    list_times.append(float(after - before))

    before = time.time()
    check_numpy(current_df)
    after = time.time()
    np_times.append(float(after - before))

# Plot results
fig, ax = plt.subplots()
ax.plot(sizes, pandas_times, 'ro', label='pandas')
ax.plot(sizes, list_times, 'bs', label='list')
ax.plot(sizes, np_times, 'g+', label='numpy')
ax.legend(loc='upper left')

rawDescription: Eliminate rows in a Pandas dataframe on complex condition


code:
from pyvirtualdisplay import Display
display = Display(visible=0, size=(800, 600))
display.start()
driver = webdriver.Chrome() # Or Firefox()

rawDescription: Schedule selenium to run on a remote server


code:
import numpy as np
probabilities = model.predict(image)
classes = np.argmax(probabilities, axis=-1)

rawDescription: Using Keras/ Neural Networks for categorical data


code:
memory_ptr =  pointer(memory)
ReadMem(0x20000000, 100, memory_ptr)

rawDescription: Working with pointers to struct

description: Working with pointers to struct


code:
def colorCycle():
    from itertools import cycle
    colors = ['black', 'red', 'green', 'blue']
    for color in cycle(colors):
        yield color
it = iter(colorCycle())
nextColor = it.next

def k7():
    c = nextColor()
    move.fillcolor(c)
    move.pencolor(c)

rawDescription: Turtle Python Module

description: Turtle Python Module


code:
# You can manipulate the beats in a song as a native python list
beats = audio_file.analysis.beats
beats.reverse()

rawDescription: Extracting beats out of MP3 music with Python


code:
import urllib2

opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))

req = urllib2.Request('http://www.google.com/doodles/finder/2014/All%20doodles',None,{"Host":"fakedomain.net"})

res = opener.open(req)

res.read()

rawDescription: Why does my host header not work?

description: Why does my host header not work


code:
import shlex
s = 'key1=4 key2="Hello World"'
shlex.split(s)

rawDescription: Splitting a string like shell would

description: Splitting a string like shell would


code:
from django.core import serializers
from django.http import HttpResponse

def get_info(request):
    data = serializers.serialize('json',
                                 Run.objects.all(),
                                 fields=('nvp_build', 'lports', 'lswitch_stt'))
    return HttpResponse(data, content_type='application/json')

rawDescription: Django QuerySet not serializable

description: Django QuerySet not serializable


code:
import os
from mock import MagicMock
os.listdir = MagicMock(return_value=['file1.txt', 'file2.txt', 'file3.txt'])
os.listdir('./test')

rawDescription: How to mock python build in methods

description: Mock python build in methods


rawDescription: Flask app hangs while processing the request


code:
import tkinter as tk

root = tk.Tk()
root.attributes('-alpha', 0.0) #For icon
#root.lower()
root.iconify()
window = tk.Toplevel(root)
window.geometry("100x100") #Whatever size
window.overrideredirect(1) #Remove border
#window.attributes('-topmost', 1)
#Whatever buttons, etc
close = tk.Button(window, text = "Close Window", command = lambda: root.destroy())
close.pack(fill = tk.BOTH, expand = 1)
window.mainloop()

rawDescription: How to remove just the window border?

description: Remove just the window border


code:
filename = "sciPHOTOf105w0.fits"
filename.rpartition('.')[0]
filename.rsplit('.', 1)[0]

rawDescription: Python simple string method

description: Python simple string method


code: eval(input('bricks are heavy'))

rawDescription: Python program fails when run outside IDE


code:
if 'test' in sys.argv:
    DATABASES['default'] = {'ENGINE': 'django.db.backends.sqlite3'}

rawDescription: How can i stop django to recreate test database

description: Stop django to recreate test database


code:
for row in nlist:
    row.insert(0, a)

rawDescription: Adding data to a nested list in Python

description: Adding data to a nested list in Python


code:
import sys
from PyQt4 import QtGui

class AnimatedSystemTrayIcon(QtGui.QSystemTrayIcon):

    def UpdateIcon(self):
        icon = QtGui.QIcon()
        icon.addPixmap(self.iconMovie.currentPixmap())
        self.setIcon(icon)

    def __init__(self, movie, parent=None):
        super(AnimatedSystemTrayIcon, self).__init__(parent)
        menu = QtGui.QMenu(parent)
        exitAction = menu.addAction("Exit")
        self.setContextMenu(menu)

        self.iconMovie = movie
        self.iconMovie.start()

        self.iconMovie.frameChanged.connect(self.UpdateIcon)

def main():
    app = QtGui.QApplication(sys.argv)

    w = QtGui.QWidget()
    trayIcon = AnimatedSystemTrayIcon(movie=QtGui.QMovie("cat.gif"), parent=w)

    w.resize(250, 150)
    w.move(300, 300)
    w.setWindowTitle('Anim Systray')
    w.show()

    trayIcon.show()

    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: How can I have an animated system tray icon in PyQt4?

description: Have an animated system tray icon in PyQt4


code: df.loc[:, df.columns <= datetime(2013, 1, 3)]

rawDescription: Pandas select columns with boolean date condition


code:
a.join(pd.DataFrame({6: [1,2]}))
a

rawDescription: Add DataFrame column with particular numeric index, not in-place


rawDescription: What is the distance between point [4, 7] and the nearest point on the circle centered at [2, 9] with radius 2? Provide at least 4 digits of accuracy


code:
def createUsbLib(params):
   if this_is_latest_ubuntu():
      return UsbUDisks2()
   else:
      return UsbLib()

rawDescription: Python class substituion with other class?