code:
from unittest.mock import Mock
m = Mock()
m.side_effect = ['foo', 'bar', 'baz']
m()
m()
m()

rawDescription: Python mock multiple return values

description: Python mock multiple return values


code:
u'Magic Cookie\xae Extra'
u'a Magic Cookie\xae Extra b'

rawDescription: Special character encoding is lost when string is passed to function


rawDescription: What is the fastest way to slice a scipy.sparse matrix?


code:
info_list = ["Client #1", "Joe", "800-213-4445", "123 Fake St.", "fake@fake.com"]
dict(zip(keys, info_list))

rawDescription: Python List to List of Dictionaries

description: Python List to List of Dictionaries


rawDescription: How to access child of child from parent in sqlalchemy?

description: Access child of child from parent in sqlalchemy


code:
def my_serialize(key_nums: list):
    key_nums = sorted(key_nums)
    base = max(key_nums)
    sum_ = 0
    for power, num in enumerate(key_nums):
        sum_ += base**power * num
    return sum_

rawDescription: Make a list of ints hashable in python

description: Make a list of ints hashable in python


code:
f1 = Fighters()
f1.foo_bar_func()

rawDescription: Python: multi level inheritance

description: Python: multi level inheritance


rawDescription: Arbitrary Amount of Tuple Unpacking With Common Date


code:
sum=0.0
for i in range(1,6):
    x,y=eval(input("Please enter length and width of room %i:" % i ))
    sf=(x*y)
    sum=sum+sf
print("The total square footage is %i" % sum )

rawDescription: Python-Need to turn this into a loop so it look like my picture?


code:
ABCDEFG
TESTVALUE
None

rawDescription: python regular expression exclude from match string

description: Python regular expression exclude from match string


code:
request.resolver_match.url_name  # 'tape-details'
request.resolver_match.view_name  # 'namespace:tape-details'

rawDescription: Test if string matches django url with params


rawDescription: Convert date to string with limited precision


code:
list_of_values = [0x55, 0x33, 0x22]
bytes_of_values = bytes(list_of_values)
bytes_of_values == b'\x55\x33\x22'

rawDescription: Python3 How to make a bytes object from a list of integers


code:
from xvfbwrapper import Xvfb

vdisplay = Xvfb()
vdisplay.start()

# launch stuff inside virtual display here

vdisplay.stop()

rawDescription: searching web-client for python that can handle frames

description: Searching web-client for python that can handle frames


code:
sql = "SELECT ... WHERE User=?1 AND (?2 IS NULL OR ColA=?2) ..."
cursor.execute(sql, [user, a_or_null])

rawDescription: Optional parameters in a SQLite SELECT statement


code:
def algorithm(input_):
    # Step 1
    instructions = []
    for s in input_.split():
        try:
            instructions.append([int(s)])
        except ValueError:
            instructions.append(list(values(s)))
    # Step 2
    for prod in itertools.product(*instructions):
        yield prod

def values(s):
    RULES = {'*': 4, '^': 2}
    n = int(s[:-1])
    for x in range(RULES[s[-1]]):
        yield n + x

rawDescription: how to implement this algorithm in python?

description: Implement this algorithm in python


code: result

rawDescription: Combining multiple CSV file into a single one


code:
# tital on top center of subplot
p.fig.suptitle('this is the figure title', verticalalignment='top', fontsize=20)

# tital above plot
p.fig.text(0.33, 1.02,'Above the plot', fontsize=20)

# left and right of plot
p.fig.text(0, 1,'Left the plot', fontsize=20, rotation=90)
p.fig.text(1.02, 1,'Right the plot', fontsize=20, rotation=270)

# an example of a multi-line footnote
p.fig.text(0.1, -0.08,
     'Some multiline\n'
     'footnote...',
      fontsize=10)

rawDescription: How to annotate seaborn pairplots?

description: Annotate seaborn pairplots


rawDescription: Pyqt QMdiSubWindow resize with variable number of widgets


code:
a_value = 1
d = {'a': a_value, 'b': a_value + 1}

rawDescription: how to build a Python dict value from another one during dict creation?

description: Build a Python dict value from another one during dict creation


code:
# Just some data to test:
from random import gauss
a = [[gauss(0, 10) for i in xrange(0, 5)] for j in xrange(0,5)]

from pylab import * # or just launch "IPython -pylab" from the command line

# We create a custom colormap:
myblue = cm.colors.LinearSegmentedColormap("myblue", {
    'red':   [(0, 1, 1), (1, 0, 0)],
    'green': [(0, 1, 1), (1, 0, 0)],
    'blue':  [(0, 1, 1), (1, 1, 1)]})

# Plotting the graph:
imshow(a, cmap=myblue)

rawDescription: Creating an Infographic In Python

description: Creating an Infographic In Python


code:
with open('dna.txt') as f:
    fdna = f.read()

fdna = fdna.lower()
...

rawDescription: Writing python chunking loops with reference to another txt


code:
PATTERN_ONE_OR_TWO_ARGS = """
    power< 'func' trailer< '('
        ( not(arglist | argument<any '=' any>) obj1=any
        | arglist< obj1=any ',' obj2=any > )
    ')' > >
    """

rawDescription: pattern to match 1-or-2-arg function call for lib2to3

description: Pattern to match 1-or-2-arg function call for lib2to3


code:
class WindowsFirefoxBinary(FirefoxBinary):

    def _start_from_profile_path(self, path):
        self._firefox_env["XRE_PROFILE_PATH"] = path

        if platform.system().lower() == 'linux':
            self._modify_link_library_path()
        command = [self._start_cmd, "-silent"]
        if self.command_line is not None:
            for cli in self.command_line:
                command.append(cli)

        # Added stdin argument:
        nul = open(os.devnull, 'w+')
        Popen(command, stdin=nul, stdout=self._log_file or nul, stderr=STDOUT,
              env=self._firefox_env).communicate()
        command[1] = '-foreground'
        self.process = Popen(
            command, stdin=nul, stdout=self._log_file or nul, stderr=STDOUT,
            env=self._firefox_env)

rawDescription: How to run Selenium Webdriver with pythonw?

description: Run Selenium Webdriver with pythonw


code:
from collections import Counter
sum(map(Counter, dict_x), Counter())

rawDescription: How to merge a list of dicts, summing values for repeated keys

description: Merge a list of dicts, summing values for repeated keys


code:
try:
   num1 = int(input("Enter an interger as your first number: "))
   num2 = int(input("Enter an integer as second number: "))
except ValueError:
   continue

rawDescription: how to add restart command in python?

description: Add restart command in python


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

depth = np.linspace(-600, 0, 30)
temp = (4 * np.random.random(depth.size)).cumsum()

fig, ax = plt.subplots()
ax.plot(temp, depth, 'k-')
ax.axis([0, 80, -600, 0])
ax.set_ylabel(r'Depth $(m)$')
ax.set_xlabel(r'Temperature $(^{\circ}C)$')
ax.set_xticks(np.arange(0, 100, 20))
ax.grid(True)

fig.savefig('plot.svg', transparent=True)
plt.show()

rawDescription: How do I 'correct' this matplotlib plotting routine?


code:
from itertools import izip, islice
myList = ['first_key', 'first_value', 'second_key', 'second_value']
myDict = dict(izip(islice(myList,0,None,2), islice(myList,1,None,2)))

rawDescription: converting a simple list to a dictionary (in python)

description: Converting a simple list to a dictionary (in python)


code:
for p in pairs:
  like,dislike = [],[]

rawDescription: Parsing a pretty printed table into Python objects


code:
df = df.loc[~df['Type'].isin(['UnweightedBase', 'Base'])]
df

rawDescription: Delete multiple Pandas DataFrame row where column value is this or that


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

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

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
        FancyArrowPatch.draw(self, renderer)

def Rx(phi):
    return np.array([[1, 0, 0],
                     [0, np.cos(phi), -np.sin(phi)],
                     [0, np.sin(phi), np.cos(phi)]])

def Ry(theta):
    return np.array([[np.cos(theta), 0, np.sin(theta)],
                     [0, 1, 0],
                     [-np.sin(theta), 0, np.cos(theta)]])

def Rz(psi):
    return np.array([[np.cos(psi), -np.sin(psi), 0],
                     [np.sin(psi), np.cos(psi), 0],
                     [0, 0, 1]])

# define origin
o = np.array([0,0,0])

# define ox0y0z0 axes
x0 = np.array([1,0,0])
y0 = np.array([0,1,0])
z0 = np.array([0,0,1])

# define ox1y1z1 axes
psi = 20 * np.pi / 180
x1 = Rz(psi).dot(x0)
y1 = Rz(psi).dot(y0)
z1 = Rz(psi).dot(z0)

# define ox2y2z2 axes
theta = 10 * np.pi / 180
x2 = Rz(psi).dot(Ry(theta)).dot(x0)
y2 = Rz(psi).dot(Ry(theta)).dot(y0)
z2 = Rz(psi).dot(Ry(theta)).dot(z0)

# define ox3y3z3 axes
phi = 30 * np.pi / 180
x3 = Rz(psi).dot(Ry(theta)).dot(Rx(phi)).dot(x0)
y3 = Rz(psi).dot(Ry(theta)).dot(Rx(phi)).dot(y0)
z3 = Rz(psi).dot(Ry(theta)).dot(Rx(phi)).dot(z0)

# produce figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
arrow_prop_dict = dict(mutation_scale=20, arrowstyle='-|>', color='k', shrinkA=0, shrinkB=0)
# plot ox0y0z0 axes
a = Arrow3D([o[0], x0[0]], [o[1], x0[1]], [o[2], x0[2]], **arrow_prop_dict)
ax.add_artist(a)
a = Arrow3D([o[0], y0[0]], [o[1], y0[1]], [o[2], y0[2]], **arrow_prop_dict)
ax.add_artist(a)
a = Arrow3D([o[0], z0[0]], [o[1], z0[1]], [o[2], z0[2]], **arrow_prop_dict)
ax.add_artist(a)

# plot ox1y1z1 axes
a = Arrow3D([o[0], x1[0]], [o[1], x1[1]], [o[2], x1[2]], **arrow_prop_dict)
ax.add_artist(a)
a = Arrow3D([o[0], y1[0]], [o[1], y1[1]], [o[2], y1[2]], **arrow_prop_dict)
ax.add_artist(a)
a = Arrow3D([o[0], z1[0]], [o[1], z1[1]], [o[2], z1[2]], **arrow_prop_dict)
ax.add_artist(a)

# draw dotted arc in x0y0 plane
arc = np.arange(-5,116) * np.pi / 180
p = np.array([np.cos(arc),np.sin(arc),arc * 0])
ax.plot(p[0,:],p[1,:],p[2,:],'k--')

# mark z0 rotation angles (psi)
arc = np.linspace(0,psi)
p = np.array([np.cos(arc),np.sin(arc),arc * 0]) * 0.6
ax.plot(p[0,:],p[1,:],p[2,:],'k')
p = np.array([-np.sin(arc),np.cos(arc),arc * 0]) * 0.6
ax.plot(p[0,:],p[1,:],p[2,:],'k')

# plot ox2y2z2 axes
a = Arrow3D([o[0], x2[0]], [o[1], x2[1]], [o[2], x2[2]], **arrow_prop_dict)
ax.add_artist(a)
a = Arrow3D([o[0], y2[0]], [o[1], y2[1]], [o[2], y2[2]], **arrow_prop_dict)
ax.add_artist(a)
a = Arrow3D([o[0], z2[0]], [o[1], z2[1]], [o[2], z2[2]], **arrow_prop_dict)
ax.add_artist(a)

# draw dotted arc in x1z1 plane
arc = np.arange(-5,105) * np.pi / 180
p = np.array([np.sin(arc),arc * 0,np.cos(arc)])
p = Rz(psi).dot(p)
ax.plot(p[0,:],p[1,:],p[2,:],'k--')

# mark y1 rotation angles (theta)
arc = np.linspace(0,theta)
p = np.array([np.cos(arc),arc * 0,-np.sin(arc)]) * 0.6
p = Rz(psi).dot(p)
ax.plot(p[0,:],p[1,:],p[2,:],'k')
p = np.array([np.sin(arc),arc * 0,np.cos(arc)]) * 0.6
p = Rz(psi).dot(p)
ax.plot(p[0,:],p[1,:],p[2,:],'k')

# plot ox3y3z3 axes
a = Arrow3D([o[0], x3[0]], [o[1], x3[1]], [o[2], x3[2]], **arrow_prop_dict)
ax.add_artist(a)
a = Arrow3D([o[0], y3[0]], [o[1], y3[1]], [o[2], y3[2]], **arrow_prop_dict)
ax.add_artist(a)
a = Arrow3D([o[0], z3[0]], [o[1], z3[1]], [o[2], z3[2]], **arrow_prop_dict)
ax.add_artist(a)

# draw dotted arc in y2z2 plane
arc = np.arange(-5,125) * np.pi / 180
p = np.array([arc * 0,np.cos(arc),np.sin(arc)])
p = Rz(psi).dot(Ry(theta)).dot(p)
ax.plot(p[0,:],p[1,:],p[2,:],'k--')

# mark x2 rotation angles (phi)
arc = np.linspace(0,phi)
p = np.array([arc * 0,np.cos(arc),np.sin(arc)]) * 0.6
p = Rz(psi).dot(Ry(theta)).dot(p)
ax.plot(p[0,:],p[1,:],p[2,:],'k')
p = np.array([arc * 0,-np.sin(arc),np.cos(arc)]) * 0.6
p = Rz(psi).dot(Ry(theta)).dot(p)
ax.plot(p[0,:],p[1,:],p[2,:],'k')

text_options = {'horizontalalignment': 'center',
                'verticalalignment': 'center',
                'fontsize': 14}

# add label for origin
ax.text(0.0,0.0,-0.05,r'$o$', **text_options)

# add labels for x axes
ax.text(1.1*x0[0],1.1*x0[1],1.1*x0[2],r'$x_0$', **text_options)
ax.text(1.1*x1[0],1.1*x1[1],1.1*x1[2],r'$x_1$', **text_options)
ax.text(1.1*x2[0],1.1*x2[1],1.1*x2[2],r'$x_2, x_3$', **text_options)

# add lables for y axes
ax.text(1.1*y0[0],1.1*y0[1],1.1*y0[2],r'$y_0$', **text_options)
ax.text(1.1*y1[0],1.1*y1[1],1.1*y1[2],r'$y_1, y_2$', **text_options)
ax.text(1.1*y3[0],1.1*y3[1],1.1*y3[2],r'$y_3$', **text_options)

# add lables for z axes
ax.text(1.1*z0[0],1.1*z0[1],1.1*z0[2],r'$z_0, z_1$', **text_options)
ax.text(1.1*z2[0],1.1*z2[1],1.1*z2[2],r'$z_2$', **text_options)
ax.text(1.1*z3[0],1.1*z3[1],1.1*z3[2],r'$z_3$', **text_options)

# add psi angle labels
m = 0.55 * ((x0 + x1) / 2.0)
ax.text(m[0], m[1], m[2], r'$\psi$', **text_options)
m = 0.55 * ((y0 + y1) / 2.0)
ax.text(m[0], m[1], m[2], r'$\psi$', **text_options)

# add theta angle lables
m = 0.55 * ((x1 + x2) / 2.0)
ax.text(m[0], m[1], m[2], r'$\theta$', **text_options)
m = 0.55 * ((z1 + z2) / 2.0)
ax.text(m[0], m[1], m[2], r'$\theta$', **text_options)

# add phi angle lables
m = 0.55 * ((y2 + y3) / 2.0)
ax.text(m[0], m[1], m[2], r'$\phi$', **text_options)
m = 0.55 * ((z2 + z3) / 2.0)
ax.text(m[0], m[1], m[2], r'$\phi$', **text_options)

# show figure
ax.view_init(elev=-150, azim=60)
ax.set_axis_off()
plt.show()

rawDescription: Arrows in matplotlib using mplot3d

description: Arrows in matplotlib using mplot3d


code:
{   'Animal': {   'Act': 'NOT_FOUND',
                  'Exp': {   'Huge': {   'Elephant': {   'color': 'black'}}}},
    'Person-->Female': {   'Act': 'Serena',
                           'Exp': {   'Girls': {   'Maria': {   'age': 15},
                                                   'Serena': {   'age': 23}}}},
    'Person-->Male-->Boys-->Rafa': {   'Act': 'NOT_FOUND', 'Exp': {   'age': 25}},
    'Person-->Male-->Boys-->Roger-->age': {   'Act': 2, 'Exp': 20}
}

rawDescription: Is there a good way python to compare complex dictionaries with unkonwn depth & level


code: ZZ[t]

rawDescription: Representing rings of algebraic integers


code:
def func_1(a, b, c):
    # Function body
    return (a, b, c)

rawDescription: Python: variables not cumulative passing through functions


code:
df1 = df[["Misc", "Year"] + [c for c in df.columns if c[-1] == "1"]]
df1 = df1.rename(columns=lambda x: x[:-1] if x[-1] == "1" else x)
df1
df2 = df[["Misc", "Year"] + [c for c in df.columns if c[-1] == "2"]]
df2 = df2.rename(columns=lambda x: x[:-1] if x[-1] == "2" else x)
pd.concat([df1, df2])

rawDescription: Python Flatten Dataframe With Multiple Columns all n-length


rawDescription: Convert string to variables (like format(), but in reverse) in Python


rawDescription: Python regex multiline replacement

description: Python regex multiline replacement


code:
# Additional directories which hold static files
STATICFILES_DIRS = [
    os.path.join(PROJECT_ROOT, "static"),
]

rawDescription: How to change the pinax(0.9a2) template?

description: Change the pinax(0.9a2) template


rawDescription: Parse a text file to a list of dictionaries


code: a = min(maximum, a)

rawDescription: value <= maximum

description: Value <= maximum


message: Request was successfully processed.

trackingCarrierCd: FDXE

trackingCarrierDesc: FedEx Express

shipperCity: SEOUL

shipperCntryCD: KR

recipientCity: CHEK LAP KOK

recipientCntryCD: HK

keyStatus: Delivered

keyStatusCD: DL

receivedByNm: .CHOP

subStatus: Signed for by: .CHOP

statusBarCD: DL

statusLocationCity: CHEK LAP KOK

statusLocationCntryCD: HK

statusWithDetails: Delivered: 9/02/2013 11:58 am Signed for by:.CHOP; CHEK LAP KOK, HK

displayTotalKgsWgt: 3.5 kgs

displayTotalLbsWgt: 7.8 lbs

displayPkgKgsWgt: 3.5 kgs

displayPkgLbsWgt: 7.8 lbs

serviceDesc: FedEx International Priority

serviceShortDesc: IP

packaging: Your Packaging

specialHandlingServicesList:
Deliver Weekday
Weekend Pick-Up

status: Delivered

statusCD: DL

scanLocation: CHEK LAP KOK HK

status: On FedEx vehicle for delivery

statusCD: OD

scanLocation: LANTAU ISLAND HK

status: At local FedEx facility

statusCD: AR

status: International shipment release - Import

statusCD: CC

status: Shipment exception

statusCD: SE

scanLocation: GUANGZHOU CN

scanDetails: Delay beyond our control

status: Departed FedEx location

statusCD: DP

status: Arrived at FedEx location

status: In transit

statusCD: IT

scanLocation: SHANGHAI CN

scanLocation: INCHEON KR

status: Left FedEx origin facility

scanLocation: SEOUL KR

status: Picked up

statusCD: PU

status: Shipment information sent to FedEx

statusCD: OC

originCity: SEOUL

originCntryCD: KR

originTermCity: SEOUL

destLocationCity: LANTAU ISLAND

destLocationCntryCD: HK

destLocationTermCity: LANTAU ISLAND

destCity: CHEK LAP KOK

destCntryCD: HK

actualDelAddrCity: CHEK LAP KOK

actualDelAddrCntryCD: HK

delToDesc: Shipping/Receiving

defaultCDOType: CDO

rawDescription: Parsing HTML does not output desired data(tracking info for FedEx)


code:
g = df.groupby(['A', 'B'])
df1 = df.set_index(['A', 'B'])

rawDescription: python pandas groupby() result

description: Python pandas groupby() result


code:
import flask.ext.whooshalchemy

# set the location for the whoosh index
app.config['WHOOSH_BASE'] = 'path/to/whoosh/base'

class BlogPost(db.Model):
  __tablename__ = 'blogpost'
  __searchable__ = ['title', 'content']  # these fields will be indexed by whoosh

  id = app.db.Column(app.db.Integer, primary_key=True)
  title = app.db.Column(app.db.Text)
  content = app.db.Column(app.db.Text)
  created = db.Column(db.DateTime, default=datetime.datetime.utcnow)

  def __repr__(self):
     return '{0}(title={1})'.format(self.__class__.__name__, self.title)

rawDescription: Search Index for user articles

description: Search Index for user articles


code:
def test(streams):
    for stream in streams:
        b=TestReader(stream)
        do_something(b)
        wrappedstream = b.detach()
        assert wrappedstream is stream

rawDescription: prevent BufferedReader from closing the file for a list of files

description: Prevent BufferedReader from closing the file for a list of files


rawDescription: Script/utility to rewrite all svn:externals in repository trunk


code: [ np.sum(row) for row in C.T ]

rawDescription: Python: applying function to each column of an array


code:
def c_id_overlap(df):
    common_vals = [] #container for values of c_col1 that are in ever c_id subgroup
    c_ids = df.c_id.unique() #get unique values of c_id
    c_col1_values = set(df.c_col1) # get a set of c_col1 values
    #create nested list of values. Each inner list contains the c_col1 values for each c_id
    nested_c_col_vals = [list(df[df.c_id == ID]['c_col1'].unique()) for ID in c_ids]
    #Iterate through the c_col1_values and see if they are in every nested list
    for val in c_col1_values:
        if all([True if val in elem else False for elem in nested_c_col_vals]):
            common_vals.append(val)
    #return a slice of the dataframe that only contains values of c_col1 that are in every
    #c_id
    return df[df.c_col1.isin(common_vals)]

rawDescription: Split Pandas Dataframe into separate pieces based on column values


code:
def add_col_c(x):
    x['col_c'] = np.arange(len(x))
    return x

rawDescription: Enumerate each row for each group in a DataFrame


code:
my_file = open('my_file.txt', 'w')
sys.stdout = my_file
print("hello") # now written to my_file.txt

rawDescription: Storing Python output in a string

description: Storing Python output in a string


code:
df1 = df1.drop_duplicates()
df3 = pd.merge(df1, df1, on='Vehicle_ID', how='left'); df3

rawDescription: Count by combination

description: Count by combination


rawDescription: python array manipulation and rearranging

description: Python array manipulation and rearranging


rawDescription: pandas DataFrame concat / update ("upsert")?

description: Pandas DataFrame concat / update ("upsert")


code:
p = figure(...)
p.rect(...)

rawDescription: Plot topics with bokeh or matplotlib

description: Plot topics with bokeh or matplotlib


code: self.assertEqual(len(self.soup.find_all('html')), 1, msg="HTML Tag is missing!")

rawDescription: Checking for duplicate tags using Beautifulsoup


code:
import os

with open(section + "_tmp"+".txt", "a") as fi:
    fi.write(os.linesep)
    fi.write(files1)
    # Or simply fi.write(os.linesep + files1)

rawDescription: How do i write a new line or \n into a file

description: Write a new line or \n into a file


rawDescription: Build slice objetcs from subscript notation


rawDescription: How to make a dictionary, in which multiple values access one value(Python)

description: Make a dictionary, in which multiple values access one value(Python)


code:
bs = BeautifulSoup.BeautifulSoup(html)

parent_stack = [None]
res = []
for span in bs.findAll('span', {'style':'white-space:nowrap;display:inline-block'}):
    indent = 1 + span.previousSibling.count(' ') / 5
    id = int(span.find('input')['value'])
    name = span.find('a').text.strip()

    # warning! this assumes that indent-level only ever
    #   increases by 1 level at a time!
    parent_stack = parent_stack[:indent] + [id]
    res.append(parent_stack[-2:])

rawDescription: Python Regex challenge indentation

description: Python Regex challenge indentation


code:
entire_raw_data = sys.stdin.read()
lines = entire_raw_data.split()
... # do something with lines

rawDescription: How to process raw data (in python)?

description: Process raw data (in python)


rawDescription: Python delimited line split problems

description: Python delimited line split problems


code: list(map(str.split, config))

rawDescription: Iterate over a list to apply a method to each member


code:
test_1: 0
test_1: 1
test_1: 2
test_1: 3
test_1: 4
test_2: 0
test_1: 5
test_2: 1
test_1: 6
test_2: 2
test_1: 7
test_2: 3
test_1: 8
test_2: 4
test_1: 9
test_2: 5
test_2: 6
test_2: 7
test_2: 8
test_2: 9

rawDescription: Writing to file in multi-threading

description: Writing to file in multi-threading


code:
d = { 'key1': 'value1',
  'key2': 'value2',
  'key3': [1,2,3, { 1: 3, 7 : 9}],
  'key4': object(),
  'key5': { 'another key1' : 'another value1',
            'another key2' : 'another value2'} }

widget = QTreeWidget()
fill_widget(widget, d)
widget.show()

rawDescription: QTreeWidget to Mirror python Dictionary

description: QTreeWidget to Mirror python Dictionary


code:
iris = Data(odo(os.path.abspath('./blaze/examples/data/iris.csv'), 'postgresql://localhost::iris'))
iris
iris.species.distinct()
print(str(iris.species.distinct()))
print(repr(iris.species.distinct()))

rawDescription: python blaze postgresql can't print "distinct" iris species

description: Python blaze postgresql can't print "distinct" iris species


code:
a = raw_input("enter the values ")
aList[-1] = a

rawDescription: How to update list in python from user entered value in last item

description: Update list in python from user entered value in last item


code:
for sublist in list:
    if (movie == sublist[0]) and (code == sublist[5]):
         return True
return False

rawDescription: How to check whether a value is in a list

description: Check whether a value is in a list


code: filtered = filter(lambda x: not re.match(r'^\s*$', x), original)

rawDescription: Remove empty lines

description: Remove empty lines


code:
atom_indices = [0, 4, 5, 8]
coords = [3*a+k for a in atom_indices for k in range(3)]
coords

rawDescription: Create larger list from an existing list using a list comprehension or map()


code:
mix = [(i,data[i]) for i in index if data[i] > 1000]
xim = [a for a in zip(*mix)]
indexes = list(xim[0])
values = list(xim[1])

rawDescription: Removing elements from list based on index from another list


code:
import matplotlib.pyplot as plt

n = 10
x = np.linspace(0, 2*np.pi, n)
y0 = np.cos(x) # zero initial slope
std = 0.5
noise = np.random.normal(0, std, len(x))
y = y0 + noise
k = 3

sp0 = UnivariateSpline(x, y, k=k, s=n*std)
sp = spline_neumann(x, y, k, s=n*std)

plt.figure()
X = np.linspace(x.min(), x.max(), len(x)*10)
plt.plot(X, sp0(X), '-r', lw=1, label='guess')
plt.plot(X, sp(X), '-r', lw=2, label='spline')
plt.plot(X, sp.derivative()(X), '-g', label='slope')
plt.plot(x, y, 'ok', label='data')
plt.legend(loc='best')
plt.show()

rawDescription: Spline with constraints at border

description: Spline with constraints at border


code:
df.ix[df['INDEX'] == 'AZB', 'INDEX'] = np.NaN
df.fillna(method='ffill', inplace=True)

rawDescription: conditional replacement with pandas

description: Conditional replacement with pandas


rawDescription: Put value at centre of bins for histogram


code:
df = pd.DataFrame({'a': [10,20,30,20,30], 'b': [1,2,3,2,1]})
df
df_counts = df.groupby(["a", "b"]).size()
df_counts.sort(ascending=False)
df_counts

rawDescription: How to create a new column with a tuple (or a list)?

description: Create a new column with a tuple (or a list)


code:
import ast
ast.literal_eval("{'a': 1, 'b': 2, 'c': 3}")

rawDescription: How can I extract a dict form from a string?

description: Extract a dict form from a string


rawDescription: pands groupby last n

description: Pands groupby last n


code:
rect_sizes = []
for x in range(-50, 500, position_x + 20):
    for y in range(-50, 400, position_y + 20):
        rect_size = pygame.Rect(position_x + x, position_y + y, position_x, position_y)
        pygame.draw.rect(screen, colour, rect_size, 0)
        rect_sizes.append(rect_size)

if event.type == pygame.MOUSEBUTTONDOWN:
    for rect_size in rect_sizes:
        click = rect_size.collidepoint(pygame.mouse.get_pos())

        if click == 1:
            print("Clicked")
            pygame.draw.rect(screen, white, rect_size, 0)

rawDescription: How do I check to see if a mouse click is within a rectangle for each rectangle in this pygame program?

description: Check to see if a mouse click is within a rectangle for each rectangle in this pygame program


code: {k: dict(v) for k, v in tp.iteritems()}

rawDescription: Removing 'Counter' from Dictionary python


code:
import requests
from bs4 import BeautifulSoup

url = 'http://espn.go.com/nba/teams'
r = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17'})

soup = BeautifulSoup(r.content, 'lxml')

teams = []
for link in soup.select('div.mod-table div.mod-content ul li h5 a[href]'):
    teams.append({
        'name': link.text,
        'url': link['href']
    })

print(teams)

rawDescription: How can I get text from within a nested <dl><dt>?

description: Get text from within a nested <dl><dt>


code:
caller(1, "ciao")
caller.assert_called_with(Any(int, str), Any(int, str))
caller("Hello, World!", 2)
caller.assert_called_with(Any(int, str), Any(int, str))

rawDescription: Assert that a method was called with one argument out of several


code: T.index = [i.strftime('%d %H:%M') for i in T.index]

rawDescription: Get time of month in pandas

description: Get time of month in pandas


code: np.sum([np.random.binomial(1,p=ps) for i in range(100000)], axis=0)

rawDescription: numpy draw a few bernoulli distributions at once

description: Numpy draw a few bernoulli distributions at once


rawDescription: How to delete a character off a string with variables and functions in Python?

description: Delete a character off a string with variables and functions in Python


code:
yourdata = [{15: [32, 'massages']}, {45: [12, 'hair-salon']}, {23:[3, 'automotive service']}]

# transfer your data into a more usable format
data = [(score,cat,name) for dat in yourdata for cat,(score,name) in dat.iteritems()]

# sort on descending score
data.sort(reverse=True)

# throw away the low-scoring items
data = data[:int(len(data)*0.6 + 1)]

rawDescription: Python - Find top largest numbers in array


rawDescription: Return rows only if all items of category are True


code: from common_imports import *

rawDescription: common import statement for similar classes

description: Common import statement for similar classes


rawDescription: Python how to match files to templates

description: Python how to match files to templates


rawDescription: How to display or show notepad file using python

description: Display or show notepad file using python


rawDescription: Use attributes in heuristic

description: Use attributes in heuristic


code:
# Doing it like this is slow
for index, row in df.iterrows():
     model = MyModel()
     model.field_1 = row['field_1']
     model.save()

rawDescription: How to write a Pandas Dataframe to Django model

description: Write a Pandas Dataframe to Django model


code: temp = temp.next.next

rawDescription: Deleting a specific node from a linked list - python


code: {'word': 'another_word'}

rawDescription: Parsing html elements using BeautifulSoup


rawDescription: Numpy Matrix Multiplication U*B*U.T Results in Non-symmetric Matrix


code:
with open('data.json') as f:
    data = f.read()

rawDescription: Python beginner: how to reduce execution time of this small program?


code:
import networkx as nx
G = nx.Graph()
G.add_edge(1, 2, weight=3, type="green")
G[1][2]
G[1][2]["weight"]

rawDescription: Is it possible to add a weight/probability to a node in graph theory(using networkx)


code:
strs = "#define FULL_CHIP /* Turn on for chip level design */"
re.sub(r'(#define FULL_CHIP)',r'//\1', strs)

rawDescription: re module in Python

description: Re module in Python


code:
movies = dict((m['name'], m['year']) for m in movies)
rest_movies = dict((m['name'], m['year']) for m in rest_movies)

rawDescription: Efficient way to find unique value in one of few lists


rawDescription: Dynamically calculated zero padding in format string in python


code:
import ipaddress

ipsub = {"10.10.10.0/24": "Firewall-Denver" ,"10.10.20.0/25": "Firewall-NewYork"}
iplist = ["10.10.10.1","10.10.10.174","10.10.20.126"]

ipfirewall = []

for i in ipsub:
    for j in iplist:
        if ipaddress.ip_address(j) in ipaddress.ip_network(i):
            ipfirewall.append([j,ipsub[i]])
with open('output.txt', 'w') as file:
    file.writelines('\t'.join(i) + '\n' for i in ipfirewall)

rawDescription: Matching IP addresses to a list of subnets and then returning the firewall


code:
def hasNumbers(inputString):
    return any(char.isdigit() for char in inputString)

hasNumbers("I own 1 dog")
hasNumbers("I own no dog")

rawDescription: check if a string contains a number

description: Check if a string contains a number


code: print(len(filter(lambda x: x is not None, lst)))

rawDescription: How to count the number of occurences of `None` in a list?

description: Count the number of occurences of `None` in a list


code:
children = {child.get('value') for child in xml_data}
for item in main_list:
    if item[4] in children:
        print(item[4])

rawDescription: Compare two lists in python and print the output


code: sorted(dictionary.items(), key=lambda t: (t[1], t[0][2:]))

rawDescription: Skip first two characters in (key=lambda) sorting


code:
from PIL import Image

self.assertIsInstance(SimpleExample.img, Image.Image)

rawDescription: assertIsInstance() against multiple class names

description: AssertIsInstance() against multiple class names


code:
def getinternaldep(item):
    local_list = []
    temp_list = []
    # Change this line depending on data format
    temp_list.extend(internal_dep[item])
    local_list.extend(temp_list)
    for new_item in temp_list:
        internal_dep_list = getinternaldep(new_item)
        local_list.extend(internal_dep_list)
    return local_list

def getexternaldep(item):
    local_list = []
    temp_list = []
    # Change this line depending on data format
    temp_list.extend(external_dep[item])
    local_list.extend(temp_list)
    for new_item in temp_list:
        external_dep_list = getexternaldep(new_item)
        local_list.extend(external_dep_list)
    return local_list

rawDescription: Recursive algorithm for generating a acyclic directed graph


code:
def filtercalls(call_stack, modul, clas, func, full):
    mod_ignore = ['shutil','scipy.optimize','re','os','sys','json']
    func_ignore = ['CustomFunctionName','pdbcall']
    clas_ignore = ['pdb']
    return modul not in mod_ignore and func not in func_ignore and clas not in clas_ignore

rawDescription: How to remove library modules or specific functions from pycallgraph

description: Remove library modules or specific functions from pycallgraph


code: mkswap /var/swap.img

rawDescription: Django-cities exits with "killed"

description: Django-cities exits with "killed"


rawDescription: Remove brackets from argv string

description: Remove brackets from argv string


rawDescription: numpy matrix rank incorrect result

description: Numpy matrix rank incorrect result


rawDescription: How to define a chi2 value function for arbitrary function?

description: Define a chi2 value function for arbitrary function


code: [u'bird', u'smart', u'cool', u'happy', u'bird', u'smart', u'smarting', u'smartness', u'cool', u'dickeybird', u'cock', u'hen', u'nester', u'night bird', u'bird of passage', u'protoavis', u'archaeopteryx', u'Sinornis', u'Ibero-mesornis', u'archaeornis', u'ratite', u'carinate', u'passerine', u'nonpasserine bird', u'bird of prey', u'gallinaceous bird', u'parrot', u'cuculiform bird', u'coraciiform bird', u'apodiform bird', u'caprimulgiform bird', u'piciform bird', u'trogon', u'aquatic bird', u'twitterer']

rawDescription: Synset function to include synonym in a list


code: customer = models.ForeignKey('Customer', null=True, blank=True, db_constraint=False)

rawDescription: Django ForeignKey which does not require referential integrity?


code:
{
 email : 'test@example.com',
 accounts.type : ['fb', 'tw'],
 accounts.account_id : ['1', '2'],
 accounts.state : ['1', '2'],
 accounts.access_token : ['1', '2'],
 accounts.access_token_secret : ['2']
}

rawDescription: Custom properties not saved correctly for Expando models in repeated StructuredProperty


code:
def commonBand(L1, L2):
    answer = []
    for band in L1:
        if band in L2:
            answer.append(band)
    return answer

rawDescription: Common Favorite Band Python

description: Common Favorite Band Python


rawDescription: Assert list of list equality without order in Python


code:
def validate_class(cls):
    if (len(cls) != 3 or
        int(cls[0]) not in [5, 6] or
        cls[1] not in ["A", "B", "C"] or
        int(cls[2]) not in [1, 2]):
        return False
    return True

rawDescription: How do I validate text entry to match an expected input?

description: Validate text entry to match an expected input


code:
import os
from django.shortcuts import render

def command_view(request):
    output = os.popen('ls -l').read()
    return render(request, 'command.html', {'output': output})

rawDescription: How do I display the results of basic shell commands in a Django 1.4 website?

description: Display the results of basic shell commands in a Django 1.4 website


code:
log.setLevel( logging.INFO )
func1_log.setLevel( logging.ERROR )

rawDescription: Disable logging per method/function?

description: Disable logging per method/function


rawDescription: Loading modules that change sys.path

description: Loading modules that change sys.path


rawDescription: I need help ordering nested loops by integers and displaying them


rawDescription: Crawling multiple sites with Python Scrapy with limited depth per site


rawDescription: Integer to string length in python?

description: Integer to string length in python


code:
while True:
    for i in range(len(asteroids)):
        ...
        # Collision checking
        myrocket.check_asteroid_collision( asteroids[i], asteroidsize[i] );

rawDescription: Sprite collide with object function?

description: Sprite collide with object function


code: args, kwargs = self.__translate(args, kwargs)

rawDescription: Django : how could I overload Q in django.db.models.query QuerySet to use for a special purpose in my Manager


rawDescription: How to print a conditional's literal expression in Python

description: Print a conditional's literal expression in Python


code:
class A(object):
    def __getattr__(self, attr):
        if attr == 'big_attr':
            self.__class__.big_attr = heavy_func(self.VAL)
        return object.__getattribute__(self, attr)

rawDescription: pythonic way of computing a value to a class object only once

description: Pythonic way of computing a value to a class object only once


code:
s = """// some comment

foo
bar
foobar
/* comment
   more comment */ bar"""
m = re.findall(r'(?://[^\n]*|/\*(?:(?!\*/).)*\*/)', s, re.DOTALL)
m

rawDescription: Python regex for matching single line and multi line comments.


code:
from random import getrandbits, randint, random, sample

s = list(range(100))

def loop_bits():
    res = []
    b = getrandbits(len(s))
    for i in s:
        if b % 2 == 0:
            res.append(i)
        b >>= 1

def comp_bits():
    res = [i for i in s if getrandbits(1)]

def comp_randint():
    res = [i for i in s if randint(0, 1)]

def comp_random():
    res = [i for i in s if random() >= .5]

rawDescription: Generate Sequence of Booleans Quickly in Python


code:
def get_dictionary_word_list():
    # with context manager assures us the
    # file will be closed when leaving the scope
    with open('dictionary.txt') as f:
        # return the split results, which is all the words in the file.
        return f.read().split()

rawDescription: How to return a list of words from a text file in python

description: Return a list of words from a text file in python


code:
x=[]
y=[]
x_val = 0
for i in values: #values is a list of several thousand experimental data points
  if x_val < 100:
    x.append(float(x_val))
    y.append(float(i))
  x_val += 5
x = np.asarray(x)
y = np.asarray(y)

rawDescription: Getting completely wrong fit from python scipy.optimize.curve_fit


code:
import sys
import sip
sip.setapi('QVariant', 2)
from PyQt4.QtGui import *
from PyQt4.QtCore import *

data = {"first":{"status":"closed"},"second":{"status":"expired"},"third":{ "status":"cancelled"}}

class ComboDelegate(QItemDelegate):

    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        li = []
        li.append("closed")
        li.append("expired")
        li.append("cancelled")
        li.append("waiting")
        editor.addItems(li)
        return editor

    def setEditorData(self, editor, index):
        value = index.model().data(index, Qt.EditRole)
        editor.setCurrentIndex(editor.findText(value))

class Example(QMainWindow):

    def __init__(self):
        super(Example, self).__init__()

        self.tableview = QTableView()
        self.tableview.setItemDelegateForColumn(1, ComboDelegate())

        self.setCentralWidget(self.tableview)

        self.model = QStandardItemModel()
        self.tableview.setModel(self.model)
        self.fillModel()

        self.show()

    def fillModel(self):
        for i in data:
            name_str = i
            status_str = data[i]["status"]
            name = QStandardItem(name_str)
            status = QStandardItem(status_str)
            items = [name, status]
            self.model.appendRow(items)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

rawDescription: How to restore the index of a QComboBox delegate in a QTableView?

description: Restore the index of a QComboBox delegate in a QTableView


code:
def genDocText(func_name):
    return r'''
    >>> conn = httplib.HTTPConnection(...)
    >>> %(func_name)s(None, conn)
    Traceback (most recent call last):
    NoneAsInputError: `mystring` should be a string and not `None`!

    >>> %(func_name)s("", conn)
    Traceback (most recent call last):
    EmptyStringError: `mystring` should not be an empty string!
    ''' % {'func_name': func_name}

def function_1(mystring, conn):
    pass

function_1.__doc__ = genDocText('function_1')

rawDescription: Better way to test several functions for the same thing in python


rawDescription: How to apply a modifier in Python, creating a new mesh?

description: Apply a modifier in Python, creating a new mesh


code:
df = pd.DataFrame(np.arange(12).reshape(4,3), columns=list('ABC'))
df.loc[:, ['A','B']]
df.loc[:, ('A','B')]

rawDescription: pandas dataframe view vs copy, how do I tell?

description: Pandas dataframe view vs copy, how do I tell


code:
import sys
import time
sys.stdout.write('Some text [\\]')
for i in ['-', '/', '|', '\\'] * 10:
    sys.stdout.write('\b\b\b[{0}]'.format(i))
    sys.stdout.flush()
    time.sleep(1)

rawDescription: How to create dynamic text?

description: Create dynamic text


code:
foobar = bar
foobar is bar
True

rawDescription: Why does string equality not working in this Python code as expected?


code:
a = [[2007, 206, 205, 8], [2007, 206, 208, 9]]
b = [[2007, 205, 206, 8], [2007, 207, 210, 10]]
from itertools import chain
seen = set()
c = []
for lst in chain(a,b):
    one_two = tuple(lst[:1] + sorted(lst[1:-1]) + lst[-1:])
    if one_two not in seen:
       seen.add(one_two)
       c.append(lst)

rawDescription: How do I loop through two lists of lists and avoid duplicate combinations for values at specific positions?

description: Loop through two lists of lists and avoid duplicate combinations for values at specific positions


code: make_list(2, 2)

rawDescription: How would you create a nested list with recursion in Python?


code:
for item in res:
    print(item)

#the_real_identifier
#the_real_identifier1

rawDescription: Remove part of an element in python

description: Remove part of an element in python


code:
from itertools import product
from pprint import pprint
brand = ["Audi", "Mercedes"]
speed = [130, 150]
model = ["sport", "family"]
keys = 'brand', 'speed', 'model'
[dict(zip(keys, combo)) for combo in product(brand, speed, model)]
pprint(_)

rawDescription: Cartesian product giving a dictionary

description: Cartesian product giving a dictionary


code:
datalayerInstance =  datalayer();

def get_datalayerinstance():
    return datalayerInstance

rawDescription: Python creating single instance in whole module


rawDescription: Rounding integers

description: Rounding integers


code:
import bisect
import random
from collections import Counter, Sequence

def weighted_sample(population, weights, k):
    return random.sample(WeightedPopulation(population, weights), k)

class WeightedPopulation(Sequence):
    def __init__(self, population, weights):
        assert len(population) == len(weights) > 0
        self.population = population
        self.cumweights = []
        cumsum = 0 # compute cumulative weight
        for w in weights:
            cumsum += w
            self.cumweights.append(cumsum)
    def __len__(self):
        return self.cumweights[-1]
    def __getitem__(self, i):
        if not 0 <= i < len(self):
            raise IndexError(i)
        return self.population[bisect.bisect(self.cumweights, i)]

rawDescription: Weighted random sample in python

description: Weighted random sample in python


code:
parser = objectify.makeparser(remove_comments=True)
tree = objectify.parse(xmlPath, parser=parser)

rawDescription: How to not load the comments while parsing XML in lxml

description: Not load the comments while parsing XML in lxml


code:
genes=[]
with open('data1', 'r') as f:
    genes=set(map(lambda line:line.strip(), f.readlines()))

with open('output', 'w') as f:
    with open('data', 'r') as csvfile:
        for i in map(lambda line:line.strip(), csvfile.readlines()):
            print(i+"\t*" if set(i.split()[0:2]) & genes else i, file=f)
            #print >>f, i+"\t*" if set(i.split()[0:2]) & genes else i   #for Python 2.x

rawDescription: I'd like to search a file, find matching terms from another list and then mark rows including those terms


code:
prices = appledata[0]["price"]
print(len(prices))  # prints 252

rawDescription: Python lengh of json is incorrect

description: Python lengh of json is incorrect


code:
import functools

def chainable(func):
    @functools.wraps(func)
    def decorated(*args, **kwargs):
        func(*args, **kwargs)
        return args[0]
    return decorated

rawDescription: DRYout a class-based chainable API

description: DRYout a class-based chainable API


code: any(d['Name'] == 'Dave' for d in dicts)

rawDescription: Find specific dictionary element without looping


code:
import os
if os.name == 'nt':
    pass # Windows
else:
    pass # other (unix)

rawDescription: Can python detect which OS is it running under?


code: pyplot.text(x, y, string, fontdict=None, withdash=False, **kwargs)

rawDescription: Show the final y-axis value of each line with matplotlib


rawDescription: How do I get nodes from the specific edge in the networkx?

description: Get nodes from the specific edge in the networkx


code:
root = Tk()
root.title("Monty Questions")
app = Tk_app()
root.mainloop()

rawDescription: Python tkinter, making a quiz with randomly generated questions that reset after each submit


rawDescription: Recreating a C CRC32 algorithm in Python with crcmod


code:
def removechars(m):
    x=m.group()
    n=re.match(r'\+(\d+).*', x).group(1) # digit part
    return '*'+x[1+len(n)+int(n):]

rawDescription: regex to match words of length specified within string

description: Regex to match words of length specified within string


code:
class Generator:
    def __init__(self, gen):
        self.gen = gen

    def __iter__(self):
        self.value = yield from self.gen

rawDescription: Best way to receive the 'return' value from a python generator

description: Receive the 'return' value from a python generator


code:
from pprint import pprint
from bs4 import BeautifulSoup
import requests

url = 'http://www.amazon.com/dp/0439136369'
response = requests.get(url, headers={'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'})

soup = BeautifulSoup(response.content)
tags = {}
for li in soup.select('table#productDetailsTable div.content ul li'):
    try:
        title = li.b
        key = title.text.strip().rstrip(':')
        value = title.next_sibling.strip()

        tags[key] = value
    except AttributeError:
        break

pprint(tags)

rawDescription: how to scrape product details on amazon webpage using beautifulsoup

description: Scrape product details on amazon webpage using beautifulsoup


code:
for row, array in enumerate(data):
    for col, value in enumerate(array):
        sheet1.write(row, col, value)

rawDescription: How can i get values in different ranges of cells?

description: Get values in different ranges of cells


code:
from collections import Counter

counts = Counter(item for key in d for item in key)
commonkkeylist = [item for item, count in counts.most_common() if count > 50]

rawDescription: How to quickly get a list of keys from dict

description: Quickly get a list of keys from dict


code: (func(x) for x in self._walk(starting_node))

rawDescription: Building a generator from a recursive algorithm


code: [node.attributes['name'].value for node in sorted(nodes, key=lambda x: x.attributes['name'].value)]

rawDescription: Sort nodes after using getElementsByTagName by the nodes attributes


rawDescription: Random's randint won't work in a for-loop


code:
def custom_replace(string, old, new):

    index = string.find(old)

    if index == -1:
        return string

    return string[:index] + new + string[index + len(old):]

string = 'Hello World !'

old = 'World'
new = 'StackOverflow'

print(custom_replace(string, old, new))

rawDescription: how to write a function, it will do the same thing with replace()

description: Write a function, it will do the same thing with replace()


code:
from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktLanguageVars

class BulletPointLangVars(PunktLanguageVars):
    sent_end_chars = ('.', '?', '!', '•')

tokenizer = PunktSentenceTokenizer(lang_vars = BulletPointLangVars())
tokenizer.tokenize(u"• I am a sentence • I am another sentence")

rawDescription: NLTK Sentence Tokenizer, custom sentence starters


code: df.applymap(lambda x: x == 'mike').any().any()

rawDescription: Check if one value exists in any rows of any columns in pandas?


code:
f = open(list, 'r')
text = f.read()
elements = text.split(" ")
for element in elements:
    print(element)

rawDescription: Print a list in python that I'm passing in


code:
with open('source.txt', 'r') as f:
    data = {}
    numbers = []
    for line in f:
        ln = line.strip()
        if 'Timestamp' in ln:
            data[ln] = numbers
            numbers = []
        elif ln:
            numbers.append([int(n) for n in ln.split()])

print(data)

rawDescription: How to selectively import only lines of words with genfromtxt into Python?

description: Selectively import only lines of words with genfromtxt into Python


code:
import os

uid = int(os.environ.get('SUDO_UID'))
gid = int(os.environ.get('SUDO_GID'))

os.chown("path/to/file", uid, gid)

rawDescription: Creating a file with python using sudo makes its owner root


code:
Post.objects.filter(hastags__pk=1)
Post.objects.filter(hastags=1)
Post.objects.filter(hashtags=h1)  # where h1 is an hashtag object instance
Post.objects.filter(hashtags__name__startswith="Science")

rawDescription: ORM data modeling in Python Django

description: ORM data modeling in Python Django


code:
a = numpy.arange(5)
a ** 2

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

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


rawDescription: python pandas: Simplest way to perform group by and extract count of unique entities?

description: Python pandas: Simplest way to perform group by and extract count of unique entities


code:
class Bond():
    def breakBond(self):
        self.start.removeBond(self)
        self.end.removeBond(self)

rawDescription: Is overriding __del__() the best choice here?


code:
numpy.isnan(a)
1 - numpy.isnan(a)

rawDescription: numpy 1D array to numpy arrays

description: Numpy 1D array to numpy arrays


code:
from itertools import takewhile, islice

def groups(l, keys, i, n):
    # lambda x: x != 0 -> take elements until we encounter any 0
    tk = takewhile(lambda x: x != i, l)
    while True:
        d = dict(zip(keys, islice(tk, n)))
        if len(d) == n: # make sure we have n keys in the dict
            yield d
        else:
            break

keys = ['gold', 'silver', 'bronze']
print(list(groups(l,keys,0,3)))
[{'bronze': 3, 'gold': 1, 'silver': 2}, {'bronze': 6, 'gold': 4, 'silver': 5}]

rawDescription: Loop through list until value is found then breaking?


code:
import math
# elsewhere
math.sqrt(n)

rawDescription: Is the expression math.sqrt() necessary?

description: Is the expression math.sqrt() necessary


code:
import re

math6 = iter(['chapter1', 'chapter2', 'chapter3', 'chapter1-3test'])
math4 = iter(['chapter1.1', 'chapter1.2-3', 'chapter2'])

text = r'''
    \begin{tabular}{|p{0.7in}|p{0.8in}|p{2.2in}|p{.9in}|p{2.6in}|p{1.6in}|}
    6${}^{th}$ Math  \newline M\newline  & _math6_&
    6${}^{th}$ Math  \newline W \newline  & _math6_ &
    6${}^{th}$ Math  \newline  F \newline  & _math6_ &
    4${}^{th}$ Math  \newline M\newline  &  & _math4_  &
    4${}^{th}$ Math \newline W\newline  &  & _math4_  &
    \end{tabular}
'''

def replace_with(data):
    def replacer(match):
        return next(data)
    return replacer

for pat, data in [(r'_math6_', math6), (r'_math4_', math4)]:
    text = re.sub(pat, replace_with(data), text)

print(text)

rawDescription: regex replace from a list

description: Regex replace from a list


code:
qtylist = []
for x in sd:
    qtylist.append((x.finished_case.name, x.qty))
return qtylist

rawDescription: Page Refresh Disrupts Sort Order. Server Restart Restores It


code:
import itertools
l = [1,2,3],[4,5,6],[7,8,9]
list(itertools.permutations(l, len(l)))

rawDescription: Making all possible combination of lists in lists


code:
u = User(username='matt')
g = Groups(name='test')
db.session.add(u)
db.session.add(g)
db.session.commit()
g.members.append(u)
db.session.commit()
db.session.delete(g)
db.session.commit()

rawDescription: many to many relationship with three tables (sql-alchemy)

description: Many to many relationship with three tables (sql-alchemy)


code:
#!/bin/python
import HTMLParser
parser=HTMLParser.HTMLParser()
print(parser.unescape("—"))

rawDescription: converting a string which contains (html)em-dash to a unified unified form?

description: Converting a string which contains (html)em-dash to a unified unified form


code:
# Assuming that Y is 1D, might need to do Y = Y.A.ravel() or such...

# just to make the point that this works only with CSR:
if not isinstance(X, scipy.sparse.csr_matrix):
    raise ValueError('Matrix must be CSR.')

Z = X.copy()
# simply repeat each value in Y by the number of nnz elements in each row:
Z.data *= Y.repeat(np.diff(Z.indptr))

rawDescription: Multiplying elements in a sparse array with rows in matrix


code: [[tuple(map(int, pair)) + (2,) for pair in pairs] for pairs in l]

rawDescription: Iterate over Python list, preserving structure of embedded lists


code:
def merge_value(cnt, doc):
    for v in doc:
        cnt[v] += 1
    return cnt1

rawDescription: Finding top words per kmeans cluster

description: Finding top words per kmeans cluster


code:
def mean_graph(graphs):
    return graphs[0][0], [sum(v) / len(graphs) for v in zip(*[g[1] for g in graphs])]

rawDescription: Mean function given a list of graphs

description: Mean function given a list of graphs


rawDescription: Width of an arbitrary polygon

description: Width of an arbitrary polygon


code: from genelist import GeneList

rawDescription: What is the Pythonic way of handling classes, modules, and packages with the same name?


rawDescription: Alternative to multiple try/except statements to check if a field exists


rawDescription: Focus on current Screen Selenium

description: Focus on current Screen Selenium


code: [s for (i,s) in enumerate(['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']) if i%3]

rawDescription: Python: building new list from existing by dropping every n-th element


code: block = wx.BoxSizer(wx.VERTICAL)

rawDescription: BoxSizer issue: Not expanding to fit contents of StaticText


code:
def encrypt(string, length):
    return ' '.join(string[i:i+length] for i in xrange(0,len(string),length))

rawDescription: How do I insert a space after a certain amount of characters in a string using python?

description: Insert a space after a certain amount of characters in a string using python


code:
import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime

x = [datetime.datetime(2011, 1, 4, 0, 0),
     datetime.datetime(2011, 1, 5, 0, 0),
     datetime.datetime(2011, 1, 6, 0, 0)]
x = date2num(x)

y = [4, 9, 2]
z=[1,2,3]
k=[11,12,13]

ax = plt.subplot(111)
ax.bar(x-0.2, y,width=0.2,color='b',align='center')
ax.bar(x, z,width=0.2,color='g',align='center')
ax.bar(x+0.2, k,width=0.2,color='r',align='center')
ax.xaxis_date()

plt.show()

rawDescription: python matplotlib multiple bars

description: Python matplotlib multiple bars


code:
import sys
import cStringIO
save_stdout = sys.stdout
sys.stdout = cStringIO.StringIO()
foo()
sys.stdout = save_stdout

rawDescription: Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call


code:
from datetime import datetime
noo = datetime.now()
then = noo.replace(month=3, day=15, hour=0, minute=0, second=0, microsecond=0)
diffy = noo - then
diffy
diffy.days

rawDescription: Python: how to get number of days from fixed past date to now


code:
def _run_wsgi_app(*args):
    from werkzeug.test import run_wsgi_app as new_run_wsgi_app
    import sys
    sys.modules[__name__]._run_wsgi_app = new_run_wsgi_app
    return new_run_wsgi_app(*args)

rawDescription: Python function replacing itself in the module namespace


code:
from zope.interface import Interface, implements
from zope.component import getUtility

class IOperation(Interface):
    def __call__(a, b):
        ''' performs operation on two operands '''

class Plus(object):
    implements(IOperation)
    def __call__(self, a, b):
        return a + b

class Minus(object):
    implements(IOperation)
    def __call__(self, a, b):
        return a - b

def eval(expr):
    a, op, b = expr.split()
    return getUtility(IOperation, op)(float(a), float(b))

rawDescription: How to make zope load my ZCML?

description: Make zope load my ZCML


code: parent = models.ForeignKey('self', blank=True, null=True, related_name="children")

rawDescription: Represent a tree of objects in Django template


code: selectors = (tempstring in dv for av, dv in izip(a, data) if len(av) > 1)

rawDescription: making python itertools work on multiple conditions

description: Making python itertools work on multiple conditions


code:
import geoalchemy2.functions as func
import json
from app import db

def point_geom_to_xy(pt):
    # extract x and y coordinates from a point geometry
    geom_json = json.loads(db.session.scalar(func.ST_AsGeoJSON(pt.geom)))
    return geom_json['coordinates']

rawDescription: Flask with GeoAlchemy sample code

description: Flask with GeoAlchemy sample code


code:
# insert contents of "/test1.txt" into "/test2.txt" at line 20
with open("/test2.txt", "rw+") as f2:
    for x in range(20):
        f2.readline()   # skip past early lines
    pos = f2.tell() # remember insertion position
    f2_remainder = f2.read()    # cache the rest of f2
    f2.seek(pos)
    with open("/test1.txt", "r") as f1:
        f2.write(f1.read())
    f2.write(f2_remainder)

rawDescription: Inserting a file's text into another file at a specific line


code: doc <- xmlParse( system("efetch -db=gene -id=4131 -format xml", intern=TRUE) )

rawDescription: Return values from a Python Entrez dictionary of dictionaries


code:
"""
This docstring shows up when someone does `help(mymodule)`.
"""
from submodule import my_function

rawDescription: choosing between a class or function in edge programming case

description: Choosing between a class or function in edge programming case


code:
from operator import itemgetter

for k, v in sorted(frequency.items(), key=itemgetter(1), reverse=True):
    print(k, v)

rawDescription: python word counter w/ sorted frequency

description: Python word counter w/ sorted frequency


code:
def update(self, **kwargs):
    self.__dict__.update((k, kwargs[k]) for k in kwargs
                          if self.__dict__.get(k, False) is None)

rawDescription: More Pythonic way of adding attributes to class?


code:
with open('highscores.txt', 'rb') as f:
    reader = csv.DictReader(f, fieldnames=('time', 'moves', 'penalties', 'score'))
    def convert_row(row):
        return {k: float(v) if k == 'time' else int(v) for k, v in row.items()}
    scores = [convert_row(row) for row in reader]
    top10 = heapq.nlargest(10, scores, key=operator.itemgetter('score'))
for record in top10:
    print('time: {time} | moves: {moves} | penalties: {penalties} | score: {score}'
          .format(**record))

rawDescription: How to display top 10 highscores from a comma separated value (.txt) file in Python (Pygame)

description: Display top 10 highscores from a comma separated value (.txt) file in Python (Pygame)


code:
def autolabel(rects):
# attach some text labels
    for ii,rect in enumerate(rects):
        height = rect.get_height()
        plt.text(rect.get_x()+rect.get_width()/2., 1.02*height, '%s'% (name[ii]),
                ha='center', va='bottom')
autolabel(rects1)

rawDescription: How can I display text over columns in a bar chart in matplotlib?

description: Display text over columns in a bar chart in matplotlib


code:
sq = MathFunction("x**2")
sq
sq(7)

rawDescription: Represent a function by a mathematical function


code:
decimal.getcontext().prec = 100
print("{:.40f}".format(decimal.Decimal(value1) - decimal.Decimal(value2)))

rawDescription: Suppressing scientific notation when applying operators to very long decimal numbers using the standard library Decimal


code: [t(x) for x in sequence]

rawDescription: Update values in list of list of tuples

description: Update values in list of list of tuples


rawDescription: Transpose list to rows of data

description: Transpose list to rows of data


code: matches = Match.query(Match.matchday == matchday.key).fetch()

rawDescription: getting related objects in template

description: Getting related objects in template


rawDescription: Get folder name of the file in Python

description: Get folder name of the file in Python


code:
from werkzeug import BaseRequest, AcceptMixin

class Request(BaseRequest, AcceptMixin):
    pass

rawDescription: What is a mixin, and why are they useful?


code:
all_scores = []

for count in range(5):
    all_scores.append( int(display_score.readline()) )

print( all_scores )

rawDescription: Looping test scores in file input/output


code: alphanumeric_invert = lambda x: [(ord(c) * -1) for c in x]

rawDescription: looking for an inverted heap in python

description: Looking for an inverted heap in python


code:
import os
counter = 0
path = "c:\\test"
for file in os.listdir(path):
    if file.endswith(".txt"):
        if file.find("_ready") > 0:
            counter = counter + 1
            os.rename(path + "\\"+file, path + "\\"+file.replace("_ready", "_busy"))
if counter == 0:
    print("No file has been found")

rawDescription: Replace a substring of file name

description: Replace a substring of file name


code:
import collections
import string
c = collections.defaultdict(collections.Counter)
speaker = None

with open('/tmp/spam.txt') as f:
  for line in f:
    if not line.strip():
      # we're on an empty line, the last guy has finished blabbing
      speaker = None
      continue
    if line.count(' ') == 0 and line.strip().endswith(':'):
      # a new guy is talking now, you might want to refine this event
      speaker = line.strip()[:-1]
      continue
    c[speaker].update(x.strip(string.punctuation).lower() for x in line.split())

rawDescription: How to add words from a text file to a dictionary depending on the name?

description: Add words from a text file to a dictionary depending on the name


code:
screen.fill((0,0,0))
screen.blit(self.bg, self.bg_rect)
pygame.display.update()

rawDescription: Set constant translucency for background


rawDescription: Sklearn Multiclass Dataset Loading

description: Sklearn Multiclass Dataset Loading


code:
while x <= link_count:
    ...
    x += 1

rawDescription: Loop through links using Selenium Webdriver (Python)


code:
for elems in zip("ABCD", "EFGH", "IJKL"):
    print(''.join(elems))

rawDescription: python combine array item by item

description: Python combine array item by item


code:
class a:
  s = 'python'
  b = 'py'
  @property
  def c(self):
    return [x for x in self.s if x in self.b]

A = a()
A.c

rawDescription: Scope of class variable with list comprehension


code:
list_of_dicts =[{'genres': ['Thriller'], 'year': '2014'}, {'genres': ['Animation','Drama'], 'year': '2014'}]
[genre for d in list_of_dicts for genre in d['genres']]

rawDescription: Remove inner list in list of lists

description: Remove inner list in list of lists


code:
import pickle
import unittest

pickle_file = open("temp" + ".pickle", 'wb')
u = unittest.TestResult()
for k, v in vars(u).items():
    if isinstance(v, file): # if not picklable(v):
        setattr(u, k, None)
pickle.dump(u, pickle_file)

rawDescription: How to save unittest.TestResult

description: Save unittest.TestResult


code:
import math

def filter_points(points, origin, radius=1.0):
  x1, y1 = origin
  return [(x2,y2) for x2,y2 in points if math.sqrt((x1-x2)**2+(y1-y2)**2) <= radius]

p = [(0, 0), (1, 0), (0, 1), (1, 1), (0, -1), (-1, 1)]
print(filter_points(p, (0, 0), 1.0))

rawDescription: How do I calculate the Euclidean distance between a point and a list of points in Python?

description: Calculate the Euclidean distance between a point and a list of points in Python


code:
parser = argparse.ArgumentParser()

subparsers = parser.add_subparsers(dest='subparser')

def handle_read(args):
    print('Handling read')
    print(args)
read = subparsers.add_parser('read')
read.add_argument('path')
read.set_defaults(handler=handle_read)

def handle_write(args):
    print('Handling write')
    print(args)
write = subparsers.add_parser('write')
write.add_argument('path')
write.add_argument('value')
write.set_defaults(handler=handle_write)

args = parser.parse_args()
args.handler(args)

rawDescription: Python argparse - creating subcommands with no labels


code:
a.reshape(3,2)
# returns a new array

a.resize(3,2)
# returns None, operates on the same array
# (equivalent to modifying ndarray.shape here since no. of elements is unchanged)

a.shape = (6,)
# operates on the same array, uses property trick to hide detailed
# setter logic behind normal attribute access.
# note the parens are unnecessary here - equivalent is a.shape = 6,
# NOT equivalent to a = a.reshape(6,), which would change the id(a)

a.__setattr__('shape',(3,2))
# just an ugly way of doing a.shape = 3,2

rawDescription: Difference between setting an attribute and calling an in-place mutating method?


code: class InheritingClass(PID(pidv), Parent): pass

rawDescription: SQLAlchemy Class Decoration for __mapper_args__


code:
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _

class EventsApphook(CMSApp):
    name = _("Event")
    urls = ["App.apps.event.urls"]
apphook_pool.register(EventsApphook)

rawDescription: Get view pk from django-cms CMSAttachMenu


code: tee = Tee(sys.stdout, file)

rawDescription: How can I pythonically print and write the same string (two operations on one object)

description: Pythonically print and write the same string (two operations on one object)


code: [dict2.get(item) or dict1.get(item) for item in dict1.keys() | dict2]

rawDescription: Match lists and write result to new list


rawDescription: Product method in c#

description: Product method in c#


code:
total_seconds = 12354324354545
m,s = divmod(total_seconds,60)
h,m = divmod(m,60)
d,h = divmod(h,24)
print(d,h,m,s)

rawDescription: Python - Catch run time of the file in specific Format


code:
def invert(x):
    return "".join(chr(ord(c) ^ 255) for c in x)

rawDescription: How to efficiently serialize 64-bit floats so that the byte arrays preserve natural numeric order?

description: Efficiently serialize 64-bit floats so that the byte arrays preserve natural numeric order


code:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, create_engine
from sqlalchemy.orm import relationship, backref, sessionmaker

Base = declarative_base()

class A(Base):
    __tablename__ = 'a'

    id = Column(Integer, primary_key=True)
    name = Column(String(1000))

class B(Base):
    __tablename__ = 'b'

    id = Column(Integer, primary_key=True)
    name = Column(String(1000))

class C(Base):
    __tablename__ = 'c'

    id = Column(Integer, primary_key=True)
    b_id = Column(Integer, ForeignKey('b.id'))
    name = Column(String(1000))
    a_id = Column(Integer, ForeignKey('a.id'))

    b = relationship('B', backref=backref('cb'), foreign_keys=b_id)
    a = relationship('A', backref=backref('ca'), foreign_keys=a_id)

engine = create_engine('sqlite:////tmp/temp.db')

connect = engine.connect()
Base.metadata.create_all(bind=engine)

Session = sessionmaker(bind=engine)
sess = Session()

c_ent = C(name='c1')
a1 = A(name='a1')
b1 = B(name='b1')

a1.ca = [c_ent]
b1.cb = [c_ent]

list1 = [a1, b1]

for i in list1:
    sess.add(i)
sess.commit()

c2 = C(name='c2')
c2.a = a1
c2.b = b1
sess.add(c2)
sess.commit()

sess.close()

rawDescription: Adding related data to a MySQL database with sqlalchemy


code:
def modified(self, event):
    self.txt.see(END)  # tkinter.END if you use namespaces

rawDescription: How to make Text scroll down automatically whenever text overcomes the visual area?

description: Make Text scroll down automatically whenever text overcomes the visual area


code: id | userquestion__id | userquestion__user_id | userquestion__value | usweranswer__id | useranswer__user_id | useranswer__value

rawDescription: Django filter a reverse relationship of each item in a queryset


code: TRI_1 = dict(template)

rawDescription: Initializing multiple python dictionaries to the same keynames and values


code:
from django.conf import settings
user = ForeignKey(settings.AUTH_USER_MODEL)

rawDescription: ForeignKey to a Model field?

description: ForeignKey to a Model field


code:
import sys

from twisted.internet.task import react
from twisted.internet.endpoints import serverFromString
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Factory

from twisted.protocols.basic import LineReceiver

class HubConnection(LineReceiver, object):
    def __init__(self, hub):
        self.name = b'unknown'
        self.hub = hub

    def connectionMade(self):
        self.hub.append(self)

    def lineReceived(self, line):
        words = line.split(" ", 1)
        if words[0] == b'identify':
            self.name = words[1]
        else:
            for connection in self.hub:
                connection.sendLine("<{}> {}".format(
                    self.name, line
                ).encode("utf-8"))

    def connectionLost(self, reason):
        self.hub.remove(self)

def main(reactor, listen="tcp:4321"):
    hub = []
    endpoint = serverFromString(reactor, listen)
    endpoint.listen(Factory.forProtocol(lambda: HubConnection(hub)))
    return Deferred()

react(main, sys.argv[1:])

rawDescription: Using asyncore to create interactive sessions with client/server model


code:
# If node has one or more child
if len( children ) >= 1 :
    # Data structure for your results
    coords = []
    # Loop through all the children
    for child in children:
        # call to recursion function
        result = getCoords( child, searchNode )
        # Add your new results together
        coords.extend(result)
    # Give the next instance up the stack your results!
    return coords

rawDescription: Xml parsing with Python using recursion. Problem with return value


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

rawDescription: Automatically run %matplotlib inline in iPython Notebook


code:
database1|abcd1234
database2|zyxw0987

rawDescription: Python Fabric load config from separate file


code:
import Image, ImageDraw

def InitializeMoonData():
    ''''
    Return a 40x40 half-circle, tilted 45 degrees, as raw data
    Only call once, at program initialization
    '''
    im = Image.new("1", (40,40))
    draw = ImageDraw.Draw(im)

    # Draw a 40-diameter half-circle, tilted 45 degrees
    draw.chord((0,0,40,40),
               45,
               45+180,
               outline="white",
               fill="white")
    del draw

    # Fetch the image data:
    moon = list(im.getdata())

    # Pack it into a 2d matrix
    moon = [moon[i:i+40] for i in range(0, 1600, 40)]

    return moon

# Store a copy of the moon data somewhere useful
moon = InitializeMoonData()

def ApplyMoonStamp(matrix, x, y):
    '''
    Put a moon in the matrix image at location x,y
    Call whenever you need a moon
    '''
    # UNTESTED
    for i,row in enumerate(moon):
        for j,pixel in enumerate(row):
            if pixel != 0:
                # If moon pixel is not black,
                # set image pixel to white
                matrix[x+i][y+j] = 255

# In your code:

#  m = Matrix(1024,768)
#  m = # some kind of math to create the image #
#  ApplyMoonStamp(m, 128,128)  # Adds the moon to your image

rawDescription: Create a half circle in angle 45 in Python


code:
@tornado.gen.coroutine
def read_utf(self):
    length_data = yield self.stream.read_bytes(2)
    length = struct.unpack('>H', length_data)[0]
    data = yield self.stream.read_bytes(length)
    raise tornado.gen.Return(data)

rawDescription: Tornado's equivalent to native socket's recv() method


code: insample = kernel(sample) < iso

rawDescription: Different integration results using Monte Carlo vs scipy.integrate.nquad


code:
import pandas as pd
d1 = {'a': 1, 'b':2}
d2 = {'a': 3, 'b':5}

df = pd.DataFrame([d1, d2]).T
df.columns = ['d{}'.format(i) for i, col in enumerate(df, 1)]

rawDescription: Joining same-key dictionaries into a dataframe in pandas


code:
from django.utils import simplejson
from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter
def as_json(data):
    return mark_safe(simplejson.dumps(data))

rawDescription: passing unicode strings from django to javascript

description: Passing unicode strings from django to javascript


code: Result = {key: result.data(value) for key, value in paths.items()}

rawDescription: Python post-processing

description: Python post-processing


code: dct = defaultdict(lambda: float('-inf'))

rawDescription: Defaultdict with values defaulted to negative infinity


rawDescription: Calculating the gap between pairs of twin primes in python


code:
allfiles = sys.argv[1:]
print(allfiles)

rawDescription: Python get all files from a directory Error


code:
import numpy as np
from matplotlib.legend_handler import HandlerPatch
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

# Define square (rectangular) patches
# that can be used as legend keys
# (this code is based on the legend guide example)

class HandlerSquare(HandlerPatch):
    def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize, trans):
        center = xdescent + 0.5 * (width - height), ydescent
        p = mpatches.Rectangle(xy=center, width=height,
                               height=height, angle=0.0)
        self.update_prop(p, orig_handle, legend)
        p.set_transform(trans)
        return [p]

# this example is the matplotlib barchart example:

N = 5
menMeans = (20, 35, 30, 35, 27)

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, menMeans, width, color='r')

womenMeans = (25, 32, 34, 20, 25)
rects2 = ax.bar(ind+width, womenMeans, width, color='y')

# add some text for labels, title and axes ticks
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )

# append the new patches to the legend-call:

ax.legend( (rects1[0], rects2[0]), ('Men', 'Women'),
           handler_map={rects1[0]: HandlerSquare(), rects2[0]: HandlerSquare()})

plt.show()

rawDescription: matplotlib: make legend keys square

description: Matplotlib: make legend keys square


code:
res = g["comp"].value_counts().unstack(1)
res
res.columns = res.columns.map({"lal": "det1", "lel": "det2", "lil": "det3"}.get)
res

rawDescription: Turn dataframe into frequency list with two column variables in Python


code:
class A(object):
    spam = 'eggs'
a = A()
a.foo = 100
a.bar = 200
a.__dict__
A.__dict__

rawDescription: Get complete list of all possible Class Attributes


code:
def custom_hash(s):
  hsh = 0
  for c in s: hsh += ord(c)
  return hsh

rawDescription: What is the equivalent C/C++ loselose algorithm in python


code: sum(tuples, ())

rawDescription: pythonic way to explode a list of tuples

description: Pythonic way to explode a list of tuples


code:
raw = negative
raw = (raw << 39) | (mantissa >> 13)
raw = (raw << 8) | ((exponent + 129) & 0xFF)

rawDescription: Float to Real48

description: Float to Real48


code:
a = [0, 1, 2, 3, 4, 5, np.array([6, 9], dtype=np.int64), 7, 8, np.array([6, 9], dtype=np.int64)]
b = [np.atleast_1d(np.asarray(x,dtype=np.int64)) for x in a]

rawDescription: Convert list into array dtype=int64 in Python


code: from my_modules.class1 import Stuff

rawDescription: Python: how to import from all modules in dir?


code: data = data.reshape((-1, 21, 3)).transpose([1, 2, 0])

rawDescription: Python matplotlib animation randomly jumping to initial position


code:
dT = sparse_dummyvar(partitions)
dT.T.dot(dT)
dT.T.dot(dT).A

rawDescription: numpy equivalent of matlab dummyvar

description: Numpy equivalent of matlab dummyvar


code:
def find_test(test_list, search_term):
    for index in range(len(test_list)):
        if test_list[index][0] == search_term:
            return test_list[index][1:]

rawDescription: How to return elements of a list as variables?

description: Return elements of a list as variables


code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-

import paramiko

class SSHSession:

    def __init__(self, server_address, user='root', port=22):
        self.connected      = False
        self.server_address = server_address
        self.user           = user
        self.port           = port

    def connect(self):
        try:
            self.ssh_client = paramiko.SSHClient()
            self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh_client.connect(self.server_address, username=self.user)
            self.transport     = self.ssh_client.get_transport()
            self.agent_channel = self.transport.open_session()
            self.agent_handler = paramiko.agent.AgentRequestHandler(self.agent_channel)
            self.channel       = self.ssh_client.invoke_shell()
        except:
            self.connected = False
        else:
            self.connected = True
        return self.connected

    def exec_command(self, command, newline='\r'):
        if not self.connected:
            raise Exception('Not connected')
        else:
            timeout = 31536000 # 365 days in seconds
            self.channel.settimeout(timeout)
            line_buffer    = ''
            channel_buffer = ''
            end_string     = 'CLIENT_EXPECT_CMD_OK'
            print('[SEND   ] >>', command)
            self.channel.send(command + ' ; echo ' + end_string + newline)
            while True:
                channel_buffer = self.channel.recv(1).decode('UTF-8')
                if len(channel_buffer) == 0:
                    raise Exception('connection lost with server: ' +     self.server_address)
                    break
                channel_buffer  = channel_buffer.replace('\r', '')
                if channel_buffer != '\n':
                    line_buffer += channel_buffer
                else:
                    if line_buffer == end_string:
                        break
                    print('[RECEIVE] <<', line_buffer)
                    line_buffer   = ''

    def disconnect(self):
        self.ssh_client.close()

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

    def __exit__(self, _type, value, traceback):
        self.disconnect()

if __name__ == "__main__":
    server_address = 'firstserver'
    ssh_user       = 'root'
    with SSHSession(server_address) as ssh_session:
        ssh_session.exec_command('hostname')
        ssh_session.exec_command('ssh root@secondserver hostname')

rawDescription: DSA key forwarding using Paramiko?

description: DSA key forwarding using Paramiko


code:
with open(filename, 'rb+') as f:

    while True:
        line = f.readline()
        if not line: break
        if '=2' in line:
                f.seek(-len(line),1)
                f.write(line.split('=2')[0]+'=6')
                f.flush()

rawDescription: how to search values in a file and replace

description: Search values in a file and replace


code:
def addTableRow(self, newTable, **kwargs):
    getattr(self, newTable).add_row(kwargs.values())

rawDescription: Using Class method to add a Class variable


code:
m_ongoing = np.zeros((197,10))

for i in range(LOWER, UPPER + 1):
    fname = file_name+str(i)+".txt"
    cur_resfile = np.genfromtxt(fname, delimiter = ",", skiprows = 1)

    # add one to the places where cur_file > 1
    m_ongoing[cur_resfile > 1] += 1

rawDescription: Numpy change elements based on threshold and then do element by element addition


code:
a = scipy.sparse.rand(100,100,format='csc')
a[2:5, 6:8]

rawDescription: Scipy: Do sparse matrices support advanced indexing?


code:
Class_Scores = [['James', 1],['Frank', 2],['Mark', 3]]

with open('Class One Scores.csv','w') as file:
    # unpack name and score from each sublist
    for name, score in Class_Scores:
          # write each name and score plus a newline
          file.write("{},{}\n".format(name,score))

rawDescription: I want to write the 'Class_Scores' to a csv file in rows(Name on one side score on the other), how do I do that?


code:
True == 1
hash(True) == hash(1)
False == 0
hash(False) == hash(0)

rawDescription: Adding 1 to a set containing True does not work


code: df_melted = df_melted.sort("name")

rawDescription: Turn columns to rows in pandas

description: Turn columns to rows in pandas


code:
@property
def consumer_tags(self):
    """Property method that returns a list of currently active consumers

    :rtype: list

    """
    return self._consumers.keys()

rawDescription: In Pika or RabbitMQ, How do I check if any consumers are currently consuming?


code:
def remove_face(M, dim, front_side):
    if front_side:
        dim_slice = slice(1, None)
    else:
        dim_slice = slice(None, -1)
    index = tuple(dim_slice if i == dim else slice(None) for i in range(M.ndim))
    return M[index]

rawDescription: Selecting (n-1)D array from (n)D array in numpy


code: apples = [v for v in (i['Apples'] for i in fruitLoads) if v != 0]

rawDescription: Extracting a list while testing a condition on extracted entries


rawDescription: I need help splitting a list into equal parts


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

x, y = np.loadtxt('spectrum.dat').T

# Let's detrend by fitting a second-order polynomial in log space
# (Note that your data looks like a parabola in log-log space.)
logx, logy = np.log(x), np.log(y)
model = np.polyfit(logx, logy, 2)
trend = np.polyval(model, logx)

# Smooth with a guassian filter
smooth = gaussian_filter1d(logy - trend, 10)

# Add the trend back in and convert back to linear space
smooth = np.exp(smooth + trend)

fig, ax = plt.subplots()
ax.loglog(x, y, color='black')
ax.loglog(x, smooth, color='red')
plt.show()

rawDescription: Smooth a curve in python with no error at the boundaries?


code:
from sklearn.svm import LinearSVC
linear_svc_model = LinearSVC()
linear_svc_model.fit(X=features, y=targets)

rawDescription: Using prepared data for Sci-kit classification


code:
x = object()
x.__dict__
class MyObject(object):
    pass

x = MyObject()
x.__dict__

rawDescription: Creating inmutable types in Python using __new__()


code:
def f1(self):
    pass

rawDescription: What is the difference between a function, an unbound method and a bound method?


rawDescription: Pythonic way to copy a key/value from one dict to another


code:
def getprojectname(ID):
    return project+ID

rawDescription: How to change variables in Python

description: Change variables in Python


code:
"Two"
"two"
"2"
"tWo"

rawDescription: How do I make two=2 equivalent in python?

description: Make two=2 equivalent in python


rawDescription: How to use index to assign address and formula to arrays?

description: Use index to assign address and formula to arrays


code:
if set(list1).difference(set(list2)):
    # lists are different
    # different_items = set(list1).difference(set(list2))
    pass
else:
    # lists are the same
    pass

rawDescription: Pythonic Way to compare two unordered lists by attributes


code:
import otherfile

for i in xrange(1000):
    otherfile.main(arg1)

rawDescription: Python : Run a script within a loop?

description: Python : Run a script within a loop


code: map_and_discard_none(lambda x: x*2 if x else x, (1, 2, None))

rawDescription: `map`-like function preserving sequence-type


code:
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _

class SearchTerm(models.Model):
    query = models.CharField(
        verbose_name = _(u'Search Term'),
        max_length = 255,
        default = None
    )

class SearchQuery(models.Model):
    term = models.ForeignKey(
        SearchTerm
    )
    user = models.ForeignKey(
        User,
        blank = True,
        null = True,
    )
    when = models.DateTimeField(
        verbose_name = _(u'Date Searched'),
    )

rawDescription: Logging Django Haystack search keyword

description: Logging Django Haystack search keyword


code:
# now test which who is closest to the detail (if that's what you meant to do)
map(lambda detail: (detail, min(people, key=lambda x: abs(float(x[1]) - float(detail)))), details)
# explanation: returns a tuple: (detail, person with minimal distance from detail)

rawDescription: Check if a number is in a range of a list


code:
AlpinoCorpusReader
BNCCorpusReader
BracketParseCorpusReader
CMUDictCorpusReader
CategorizedCorpusReader
CategorizedPlaintextCorpusReader
CategorizedTaggedCorpusReader
ChunkedCorpusReader
ConllChunkCorpusReader
ConllCorpusReader
CorpusReader
DependencyCorpusReader
EuroparlCorpusReader
IEERCorpusReader
IPIPANCorpusReader
IndianCorpusReader
MacMorphoCorpusReader
NPSChatCorpusReader
NombankCorpusReader
PPAttachmentCorpusReader
Pl196xCorpusReader
PlaintextCorpusReader
PortugueseCategorizedPlaintextCorpusReader
PropbankCorpusReader
RTECorpusReader
SensevalCorpusReader
SinicaTreebankCorpusReader
StringCategoryCorpusReader
SwadeshCorpusReader
SwitchboardCorpusReader
SyntaxCorpusReader
TaggedCorpusReader
TimitCorpusReader
ToolboxCorpusReader
VerbnetCorpusReader
WordListCorpusReader
WordNetCorpusReader
WordNetICCorpusReader
XMLCorpusReader
YCOECorpusReader

rawDescription: How to extract words from sample corpus that comes with NLTK?

description: Extract words from sample corpus that comes with NLTK


code:
m = MultipartEncoder(fields=your_fields)
r = requests.post('https://httpbin.org/post', data=m, headers={'Content-Type': m.content_type})
print(r.json()['form'])

rawDescription: Uploading an image from python client to a flask server


code:
#imports
import numpy as np
import statsmodels.api as sm

#generate the input matrix
X=[foo,bar,spam]
#turn it into a numpy array
X = np.array(X).T
#add a constant column
X=sm.add_constant(X)

rawDescription: Linear Regression with 3 input vectors and 4 output vectors?


code:
from toolz.itertoolz import sliding_window, concat

def sliding2(rdd, n):
    assert n > 1

    def get_last_el(i, iter):
        """Return last n - 1 elements from the partition"""
        return  [(i, [x for x in iter][(-n + 1):])]

    def slide(i, iter):
        """Prepend previous items and return sliding window"""
        return sliding_window(n, concat([last_items.value[i - 1], iter]))

    def clean_last_items(last_items):
        """Adjust for empty or to small partitions"""
        clean = {-1: [None] * (n - 1)}
        for i in range(rdd.getNumPartitions()):
            clean[i] = (clean[i - 1] + list(last_items[i]))[(-n + 1):]
        return {k: tuple(v) for k, v in clean.items()}

    last_items = sc.broadcast(clean_last_items(
        rdd.mapPartitionsWithIndex(get_last_el).collectAsMap()))

    return rdd.mapPartitionsWithIndex(slide)

rawDescription: How to transform data with sliding window over time series data in Pyspark

description: Transform data with sliding window over time series data in Pyspark


rawDescription: PYTHON: Searching two files for common lines and collecting their contents into set


code:
wrapper = ImportWrapper(__import__)
wrapper.mock_import('myModule', [])

rawDescription: Python, unit-testing and mocking imports


code:
urls.py
from myproject.views import index
urlpatterns = patterns('',
   (r'^$', index),
)

rawDescription: Where to put Python files to be redirected to by urls.py in Django?


code:
try:
    num = float(num_str)
except ValueError:
    try:
        num = locale.atof(num_str)
    except ValueError:
        try:
            num = float(Fraction(num_str))
        except ValueError:
            raise Exception("Cannot parse '%s'" % num_str)  # Or handle '42 billion' here
# 'num' has the numerical value of 'num_str', here.

rawDescription: Flexible numeric string parsing in Python


code:
l=[[100], [500], [300]]
result=[item for sublist in l for item in sublist]

rawDescription: Extract numbers from a string list - python


code:
tuple = 'one', 'two'

def function(string):
    global tuple
    if new_string not in tuple:
        tuple = (new_string,) + tuple

function('add this')

rawDescription: Python changing modifying via imported function


code:
if not self.e.get().isdigit():
     #get the length of the string in the widget, and subtract one, and delete everything up to the end
     self.e.delete(len(self.e.get)-1, tk.END)

rawDescription: Python Tkinter: Delete the Last Character of a String


code: [x for l in range(2, len(arr)) for x in itertools.combinations(arr, l)]

rawDescription: In Python how do I create variable length combinations or permutations?


code: cartesian.connect_to(toroidal, ... , ... , inverse=False)

rawDescription: Using sympy.diffgeom.CoordSystem to connect two coordinate systems


rawDescription: Regex to ensure group match doesn't end with a specific character


code:
v1 = v2 = "hello"
v1 += "world"
v1 is v2
v1
v2

rawDescription: mutable objects changed in-place means what?

description: Mutable objects changed in-place means what


code:
def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

rawDescription: Python while, continue loops

description: Python while, continue loops


code:
# helloworld.py
import webapp2

class MainPage(webapp2.RequestHandler):

    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write('Hello, World!')

application = webapp2.WSGIApplication([
    ('/', MainPage),
], debug=True)

rawDescription: App Engine - Python - Open local HTML file from script


code:
def f(objects):
    list_type = "string_x"
    other = "string_y"
    hold = []
    for x in objects:
        hold.append((list_type if isinstance(x[1], list) else other, x[1]))
    return hold

rawDescription: python optimize function without looping

description: Python optimize function without looping


code:
def char_range(c1, c2):
    """Generates the characters from `c1` to `c2`, inclusive."""
    for c in xrange(ord(c1), ord(c2)+1):
        yield chr(c)

matrix = [[c + str(i) for c in char_range('a', 'e')] for i in range(1, 5)]

rawDescription: Transpose and copy column data to each row


code: ă

rawDescription: when to use utf8 as a header in py files

description: When to use utf8 as a header in py files


code:
import os
import signal
import threading
from pipes import quote

class MPlayer(object):

    def __init__(self):
        self.process = Process(['mplayer',
            '-slave', '-idle',
            '-really-quiet', '-msglevel', 'global=6:cplayer=4', '-msgmodule',
            '-input', 'nodefault-bindings',
            '-cache', '1024',
        ], bufsize=1)
        self.write_lock = threading.Lock()

    # (...)

    def load(self, path):

        with self.write_lock:
            self.p.write('loadfile {}\n'.format(quote(path)))

        def wait_for_finish(process):
            # HERE: poll process for track ending with process.read()
            os.kill(os.getpid(), signal.SIGUSR1)

        t = threading.Thread(target=wait_for_finish, args=(self.process,))
        t.daemon = True
        t.start()

rawDescription: Python parallelization of tasks (event loop?)


code:
def paired_sum(a):
    return [sum(a[i:i+2]) for i in xrange(0,len(a),2)]

[paired_sum(sublist) for sublist in a]
map(paired_sum, a)

rawDescription: How to add paired values in sub-lists separately?

description: Add paired values in sub-lists separately


code:
def _split_lines(self, text, width):
    text = self._whitespace_matcher.sub(' ', text).strip()
    return _textwrap.wrap(text, 40)

rawDescription: Python argparse.RawTextHelpFormatter with line wrap


code:
def create_dictionary():
    with open("textToEnglish2014.csv", newline="") as fo:  # note the newline parameter!
        reader = csv.reader(fo)
        return dict(reader)

rawDescription: Why is my if else statement being ignored


code:
import pickle

def load_or_make(filename):
    def decorator(func):
        def wrapped(*args, **kwargs):
            # Make a key for the arguments. Try to make kwargs hashable
            # by using the tuple returned from items() instead of the dict
            # itself.
            key = (args, kwargs.items())
            try:
                hash(key)
            except TypeError:
                # Don't try to use cache if there's an
                # unhashable argument.
                return func(*args, **kwargs)
            try:
                with open(filename) as f:
                    cache = pickle.load(f)
            except Exception:
                cache = {}
            if key in cache:
                return cache[key]
            else:
                value = func(*args, **kwargs)
                cache[key] = value
                with open(filename, "w") as f:
                    pickle.dump(cache, f)
                return value
        return wrapped
    return decorator

rawDescription: Use decorators to retrieve jsondata if file exists, otherwise run method and then store output as json?


code:
c = Counter(**{'value1': 10, 'value2': 5})
c.update({'value1': 7, 'value2': 3})
c

rawDescription: Group by and aggregate the values of a list of dictionaries in Python


code:
'''MIDODRINE HCL 2.5 MG   1 TAB(S) TWICE PER DAY ORAL
REGULAR INSULIN SLIDING SCALE 150-200 4U 201-250 6U DAILY SUBCUTANEOUS
FLUTICASONE PROPIONATE 50 MCG/DOSE ML DAILY NASAL
B COMPLEX 1 TAB(S) DAILY ORAL
VIT B 12 1000U 1 CAP(S) DAILY ORAL
MAGNESIUM 250 MG  1 TAB(S) DAILY ORAL
REGULAR INSULIN SLIDING SCALE 150-200 4U 201-250 6U DAILY SUBCUTANEOUS
FOLIC ACID 800 MCG 1 TAB(S) DAILY ORAL
VIT B 12 1000U 1 CAP(S) DAILY ORAL
VIT-D3 1000U 1 CAP(S) DAILY ORAL
LANTUS 100 UNIT/ML 40U TWICE PER DAY SUBCUTANEOUS
LASIX 20 MG  1 TAB(S) DAILY ORAL
CENTRUM SILVER 1  TAB(S) DAILY ORAL
OMEPRAZOLE 20 MG  1 CAP(S) TWICE PER DAY ORAL
LANTUS 100 UNIT/ML 40U TWICE PER DAY SUBCUTANEOUS
B COMPLEX 1 TAB(S) DAILY ORAL
SENOKOT 8.6 MG  3 TABS TWICE PER DAY ORAL
TRIANCINILONE ACETONIDE 0.1% AS NEEDED FOR MOUTH SORE TOPICAL'''

rawDescription: removing duplicates in python and selenium

description: Removing duplicates in python and selenium


code:
import pandas as pd
import numpy as np

d = {'year' : [2000, 2000, 2000, 2000, 2001, 2001, 2001],
 'home': ['A', 'B', 'B', 'A', 'B', 'A', 'A'],
 'away': ['B', 'A', 'A', 'B', 'A', 'B', 'B'],
 'aw': [1, 0, 0, 0, 1, 0, np.nan],
 'hw': [0, 1, 0, 1, 0, 1, np.nan]}

df = pd.DataFrame(d, columns=['home', 'away', 'hw', 'aw', 'year'])
df.index = range(1, len(df) + 1)
df.index.name = 'game'

df = df.set_index(['hw', 'aw', 'year'], append=True).stack().reset_index().rename(columns={'level_4': 'role', 0: 'team'}).loc[:,
 ['game', 'team', 'role', 'hw', 'aw', 'year']]

def wins(row):
    if row['role'] == 'home':
        return row['hw']
    else:
        return row['aw']
df['wins'] = df.apply(wins, axis=1)

df['expanding_mean'] = df.groupby(['team', 'year'])['wins'].apply(lambda x: pd.expanding_mean(x).shift())

rawDescription: Groupby Pandas levels

description: Groupby Pandas levels


code:
MICROSECOND=1
MILLISECOND=MICROSECOND*1000
SECOND=MS*1000
MINUTE=SECOND*60
HOUR=MINUTE*60
DAY=HOUR*24
WEEK=DAY*7

rawDescription: Converting time efficiently in Python

description: Converting time efficiently in Python


code:
for commit, lines in repo.blame('HEAD', filepath):
    print("%s changed these lines: %s" % (commit, lines))

rawDescription: How to use git blame in GitPython?

description: Use git blame in GitPython


code:
console_factory.py
from multiprocessing.connection import Listener
from subprocess import Popen, CREATE_NEW_CONSOLE

address = '\\\\.\pipe\\new_console'
listener = Listener(address)

def new_console():
    Popen("python new_console.py", creationflags=CREATE_NEW_CONSOLE)
    return listener.accept()

c1 = new_console()
c1.send("console 1 ready")
c2 = new_console()
c2.send("console 2 ready")

rawDescription: Create new console for the same process

description: Create new console for the same process


code:
x['item'] = x.groupby(['site_num']).cumcount()
x.pivot(columns='site_num', index='item')

rawDescription: Reshaping pandas dataframe, converting values of an existing column into new lower level columns with index ignored


code:
zip(ranked, array)
sorted(zip(ranked, array))
sorted(zip(ranked, array1))

rawDescription: Ranking data in python without numpy

description: Ranking data in python without numpy


rawDescription: Capping linear regression prediction values using scikit


code: data.get(num, data[min(data.keys(), key=lambda k: abs(k-num))])

rawDescription: Python: find closest key in a dictionary from the given input key


code: exec(compile(open(filename, "rb").read(), "proga.py", 'exec'))

rawDescription: Python: How do you repeatedly call programs from a base program?


rawDescription: Python equivalent of mysql_real_escape_string, for getting strings safely into MySQL?


code:
try:
    reversed
except NameError:
    from django.utils.itercompat import reversed     # Python 2.3 fallback

rawDescription: Supporting Multiple Python Versions In Your Code?


code: request.session['foo'] = ['bar']

rawDescription: Django Session Variable resetting

description: Django Session Variable resetting


code:
def test():
    with patch.multiple('module.ClassName', foo=DEFAULT, bar=DEFAULT) as mocks:
        mock_foo, mock_bar = mocks["foo"], mocks["bar"]
        mock_foo.return_value = 'foo'
        mock_bar.return_value = 'bar'

rawDescription: Python Mock patch.multiple argument names


code:
functions = [somefunction1, somefunction2, somefunction3]

i = 0
var = True

while var and i < len(functions):
    var, msg = func()
    i += 1

rawDescription: Exiting block of code when variable changes in python


rawDescription: SQLAlchemy relationships, when to use which relationship?


code:
prefixes = {('map', 'inventory'): ('check',),
            ('north', 'south', 'east', 'west'): ('go', 'walk')}
commands = [word for word in move_input if word not in noise]
if len(commands) == 1:
   command = commands[0]
else:
    assert len(commands) == 2 # or decide what to do otherwise
    for com, pref in prefixes.items():
        if commands[0] in pref and commands[1] in com:
           command = commands[1]
           break
    else:
        print('Invalid command')

rawDescription: Checking a partial match in input to a list of valid arguments with varying prefixes