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

def fmt(x, y):
    return 'x: {x:0.2f}\ny: {y:0.2f}'.format(x=x, y=y)

class FollowDotCursor(object):
    """Display the x,y location of the nearest data point."""
    def __init__(self, ax, x, y, tolerance=5, formatter=fmt, offsets=(-20, 20)):
        try:
            x = np.asarray(x, dtype='float')
        except (TypeError, ValueError):
            x = np.asarray(mdates.date2num(x), dtype='float')
        y = np.asarray(y, dtype='float')
        self._points = np.column_stack((x, y))
        self.offsets = offsets
        self.scale = x.ptp()
        self.scale = y.ptp() / self.scale if self.scale else 1
        self.tree = spatial.cKDTree(self.scaled(self._points))
        self.formatter = formatter
        self.tolerance = tolerance
        self.ax = ax
        self.fig = ax.figure
        self.ax.xaxis.set_label_position('top')
        self.dot = ax.scatter(
            [x.min()], [y.min()], s=130, color='green', alpha=0.7)
        self.annotation = self.setup_annotation()
        plt.connect('motion_notify_event', self)

    def scaled(self, points):
        points = np.asarray(points)
        return points * (self.scale, 1)

    def __call__(self, event):
        ax = self.ax
        # event.inaxes is always the current axis. If you use twinx, ax could be
        # a different axis.
        if event.inaxes == ax:
            x, y = event.xdata, event.ydata
        elif event.inaxes is None:
            return
        else:
            inv = ax.transData.inverted()
            x, y = inv.transform([(event.x, event.y)]).ravel()
        annotation = self.annotation
        x, y = self.snap(x, y)
        annotation.xy = x, y
        annotation.set_text(self.formatter(x, y))
        self.dot.set_offsets((x, y))
        bbox = ax.viewLim
        event.canvas.draw()

    def setup_annotation(self):
        """Draw and hide the annotation box."""
        annotation = self.ax.annotate(
            '', xy=(0, 0), ha = 'right',
            xytext = self.offsets, textcoords = 'offset points', va = 'bottom',
            bbox = dict(
                boxstyle='round,pad=0.5', fc='yellow', alpha=0.75),
            arrowprops = dict(
                arrowstyle='->', connectionstyle='arc3,rad=0'))
        return annotation

    def snap(self, x, y):
        """Return the value in self.tree closest to x, y."""
        dist, idx = self.tree.query(self.scaled((x, y)), k=1, p=1)
        try:
            return self._points[idx]
        except IndexError:
            # IndexError: index out of bounds
            return self._points[0]

x=[1,2,3,4,5]
y=[6,7,8,9,10]

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x, y)
cursor = FollowDotCursor(ax, x, y)
plt.show()

rawDescription: Get data from plot with matplotlib

description: Get data from plot with matplotlib


code:
pdf_re = ".+resume\w*\.pdf"
doc_re = ".+resume\w*\.doc"

rawDescription: Finding and moving PDF and DOC files to different directories using python


rawDescription: can't convert string to integer-python

description: Can't convert string to integer-python


code:
import matplotlib.pyplot as plt
import numpy as np
sin = np.sin
cos = np.cos

# http://stackoverflow.com/questions/6370742/#6372413
xmax = 4.0
xmin = -xmax
D = 20
ymax = 4.0
ymin = -ymax
x = np.linspace(xmin, xmax, D)
y = np.linspace(ymin, ymax, D)
X, Y = np.meshgrid(x, y)
# plots the vector field for Y'=Y**3-3*Y-X
deg = np.arctan(Y ** 3 - 3 * Y - X)
widths = np.linspace(0, 2, X.size)
plt.quiver(X, Y, cos(deg), sin(deg), linewidths=widths)
plt.show()

rawDescription: Change size of arrows using matplotlib quiver


code:
#Okay first if you want the table to have HEADERS above each column you should save the heading names in a list like so...
listofheaders=['header1','header2','header3']

#for each row in the table save the data included in the row in a list of lists something like this:
listofrows=[['a','b','c'],['a','b','c'],['a','b','c']]

#now create a string with the following:
htmlstuff='<!DOCTYPE html>\n\n\n\n\n\n\n
\n
\n  '

#now you would add the COLUMN HEADERS to the list...
for header in listofheaders:
    htmlstuff=htmlstuff+''+str(header)+'	\n'

#then you can populate the table row by row...
for row in listofrows:
    htmlstuff+='
\n'
    for item in row:
        htmlstuff=htmlstuff+'    '+str(item)+'	\n'
    htmlstuff+='
\n'

#finish off the html coding...
htmlstuff+='
\n\n\n'

#now create the html page and write the data...
f=open('webpage.html','w')
f.write(htmlstuff)
f.close()

rawDescription: Html file writing from a for loop's output


code:
a = b.copy()
c = hybrid_array(a,args)

rawDescription: apply two functions to the two halves of a numpy array

description: Apply two functions to the two halves of a numpy array


code:
class Choice(models.Model):
    name = models.ForeignKey(Person)
    rating = models.DateTimeField(blank=True, null=True)

    @property
    def photo_other(self):
        return self.name.photo

class Person(models.Model):
    name = models.CharField(max_length=250)
    photo = models.ImageField(upload_to="photos")
    pub_date = models.DateTimeField()

rawDescription: Django multiple Foreign Key - Display related field in details admin page for add/edit


code:
x = testData[0].sort_values()
x.index = range(len(x))
plt.plot(x)

rawDescription: Python sort_values plot is inverted

description: Python sort_values plot is inverted


rawDescription: Get the string within brackets in Python


code:
import urllib.request, json

response = urllib.request.urlopen('http://vimeo.com/api/v2/video/31161781.json')
content = response.read()
data = json.loads(content.decode('utf8'))

rawDescription: How to retrieve and display a Vimeo video's JSON data in python 3.x?

description: Retrieve and display a Vimeo video's JSON data in python 3.x


rawDescription: - vs -= operators with numpy

description: - vs -= operators with numpy


code:
import numpy as np

i, j = np.indices([states, states])
bool_index = (i != j) & (z != 0) & (m < 0.0)
z[bool_index] = 0

rawDescription: How can I optimize this double-loop over an array using numpy?

description: Optimize this double-loop over an array using numpy


code:
list_of_unused_words = [x for x in words]

if len(list_of_unused_words) == 1:
    list_of_unused_words = list_of_unused_words[0]

print(list_of_unused_words)

rawDescription: Python - Using Random with No Repeated Words and Selecting a Spare Word from a List


rawDescription: Documentation for understanfing

description: Documentation for understanfing


code:
def runs_of_ones(bits):
  for bit, group in itertools.groupby(bits):
    if bit: yield sum(group)

rawDescription: find length of sequences of identical values in a numpy array

description: Find length of sequences of identical values in a numpy array


code:
from collections import namedtuple
NameStory = namedtuple('NameStory', ['name', 'story'])
name_story1 = NameStory(name=dict['data']['name'], story=dict['data']['story'] + dict['data']['story2'])
name_story2 = NameStory(name=dict2['data']['name'], story=dict2['data']['name'])

rawDescription: Layer between data extraction and storage


rawDescription: Possible to modify every first tuple element in a list of tuples?


code:
(r'^profile/$', login_required(profile,'student')),
(r'^editprofile/$', login_required(editprofile,'student')),

rawDescription: Django - view, url weirdness

description: Django - view, url weirdness


code:
DATABASES = {'default':{}}
#Database Config is pulled from the config file
DATABASES['default']['USER'] = config.get('database', 'DATABASE_USER')
DATABASES['default']['PASSWORD'] = config.get('database', 'DATABASE_PASSWORD')
DATABASES['default']['HOST'] = config.get('database', 'DATABASE_HOST')
DATABASES['default']['PORT'] = config.get('database', 'DATABASE_PORT')
DATABASES['default']['ENGINE'] = config.get('database', 'DATABASE_ENGINE')
DATABASES['default']['NAME'] = config.get('database', 'DATABASE_NAME')

rawDescription: Running syncdb in django after converting to ConfigParser


rawDescription: find optional middle of string surrounded by lazy, regex

description: Find optional middle of string surrounded by lazy, regex


code:
parser = argparse.ArgumentParser()
parser.add_argument('--resize', nargs='?', type=int, const=True)
parser.parse_args('--resize 123'.split())

rawDescription: Is there a way to create argument in python's argparse that returns true in case no values given


code: users = p.project_tasks.all()  # Because of `related_name` in Task.project

rawDescription: have multiple users as one model field in many to one format django models

description: Have multiple users as one model field in many to one format django models


rawDescription: Assemble strings for particular ID by order of index. Python


rawDescription: python: read json and loop dictionary

description: Python: read json and loop dictionary


code:
for _, category in itertools.groupby(dictList, key=lambda item:item['type']):
    processingMethod(category)

rawDescription: How to categorize list of dictionaries based on the value of a key in python efficiently?

description: Categorize list of dictionaries based on the value of a key in python efficiently


code:
tree.tag_configure('oddrow', background='orange')
tree.tag_configure('evenrow', background='purple')

rawDescription: ttk treeview: alternate row colors

description: Ttk treeview: alternate row colors


rawDescription: match element of a list based on another list in python where elements of one list is the substring of elements of another list

description: Match element of a list based on another list in python where elements of one list is the substring of elements of another list


code:
column1 = [
    ('H', 'Hydrogen'),
    ('Li', 'other'),
    ('Na', 'other'),
    ('K', 'other'),
    ('Rb', 'other'),
    ('Cs', 'other'),
    ('Fr', 'other')
]

# create all buttons with a loop
r = 1
c = 0
for b in column1:
    tk.Button(self,text=b[0],width=5,height=2, bg="grey",command=lambda text=b[1]:self.info(text)).grid(row=r,column=c)

rawDescription: Python: Changing label depending which button is pressed


code:
arr.tolist()
G = {item:0 for item in arr.tolist()}
G
(1490775.0, 12037425.0) in G

rawDescription: Dictionary not recognizing floating point keys


code: matches = [m.groups() for m in (re.match('(\w+?)(\d+)', f) for f in fnames) if m]

rawDescription: Is there a `let` or `as` keyword for Python generators?


code:
@memoized
def change(a, kinds=(50, 20, 10, 5, 1)):
    if a == 0:
        return 1
    if a < 0 or len(kinds) == 0:
        return 0

    return change(a - kinds[0], kinds) + change(a, kinds[1:])

print(change(10))  # 4

rawDescription: Memoizing Coin Change

description: Memoizing Coin Change


code:
import numpy as np

def gendata():
    # You, of course, have a different gendata...
    for i in xrange(N):
        yield (np.random.random(), str(i))

N = 100

arr = np.fromiter(gendata(), dtype='<f8,|S20')

rawDescription: How do I fill two (or more) numpy arrays from a single iterable of tuples?

description: Fill two (or more) numpy arrays from a single iterable of tuples


code:
from flask import url_for, redirect, render_template
from flask_wtf import Form
from flask_wtf.file import FileField
from werkzeug import secure_filename

class UploadForm(Form):
    file = FileField()

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    form = UploadForm()

    if form.validate_on_submit():
        filename = secure_filename(form.file.data.filename)
        form.file.data.save('uploads/' + filename)
        return redirect(url_for('upload'))

    return render_template('upload.html', form=form)

rawDescription: Get an uploaded file from a WTForms field


code:
latitude = "20-55-70.010N"
N = 'N' in latitude
d, m, s = map(float, latitude[:-1].split('-'))
latitude = (d + m / 60. + s / 3600.) * (1 if N else -1)
longitude = "32-11-50.000W"
W = 'W' in longitude
d, m, s = map(float, longitude[:-1].split('-'))
longitude = (d + m / 60. + s / 3600.) * (-1 if W else 1)

rawDescription: How to convert latitude longitude to decimal in python?

description: Convert latitude longitude to decimal in python


code: people.groupby(lambda x: 'Group1' if people['b'].loc[x] > people['a'].loc[x] else 'Group2').sum()

rawDescription: Groupby with User Defined Functions Pandas


rawDescription: input a list of 2D coordinates in python from user

description: Input a list of 2D coordinates in python from user


code: df.merge(df1, left_index=True, right_index=True, how='left')

rawDescription: How can I merge one dataframe into another, inserting rows that do not exist?

description: Merge one dataframe into another, inserting rows that do not exist


code:
GLOBAL          = 'c'   # push self.find_class(modname, name); 2 string args
INST            = 'i'   # build & push class instance

rawDescription: How to control what gets imported when you unpickle python object?

description: Control what gets imported when you unpickle python object


code:
Code
import numpy as np

class CustomIndexTable:
    def __init__(self, rows, columns, elements):
        self.rows = rows
        self.columns = columns
        self.data = np.array(elements, dtype=object)
        self.data = self.data.reshape((len(rows), len(columns)))

    def __getitem__(self, index):
        x, y = index[:2], index[2:]
        return self.data[self.rows.index(x),self.columns.index(y)]

    def __setitem__(self, index, element):
        x, y = index[:2], index[2:]
        self.data[self.rows.index(x),self.columns.index(y)] = element

    def _where(self, element):
        x, y = np.where(self.data == element)
        return self.rows[x] + self.columns[y]

    def transpose(self):
        self.rows, self.columns = self.columns, self.rows
        self.data = self.data.T

    def where(self, sequence):
        elements = []
        start = 0
        for end in xrange(1, len(sequence)+1):
            if sequence[start:end] in self.data:
                elements.append(sequence[start:end])
                start = end
        return ''.join(self._where(e) for e in elements)

def input_matrix_data(text):
    return raw_input(text).split()

col_indices = input_matrix_data("Column indices: ")
row_indices = input_matrix_data("Row indices: ")
data = input_matrix_data("All data, sorted by row: ")

table = CustomIndexTable(row_indices, col_indices, data)

rawDescription: two dimensional array for encryption in python

description: Two dimensional array for encryption in python


code:
count_query = session.query(func.count('*')).filter(Baz.foo_id==Foo.id).filter(Baz.bar_id==Bar.id).correlate(Bar).correlate(Foo).as_scalar()
query = session.query(Foo.name, Bar.name, count_query)

rawDescription: Trying to do left outer joins to two related tables


code:
col.find_one()
col.update({'_id': 1}, {'$set': {'value.key2': 300}})
col.find_one()

rawDescription: pymongo, mongodb add a new key to an existing dictionary

description: Pymongo, mongodb add a new key to an existing dictionary


code:
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
load_more = wait.until(EC.visibility_of_element_located((By.LINK_TEXT, 'LOAD MORE')))

rawDescription: Selenium can't seem to find and click a button on website? - Python


code: new_im_vec = ravel(rollaxis(im, 2))

rawDescription: reordering of numpy arrays

description: Reordering of numpy arrays


code: print(next(key for key, value in data.items() if value == something))

rawDescription: how to get key of dictionary in python

description: Get key of dictionary in python


rawDescription: Convert a datetime.timedelta into ISO 8601 duration in Python?


rawDescription: Call to functions that prints, avoid new line


code:
def startProgress(title):
    global progress_x
    sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41)
    sys.stdout.flush()
    progress_x = 0

def progress(x):
    global progress_x
    x = int(x * 40 // 100)
    sys.stdout.write("#" * (x - progress_x))
    sys.stdout.flush()
    progress_x = x

def endProgress():
    sys.stdout.write("#" * (40 - progress_x) + "]\n")
    sys.stdout.flush()

rawDescription: Replace console output in python

description: Replace console output in python


rawDescription: Merge Dictionaries with different TimeStamp


code:
data = []
for line in ins:
    number_strings = line.split() # Split the line on runs of whitespace
    numbers = [int(n) for n in number_strings] # Convert to integers
    data.append(numbers) # Add the "row" to your list.
print(data) # [[1, 3, 4], [5, 5, 6]]

rawDescription: Python read file into 2d list

description: Python read file into 2d list


code:
split_loc = re.split(r' ?,? ?', location)
city = ' '.join(split_loc[:-1]) # Everything up to last element joined by space
state = split_loc[-1]

rawDescription: Separate city and state in string?

description: Separate city and state in string


code:
ImageDraw.floodfill(
    im, point_inside_digit, ImageColor.getrgb("black"),
    border=ImageColor.getrgb("black"))

rawDescription: How to fill the outline text by PIL to using tesseract?

description: Fill the outline text by PIL to using tesseract


code:
def foo(**kwargs):
    kwargs = dict((key, val) for key,val in izip(kwargs.iterkeys(), \
    map(django.utils.htmls.escape, kwargs.itervalues())))

    # OR if you use Python 3
    kwargs = {key:django.utils.htmls.escape(val) for key, val in kwargs.items()}

rawDescription: HTML-escaping replacement fields when using str.format() in Python


code:
with open('Block.csv') as infile, open('Block_sorted.csv', 'wb') as op:
    data = sorted(csv.DictReader(infile), key=lambda d: (d['Track_ID'], d['Kp_Begin']))

    # read the column names in the correct order.
    infile.seek(0)
    headers = infile.readline().split()

    wr = csv.DictWriter(op, headers, quoting=csv.QUOTE_NONE)
    wr.writeheader()
    wr.writerows(data)

    # don't need to close() files when using "with"

rawDescription: Sort in Python changing column order

description: Sort in Python changing column order


code:
cons = []
for i in range(4):
    cons.append({'type': 'ineq', 'fun': lambda x:  x[0] - 2 * x[1] + i})

rawDescription: Generating a 'sequence of dicts' for scipy.optimize.minimize


code:
class O1(object):
    def __getattr__(self, name):
        return "__getattr__ has the lowest priority to find {}".format(name)

class O2(O1):
    var = "Class variables and non-data descriptors are low priority"
    def method(self): # functions are non-data descriptors
        return self.var

class O3(O2):
    def __init__(self):
        self.var = "instance variables have medium priority"
        self.method = lambda: self.var # doesn't recieve self as arg

class O4(O3):
    @property # this decorator makes this instancevar into a data descriptor
    def var(self):
        return "Data descriptors (such as properties) are high priority"

    @var.setter # I'll let O3's constructor set a value in __dict__
    def var(self, value):
        self.__dict__["var"]  = value # but I know it will be ignored

class O5(O4):
    def __getattribute__(self, name):
        if name in ("magic", "method", "__dict__"): # for a few names
            return super(O5, self).__getattribute__(name) # use normal access

        return "__getattribute__ has the highest priority for {}".format(name)

rawDescription: Confused with getattribute and setattribute in python


code:
class DictAsMember(dict):
    def __getattr__(self, name):
        value = self[name]
        if isinstance(value, dict):
            value = DictAsMember(value)
        return value

my_dict = DictAsMember()
my_dict['property'] = {'sub_property': 1}

print(my_dict.property.sub_property) # 1 will be printed

rawDescription: When to use __getattr__

description: When to use __getattr__


code:
d={
    'global':
    {
        'www.test1.com': ['x', 'y'],
        'www.test2.com': ['x', 'y'],
        'www.test3.com': ['x'],
        'www.test4.com': ['x', 'y'],
        'www.test5.com': ['x']
    },
    'private':
    {
        'www.test6.com': ['m', 'n'],
        'www.test7.com': ['n'],
        'www.test8.com': ['m']
    }
}
new_d={key:dict(filter(lambda x:'n' in x[1], value.items())) for key, value in d.items() if dict(filter(lambda x:'n' in x[1], value.items()))}
new_d

rawDescription: Fetch only those part in dictionary of dictionary which contains particular string in value


code:
def permutations_with_replecement(elements,n):
    return permutations_helper(elements,[0]*n,n-1)#this is generator

def permutations_helper(elements,result_list,d):
    if d<0:
        yield tuple(result_list)
    else:
        for i in elements:
            result_list[d]=i
            all_permutations = permutations_helper(elements,result_list,d-1)#this is generator
            for g in all_permutations:
                yield g

rawDescription: permutations with unique values

description: Permutations with unique values


code:
pythons_psutil
print(*sorted(pythons_psutil[0].as_dict()), sep='\n')
pythons_psutil[0].memory_info()

rawDescription: How to detect if a process is running using Python on Win and MAC

description: Detect if a process is running using Python on Win and MAC


code: [pd.set_option(option, setting) for option, setting in [('max_rows', 1000), ('notebook_repr_html', False)]]

rawDescription: Pandas set_option - more than one option per line


code:
# 7x7 boolean mask with the "brush" (example: a _crude_ circle)
mask = array([[0, 0, 1, 1, 1, 0, 0],
              [0, 1, 1, 1, 1, 1, 0],
              [1, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 1, 1],
              [0, 1, 1, 1, 1, 1, 0],
              [0, 0, 1, 1, 1, 0, 0]], dtype=bool)

# random image
I = rand(100, 100)
# apply filter only on mask
# compute the gauss. filter only on the 7x7 subregion, not the whole image
I[40:47, 40:47][mask] = gaussian_filter(I[40:47, 40:47][mask], sigma=1)

rawDescription: "painting" one array onto another using python / numpy


code: Namespace(which='all')

rawDescription: argparse: identify which subparser was used

description: Argparse: identify which subparser was used


code:
import time
from flask import Flask, render_template_string
app = Flask(__name__)

@app.route('/')
@app.route('/<name>')
def hello(name='World'):
    time.sleep(1)
    return render_template_string('''

        Hello, {{ name }}!

''', name=name)

if __name__=="__main__":
    app.run(debug=True)

rawDescription: Python serving html async

description: Python serving html async


code: background = re.search(r'background:(.*?);', some_string).group(1)

rawDescription: Python Regular Expression- Selecting value based on surounding patterns


code:
def X509_get_notBefore(self):
    return self.X509[0].cert_info.validity.notBefore

rawDescription: Wrapper for libeay32.dll: how to import macro?


code:
import binascii

packed = binascii.unhexlify('01009f5a06379ae1cb13f7a6b62bca010dc703000000c300fefff9ff00000000')

rawDescription: Converting binary timestamp to string

description: Converting binary timestamp to string


code:
imax = 8;
jmax = 8;
kmax = 5;
x = zeros(imax,jmax,kmax);

rawDescription: How to auto-generate and assign variables corresponding to elements in a matrix?

description: Auto-generate and assign variables corresponding to elements in a matrix


rawDescription: Make a button's command cause the button's text to be inserted into an entry


code:
#convert column Concentration to float
data['Concentration'] = data['Concentration'].astype(float)
#strip first and last whitespaces
data['Name'] = data['Name'].str.strip()

#groupby and set rolling count from column Block
data["Replicate"] = data.groupby(["Block", "Name"])["Block"].transform(pd.rolling_count, window=3)

rawDescription: groupby issues of not recognizing numeric column pandas python

description: Groupby issues of not recognizing numeric column pandas python


code:
def twentyone(array, num=21):
    if num < 0:
        return
    if len(array) == 0:
        if num == 0:
            yield []
        return
    for solution in twentyone(array[1:], num):
        yield solution
    for solution in twentyone(array[1:], num - array[0]):
        yield [array[0]] + solution

rawDescription: Subset Sum with Backtracking on Python

description: Subset Sum with Backtracking on Python


code: {'corse': 'Definition of "corse" via generator', 'cielo': 209, 'mute': 16}

rawDescription: Python dictionary replace values

description: Python dictionary replace values


rawDescription: Grouping of element in a list given a list of intervals


code:
#Piecewise function defining 2nd deg, 1st degree and 3rd degree exponentials
def piecewise_linear(x, x0, x1, y0, y1, k1, k2, k3, k4, k5, k6):
    return np.piecewise(x, [x < x0, x>= x0, x> x1], [lambda x:k1*x + k2*x**2, lambda x:k3*x + y0, lambda x: k4*x + k5*x**2 + k6*x**3 + y1])

rawDescription: Plotting a piece-wise fit to non-linear data


code:
ansi_codes = re.compile('\033\[[0-9;]+m')
def strip_ansi(with_ansi):
    return ansi_codes.sub('', with_ansi)

rawDescription: How to get text from dialog box in unix using pexpect?

description: Get text from dialog box in unix using pexpect


code:
from inspect import getmembers, isfunction, signature

def override(f):
    """
    Mark method overrides.
    """
    f.__override__ = True
    return f

def _is_method_override(m):
    return isfunction(m) and getattr(m, '__override__', False)

def annotate_overrides(cls):
    """
    Copy annotations of overridden methods.
    """
    bases = cls.mro()[1:]
    for name, method in getmembers(cls, _is_method_override):
        for base in bases:
            if hasattr(base, name):
                break

        else:
            raise RuntimeError(
                    'method {!r} not found in bases of {!r}'.format(
                            name, cls))

        base_method = getattr(base, name)
        method.__annotations__ = base_method.__annotations__.copy()

    return cls

rawDescription: How to type annotate overrided methods in a subclass?

description: Type annotate overrided methods in a subclass


code:
from django.db.models import Count

Person.objects.annotate(count_book=Count('book')).filter(count_book__gt=0)

rawDescription: How do I select from a many-to-many intermediate model in django?

description: Select from a many-to-many intermediate model in django


rawDescription: Python - re - need help for regular expression


code:
frame['sum_order'] = frame['sum'].rank()
frame['sum_sq_order'] = frame['sum_sq'].rank()
frame['max_order'] = frame['max'].rank()

frame['mean_order'] = frame[['sum_order', 'sum_sq_order', 'max_order']].mean(axis=1)

rawDescription: Python Pandas add column with relative order numbers


code:
from tkinter import *

root = Tk()
t = Text(wrap=WORD)
t.pack()
root.mainloop()

rawDescription: Python 3 Tkinter: How to word-wrap text in Tkinter Text


code: a = r'this\is\a\path\to\file'

rawDescription: Get characters of a string (from right)

description: Get characters of a string (from right)


code:
def depthGenerator(seq, depth):
    if depth==0:
        for x in seq:
            yield x[:2] #strip subsequences
        return

    for x in seq:
        if len(x)==3:   #has subsequence?
            for y in depthGenerator(x[2], depth-1):
                yield y

rawDescription: Python: Get items at depth? (set library?)


rawDescription: How do I generate a TimedeltaIndex from a column of timestamps where the each TimeDelta is generated with reference to the previous timestamp

description: Generate a TimedeltaIndex from a column of timestamps where the each TimeDelta is generated with reference to the previous timestamp


code:
import example
spam = example.Spam()
spam.doSomething("test")
spam.doSomethingWide(u"test")

rawDescription: Using Unicode in Boost Python with a C++ function that takes std::wstring


code:
df.index > ind
df[mask].sum()
pd.concat([df[~mask].T, df[mask].sum()], axis=1).T

rawDescription: summing up certain rows in a panda dataframe

description: Summing up certain rows in a panda dataframe


code:
def _yes(event):
    if event.button == 3:
        print("yolo")

rawDescription: Matplotlib Python: How to add panel button


code: mydict = {'fieldname': firstvalue, 'secondfield': secondvalue}

rawDescription: When and why should I use a namedtuple instead of a dictionary?


code:
print(data.dtype, data.min(), data.max(), data.shape)
print(np.unique(data))
print(len(np.unique(data)))

rawDescription: Should I bother for array type in Python?


rawDescription: Python3 Classes- Can you change it into a string?


code:
# send to emailname@example.com
emailname: "|/path/to/script.py"

rawDescription: Python : Postfix stdin

description: Python : Postfix stdin


rawDescription: Mean in group of columns

description: Mean in group of columns


rawDescription: Long argument lists and performance

description: Long argument lists and performance


code:
import numpy as np
Range('C3').value = (Range('A3:A9', asarray=True).value +
                     Range('B3:B9', asarray=True).value)[:,np.newaxis]

rawDescription: Xlwings - adding columns

description: Xlwings - adding columns


rawDescription: Whats the easiest way to pad an alphabet index both sides with zeroes?


rawDescription: Python class decorator converting element access to attribute access


code: result = [attributes[key] for key in sorted(attributes.keys(), reverse=True)]

rawDescription: Building a list of dictionary values, sorted by key


rawDescription: regular express with (?:) for grouping and $ at the end

description: Regular express with (?:) for grouping and $ at the end


code:
#Call get_column_number
column_num = get_column_number()

rawDescription: How to use first function's return value in second function?

description: Use first function's return value in second function


code:
multiplication = lambda x,y: x*y

def dot_product(*args):
    return sum([reduce(multiplication, arg) for arg in zip(*args)])

rawDescription: How to Enter an unknown number of variables into a function?


code:
for x in dic:
    for y in dic:
        score_temp = len(x[2] & y[2])
        score_final = float(score_temp) / (x[1] + y[1])
        dice_cursor.execute('insert into dices values(?,?,?)',
                            (x[0], y[0], score_final))

rawDescription: How to reduce the number of for-loops for shortening running time in Python programming?

description: Reduce the number of for-loops for shortening running time in Python programming


rawDescription: Removing all alphabets and commas from a string


code:
back_to_lists = {k:list(v) for k,v in d.items()}
back_to_lists

rawDescription: How can I convert a list of maps into a map of sets in python?

description: Convert a list of maps into a map of sets in python


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

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

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


code:
p = re.compile(r'(?=\n(?:ADDITIONAL|Additional)\n)[\s\S]+?(?<=\n(?:Languages|LANGUAGES)\b)', re.MULTILINE)
test_str = "Academy \nADDITIONAL\nAwards and Recognition: Greek Man of the Year 2011 Stanford PanHellenic Community, American Delegate 2010 Global\nEngagement Summit, Honorary Speaker 2010 SELA Convention, Semi-Finalist 2010 Strauss Foundation Scholarship Program\nComputer Skills: Competency: MATLAB, MySQL/PHP, JavaScript, Objective-C, Git Proficiency: Adobe Creative Suite, Excel\n(highly advanced), PowerPoint, HTML5/CSS3\nLanguages: Fluent English, Advanced Spanish\n\x0c"
print(re.findall(p, test_str))

rawDescription: How to capture both lookahead lookbehind regex python

description: Capture both lookahead lookbehind regex python


code:
while True:
    lastcommand = input("C-Gen@H//Vilius #OpDesc: ")
    if lastcommand == "info":
        print (info)
    elif lastcommand == "list1":
        print (list1)
    elif lastcommand == "list2":
        print (list2)
    elif lastcommand == "list3":
        print (list3)
    elif lastcommand == "session_name":
        print (session_name)
    elif lastcommand == "myName":
        print (myName)
    elif lastcommand == "currentloc":
        print (currentloc)
    elif lastcommand == "currentfold":
        print (currentfold)
    elif lastcommand == "filenameloc":
        print (filenameloc)
    elif lastcommand == "cpu":
        print (cpu)
    else:
        print ("Error: incorrect command (" + lastcommand + ")")

rawDescription: Python looping [Module]

description: Python looping [Module]


code: np.array([gdal.Open(f).ReadAsArray().astype(np.float32) for f in glob.glob('*.tif')])

rawDescription: Numpy way of appending the data retrieved from for loop


code:
while SDate <= EDate:
    if SDate.month < 12:
        SDate = SDate.replace(month=SDate.month + 1)
    else:
        SDate = SDate.replace(month=1, year=SDate.year + 1)

rawDescription: Stepping dates with timedelta in months for Python


code:
from pprint import pprint
from collections import Counter
block = [
    ['alfa', 'T31360N', '2013-12-19 12:07:2'],
    ['beta', 'D41535N', '2013-12-19 12:20:1'],
    ['gamma', 'E61460N', '2013-12-19 13:58:2'],
    ['delta', 'D133PR01', '2013-12-19 14:19:4'],
    ['beta', 'Q3332N', '2013-12-19 14:19:5']
]
seen = set()
pprint([row for row in block if row[0] not in seen and not seen.add(row[0])])
counts = Counter(row[0] for row in block)
pprint([row for row in block if counts[row[0]] == 1])

rawDescription: Delete same rows from list of lists in python


code:
from itertools import chain

print(sum(i % 2 for i in  chain(*list_of_lists)))

rawDescription: Count odds in list of lists

description: Count odds in list of lists


code:
obj = Child()
obj.do_something()
Child.do_something()
obj.do_something()

rawDescription: python overriding a classmethod with an instance method

description: Python overriding a classmethod with an instance method


code:
dict = {}
tree = ET.parse('file.xml')
root=tree.getroot()
for attribute in root:
        for stats in attribute.iter('statistics'):  #Accessing to child tree of the process 'attribute'
            for sub_att in stats.iter('statistic'): #Iterating trough the attribute items
                    name      =  sub_att.get('name')
                    parameter =  sub_att.get('forparameter')
                    for param_value in sub_att.iter('value'):
                         value = param_value.text   #Collecting the value of the sub_attribute
                         break                      #Speed up the script, skips the <real_value>
            if not dict.has_key(parameter):
                    dict[parameter] = {}
            dict[parameter][name] = value

rawDescription: XML subtree parsing

description: XML subtree parsing


code:
from pyspark.sql.functions import udf, lit
my_date_format = udf(lambda d, fmt: d.strftime(fmt))

df.select(
    my_date_format(col("vacationdate"), lit("%d-%m-%Y")).alias("date_string")
).show()

rawDescription: Pyspark changing type of column from date to string


rawDescription: Composition of a hierarchy of functions

description: Composition of a hierarchy of functions


rawDescription: Sub graph isomorphism

description: Sub graph isomorphism


rawDescription: Printing a list of numbers in python v.3


code:
class TypeAdaptingProperty(object):
    def __init__(self, key, type_, factory=None):
        self.key = key
        self.type_ = type_
        if factory is None:
            self.factory = type_

    def __get__(self, instance, owner):
        if instance is None:
            return self
        return getattr(instance, self.key)

    def __set__(self, instance, value):
        if not isinstance(value, self.type_):
            value = self.factory(value)
        setattr(instance, self.key, value)

    def __delete__(self, instance):
        delattr(instance, self.key)

class Book(object):
    isbn = TypeAdaptingProperty('isbn_', ISBNNumber)

b = Book()
b.isbn = 123 # Does the equivalent of b.isbn = ISBNNumber(123)

rawDescription: What is the pythonic way to add type information to an object's attributes?


code: df_scen = df.groupby(['master id', 'scenario']).agg({'price': 'sum'}).unstack('scenario')

rawDescription: How to df.groupby.sum only one column

description: Df.groupby.sum only one column


rawDescription: iterparse large XML using python

description: Iterparse large XML using python


code:
x = 1
x + 2   # Simply returns a new value, doesn't affects `x`
x       # `x` is still unchanged
x += 1  # Assign the new value back to `x`
x       # `x` is now updated.

rawDescription: Using the if "x" in function to do a calculator but total isn't being produced


code:
reduct(2)
reduct(3)
len(reduct(7))

rawDescription: Python Itertools: Complex "product"

description: Python Itertools: Complex "product"


code:
for line in self.data:
    yield {
        "Number": line[0:9],
        "FullName": line[9:27].rstrip(),
        "LastName": line[27:63].rstrip(),
        "Area": line[63:65].rstrip(),
        "City": line[65:90].rstrip(),
        "Status": line[91],
        "Status2": line[92],
        "Status3": line[93]
    }

rawDescription: parsing a line into a dictionary through a list comprehension

description: Parsing a line into a dictionary through a list comprehension


code:
def RandomFighter(object):

    def __init__(self):
        self.strength = random.randint(1, 1000)
        self.skill = random.randint(1, 1000)

player = RandomFighter()
enemy = RandomFighter()

strength_difference = player.strength - enemy.strength
...

rawDescription: Efficient way of writing same process with different variable


code:
for i in range(0, len(gameMap)):

    for x in range(0, len(gameMap[i])):
        xC = x * 30
        y = i * 30

        if gameMap[i][x] == "*":
            screen.blit(wallImage, (xC, y))

        elif gameMap[i][x] == ".":
            screen.blit(floorImage, (xC, y))

        elif gameMap[i][x] == "+":

            if playerDirection == "up" or playerDirection == "":
                screen.blit(playerForwardImage, (xC, y))

            elif playerDirection == "right":
                screen.blit(playerRightImage, (xC, y))

            elif playerDirection == "left":
                screen.blit(playerLeftImage, (xC, y))

            elif playerDirection == "down":
                screen.blit(playerDownImage, (xC, y))

        elif gameMap[i][x] == "#":
            pygame.draw.rect(screen, black, (xC, y, 30, 30))

        elif gameMap[i][x] == "=":
            pygame.draw.rect(screen, red, (xC, y, 30, 30))

rawDescription: Storing 2D arrays within a 2D array - Python


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

rawDescription: regex replace from a list

description: Regex replace from a list


rawDescription: generating a hemispherical surface with triangular_mesh and representing a data( as value or as colors) at each vertex

description: Generating a hemispherical surface with triangular_mesh and representing a data( as value or as colors) at each vertex


code:
import subprocess
time = 10
subprocess.call(["shutdown.exe", "/t", str(time)]) # replaced `time` with `str(time)`
# OR subprocess.call([r"C:\Windows\system32\shutdown.exe", "/t", str(time)])
#      specified the absolute path of the shutdown.exe
#      The path may vary according to the installation.

rawDescription: How to shutdown windows 8 with python 2.7 using a timer

description: Shutdown windows 8 with python 2.7 using a timer


code:
dt = {'names': ['user', 'gender', 'number'], 'formats':['a10', 'a10', 'float']}
my_arr = np.array(dat, dt)  # dat is the list with tuples, see above

rawDescription: Make single column of numpy array another datatype


code:
with open('/tmp/output.csv', 'wb') as csvfile:
  writer = csv.writer(csvfile)
  writer.writerow(['Project Name', 'Documents'])
  for dirpath, dirs, filenames in os.walk(path, topdown=True):
    dirs.sort()
    if filenames:
      writer.writerow([os.path.basename(dirpath)] + sorted(filenames))

rawDescription: Python script to generate CSV file with foldernames including their associated files


rawDescription: Extracting polygon given coordinates from an image using OpenCV


code:
df3 = pd.concat((df1, df2))
df3.groupby(df3.index).mean()

#    col
# a    1
# b    3
# c    4
# d    6

rawDescription: Merge DataFrames in Pandas using the mean


code: 'Argument goes here'[::-1]

rawDescription: What is a bytearray? Why was it used?

description: What is a bytearray? Why was it used


code:
import os
len(os.sched_getaffinity(0))

rawDescription: On what CPU cores are my Python processes running?


code: raw_buffered = fobj.buffer

rawDescription: Re-open a file in binary mode with Python


rawDescription: How to get scrape DIV having Class or ID containing specific text

description: Get scrape DIV having Class or ID containing specific text


code: subs = [" ".join(words[i:i+n]) for i in range(0, len(words), n)]

rawDescription: Split a large string into multiple substrings containing 'n' number of words via python


code: my_data = person_start + first("firstname") + last("lastname") + ...

rawDescription: PyParsing a string representing a function


code:
import os,sys
from bar.controller import Controller
from bar.model import Model
from bar.view import View
class Controller(object):
 model = Model()
 view = View()

rawDescription: Laying out MVC classes in Python

description: Laying out MVC classes in Python


code:
pl.plot(np.array(XsavedArr[:,0]),np.array(XsavedArr[:,1]),
        'x-',label = 'Xsaved')

rawDescription: plotting numpy.ndarray

description: Plotting numpy.ndarray


code:
import Tkinter as tk
class Page(tk.Frame):
    def __init__(self, master, text, height, width, *args, **kwargs):
        tk.Frame.__init__(self, *args, borderwidth=20, **kwargs)
        self.height = height
        self.width = width
        button = tk.Button(self, text=text, font=('Comic Sans MS', 20),
                           command=lambda: self.callback())
        button.pack(side="top", fill="both", expand=True)
    def onlift(self):
        root.geometry('{}x{}'.format(self.width, self.height))
        self.lift()

class App(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)

        p1 = Page(self, 'Login 1', height=200, width=300)
        p2 = Page(self, 'Next page is 2', height=400, width=300)
        p3 = Page(self, 'We love number 3', height=400, width=600)
        p1.callback = p2.onlift
        p2.callback = p3.onlift
        p3.callback = p1.onlift

        p1.place(x=0, y=0, relwidth=1, relheight=1)
        p2.place(x=0, y=0, relwidth=1, relheight=1)
        p3.place(x=0, y=0, relwidth=1, relheight=1)

        p1.onlift()

root = tk.Tk()
app = App(root)
root.mainloop()

rawDescription: python Tkinter() how to hide the UI

description: Python Tkinter() how to hide the UI


code:
import numpy as np

N_TYPES = 3

instream = [ [(0,0.3), (1,0.5), (2,0.1)],
             [(0,0.5), (1,0.3), (2,0.3)],
             [(0,0.4), (1,0.4), (2,0.5)],
             [(0,0.3), (1,0.7), (2,0.2)],
             [(0,0.2), (1,0.6), (2,0.1)] ]
instream = np.array(instream)

# this removes document tags because we only consider probabilities here
values = [map(lambda x: x[1], doc) for doc in instream]

# determine the cluster of each document by using maximum probability
belongs_to = map(lambda x: np.argmax(x), values)
belongs_to = np.array(belongs_to)

# construct clusters of indices to your instream
cluster_indices = [(belongs_to == k).nonzero()[0] for k in range(N_TYPES)]

# apply the indices to obtain full output
out = [instream[cluster_indices[k]].tolist() for k in range(N_TYPES)]

rawDescription: How can I cluster a list of a list of tuple (tag, probability)? - python

description: Cluster a list of a list of tuple (tag, probability)? - python


code:
g = df.groupby('id_customer')
g[['id_order', 'product_name']].nth(0)
g[['id_order', 'product_name']].nth(1)
a = g[['id_order', 'product_name']].nth(0)
pd.concat([a, b], axis=1)

rawDescription: Pandas, create columns after groupby

description: Pandas, create columns after groupby


rawDescription: Assign many values to an element of a list


code: iter({'name': 'value'})

rawDescription: How does the `for` loop work on dictionaries specifically


code: import sys

rawDescription: how import statement executes in python?

description: How import statement executes in python


code: name = df.index[0].split("_")[0]

rawDescription: Improvement in pandas dataframe conversion in Python


code:
for modulename, submodule in inspect.getmembers(package, inspect.ismodule):
    for result in find_name(submodule, name):
        yield result

rawDescription: How to locate a function in a Python module tree?

description: Locate a function in a Python module tree


rawDescription: How to filter the string patterns to match in textlines with regex?

description: Filter the string patterns to match in textlines with regex


code:
import timeit
def sum1(lst):
    s = 0
    for i in lst:
        s += i
    return s

def sum2(lst):
    return sum(lst)

values = range(1000000)
timeit.timeit('f(lst)', 'from __main__ import sum1 as f, values as lst', number=100)
timeit.timeit('f(lst)', 'from __main__ import sum2 as f, values as lst', number=100)

rawDescription: Python built-in sum function vs. for loop performance


code:
for x in sorted(np.unique(arr[...,2])):
    results.append([np.average(arr[np.where(arr[...,2]==x)][...,0]),
                    np.average(arr[np.where(arr[...,2]==x)][...,1]),
                    x])

rawDescription: Group and Average Numpy Matrix

description: Group and Average Numpy Matrix


code:
count_contig['contig92741'] # returns 2
count_contig['unknown_contig'] # returns 0, thanks to defaultdict

rawDescription: Comparing elements in line

description: Comparing elements in line


rawDescription: Replace all non-alphanumeric characters in a string


code:
import re
control_input="prompt_029"
if re.match('^prompt_[0-9]+$',control_input):
    print("Matches Format")
else:
    print("Doesn't Match Format")

rawDescription: Condition if string contains only variable and integer Python


code:
current_status_list = ['foo', 'bar', 'baz']
previous_status_list = current_status_list
current_status_list is previous_status_list
current_status_list.append('spam')
previous_status_list
previous_status_list = current_status_list[:]  # shallow copy
current_status_list is previous_status_list
current_status_list.append('ham')
current_status_list
previous_status_list

rawDescription: List comparison failing

description: List comparison failing


code: getAdditionalGooglePages = beautifulSoupObj.find_all('a', attrs={"class": "fl"})

rawDescription: BeautifulSoup Django Parse for Links

description: BeautifulSoup Django Parse for Links


code:
from twisted.internet import reactor
reactor.callLater(3, reactor.stop)
reactor.run()

rawDescription: How to stop a TimerService from within the LoopingCall

description: Stop a TimerService from within the LoopingCall


code: l = [ i for i in range(1, 11) if i % 2 == 0]

rawDescription: Storing values from loop in a list or tuple in Python


rawDescription: Python re.findall with * and **

description: Python re.findall with * and **


rawDescription: Correlating vector data with numpy

description: Correlating vector data with numpy


code: x -= A[:,5].toarray().flatten()

rawDescription: subtract column of scipy.sparse matrix from a vector

description: Subtract column of scipy.sparse matrix from a vector


rawDescription: How to convert pandas single column data frame to series or numpy vector

description: Convert pandas single column data frame to series or numpy vector


code: cur.execute("SELECT %s FROM Data where %s=?" % (column, goal), (constrain,))

rawDescription: Python sqlite3 string variable in execute


code:
b='student'
[b[i:i+2] for i in range(len(b)-1)]

rawDescription: Quick implementation of character n-grams using python


code:
self.adviser_store = simpy.FilterStore(self.env,
capacity=self.total_ad_instances)

rawDescription: simpy resource availability schedule

description: Simpy resource availability schedule


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

x = np.exp2(np.arange(10))

fig = plt.figure()
ax = fig.add_subplot(111)
ax.semilogy(x)
ax.yaxis.get_major_locator().base(2)
ax.yaxis.get_minor_locator().base(2)

# This will place 1 minor tick halfway (in linear space) between major ticks
# (in general, use np.linspace(1, 2.0001, numticks-2))
ax.yaxis.get_minor_locator().subs([1.5])

ax.yaxis.get_major_formatter().base(2)

plt.show()

rawDescription: PyLab: Plotting axes to log scale, but labelling specific points on the axes


rawDescription: How do you get the first 3 elements in Python OrderedDict?

description: Get the first 3 elements in Python OrderedDict


code:
math.floor(math.log(10, 2)) + 3

len(bin(10))
math.floor(math.log(77, 2)) + 3
len(bin(77))

rawDescription: Python character length of a binary value


code:
def setup(self):
    Sample.__init__(self, 'good', 'day', 'sir')

myclass = type("TestSample", (Sample,), dict(__init__=setup))

rawDescription: Python27: Subclassing a class by using type


rawDescription: Break string into list elements based on keywords


code:
from itertools import cycle
hexlify(''.join(chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(unhexlify(s1), cycle(unhexlify(s2)))))

rawDescription: (Python) How to XOR two hex strings so that each byte is XORed separately?


rawDescription: Variable within a Variable in Python (3)


code:
add_method(e, bark)
e.bark()

rawDescription: Any elegant way to add a method to an existing object in python?


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

z = np.arange(40).reshape(4, 10)
x = np.linspace(1900, 2000, 10)
y = np.linspace(20, 50, 4)

fig, ax = plt.subplots()
ax.imshow(z, cmap='gist_earth', interpolation='nearest', origin='lower',
          extent=[x.min(), x.max(), y.min(), y.max()])
plt.show()

rawDescription: Adding a constant to the x axis

description: Adding a constant to the x axis


code:
command = input("enter a command: ")
arguments = input("enter arguments separated by a single space: ").split()
if command in commands:
    commands[command](*arguments)

rawDescription: Create a sort of command line for a python server


code:
new_list = my_list[:]
new_list[replace_index] = new_value

rawDescription: Replacing a list item and returning a copy of the list (in one line) with Python


code: sorted(set().union(first, second)) #returns a sorted list of unique items

rawDescription: Create a list of integer elements from list of objects


code:
import csv

table = {"2015-11-10": [('pear', 22), ('banana', 50)],
         "2015-11-13": [('banana', 22), ('apple', 50), ('strawberry', 30), ('pear', 35), ('orange', 2), ('mango', 76)],
         "2015-11-12": [('banana', 22), ('orange', 50), ('mango', 30), ('strawberry', 35)]
         }

with open('transaction.csv', 'wb') as f:
    w = csv.writer(f, delimiter=',')
    w.writerow(['transaction_date', 'fruits', 'quantity'])

    for transaction_date, fruits in table.items():
        for fruit, quantity in fruits:
            w.writerow([transaction_date, fruit, quantity])

rawDescription: Create CSV file from dictionary of list of tuples


code:
event_form = EventForm(request.POST, prefix="event")
event_time_form = EventTimeForm(request.POST, prefix="eventtime")

if event_form.is_valid() and event_time_form.is_valid():
    event = event_form.save()
    event_time = event_time_form.save()
    event_time.event.add(event)

rawDescription: Multiple models in one form

description: Multiple models in one form


rawDescription: parsing first character of e164 string seperately in python

description: Parsing first character of e164 string seperately in python


rawDescription: Optimal solution to extend a python list by adding the at the beginning of the list instead of tail?


code:
import numpy as np

times = np.fromiter((d['first_alerted_time'] for d in example_table),
                     dtype='datetime64[us]', count=len(example_table))
bins = np.fromiter(date_range(start_date, end_date + step, step),
                   dtype=times.dtype)
a, bins = np.histogram(times, bins)
print(dict(zip(bins[a.nonzero()].tolist(), a[a.nonzero()])))

rawDescription: Python- Count the frequency of messages within a date range within per dynamic interval


code:
from builtins import abs as _abs

# ...

def abs(a):
    "Same as abs(a)."
    return _abs(a)

rawDescription: Python: what's the difference - abs and operator.abs


code:
mpl.rcParams['legend.markerscale'] = 0
mpl.rcParams['legend.handletextpad'] = 0

rawDescription: Python plot legend : markers appear twice


rawDescription: Pandas saving and reading DataFrame to json


code: Superclass = Watcher(name, bases, clsdict)

rawDescription: Python: Run code when a class is subclassed


code:
def random_powerset(iterable):
     s = list(iterable)
     lengths = list(range(len(s)+1))
     shuffle(lengths)
     return chain.from_iterable(combinations(s, r) for r in lengths if not shuffle(s))

rawDescription: Randomize chain from itertools

description: Randomize chain from itertools


code:
class CustomPasswordResetForm(PasswordResetForm):
    def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
         use_https=False, token_generator=default_token_generator, request=None):
        from django.core.mail import send_mail
        for user in self.users_cache:
            if not domain_override:
                current_site = get_current_site(request)
                site_name = current_site.name
                domain = current_site.domain
            else:
                 site_name = domain = domain_override
            t = loader.get_template(email_template_name)
            c = {
            'email': user.email,
            'domain': domain,
            'site_name': site_name,
            'uid': int_to_base36(user.id),
            'user': user,
            'token': token_generator.make_token(user),
            'protocol': use_https and 'https' or 'http',
            }
            send_mail(_("YOUR SUBJECT HERE %s") % site_name,
                t.render(Context(c)), None, [user.email])

rawDescription: Django password reset email subject

description: Django password reset email subject


code: result = result.groupby(['Protein', 'Peptide'])['Mean intensity'].mean()

rawDescription: Grouping and filtering data

description: Grouping and filtering data


code:
def multiply_cost(value):
    return value*100

register.filter('multiply_cost', multiply_cost)

rawDescription: Django Template How to Show Money Values like 4.8p


code:
class Config(object):
    def __init__(self, x=2):
        self.x = x
        self.y = x * 2

rawDescription: Python dynamic import and changing a variable


code:
from django.forms.formsets import formset_factory

def add_poll(request):
    ChoiceFormSet = formset_factory(ChoiceForm, extra=3,
                                    min_num=2, validate_min=True)
    if request.method == 'POST':
        form = PollForm(request.POST)
        formset = ChoiceFormSet(request.POST)
        if all([form.is_valid(), formset.is_valid()]):
            poll = form.save()
            for inline_form in formset:
                if inline_form.cleaned_data:
                    choice = inline_form.save(commit=False)
                    choice.question = poll
                    choice.save()
            return render(request, 'polls/index.html', {})
    else:
        form = PollForm()
        formset = ChoiceFormSet()

    return render(request, 'polls/add_poll.html', {'form': form,
                                                   'formset': formset})

rawDescription: Combining two forms in one Django view

description: Combining two forms in one Django view


code:
dimList <- list(farms=c('farm A', 'farm B'), crops=c('apple', 'pear', 'durian'));
constList <- list(numTrees=c(10,20,30,1,2,3));
paramList <- list(mean=c(10,20,30,5,10,15), sd=c(2,4,6,1,2,3));
distSim(nSims=3, simName='harvestPerTree', distFn=rnorm, dimList=dimList,
        paramList=paramList, constList=constList);

rawDescription: How to structure an easily extensible Monte Carlo model in R

description: Structure an easily extensible Monte Carlo model in R


code:
def zahlen(schein, function, *arguments):
    if len(schein) < 6:
        schein.append(function(*arguments))
        return zahlen(schein, function, *arguments)
    return schein

rawDescription: recursive number generator not working

description: Recursive number generator not working


code:
button = QPushButton('start')
textedit = QTextEdit()
process = QProcess()

button.clicked.connect(on_clicked)

def on_clicked():
    process.readyReadStandardOutput.connect(read_ready)
    process.start('/bin/sh',
       ('-c', "while /bin/true; do echo hello world ; sleep 1; done"))

def read_ready(self):
    chunk = process.readAllStandardOutput()
    textedit.append(str(chunk))

rawDescription: Python QT create app. that can interactively receive from and send to a CLI script


code: df = pd.read_csv(filename, parse_dates=[0])

rawDescription: possible speed up of pandas apply

description: Possible speed up of pandas apply


code: dists[abs(dists - r - dr/2.) <= dr/2.]

rawDescription: Numpy where function multiple conditions


code: dict(map(tuple, kv) for kv in json.loads('[[[1, 2, 3], ["foo", "bar"]]]'))

rawDescription: JSON encoding for dict of dicts

description: JSON encoding for dict of dicts


code: b = (msg + '\n').encode('utf-8')

rawDescription: Possible to send two seperate data within the same connection for Twisted TCP?


rawDescription: Efficient reverse of queryset

description: Efficient reverse of queryset


code:
import dis
def wrapper():
    class A(object):
        pass

dis.dis(wrapper)
dis.dis(wrapper.__code__.co_consts[2])

rawDescription: Why does a class definition always produce the same bytecode?


code:
with mock.patch("__builtin__.open", side_effect = lambda name, *args: name):
    assert "stuff.txt" == open("stuff.txt")
    assert "another_thing.txt" == open("another_thing.txt")
    assert "last_one.txt" == open("last_one.txt")

rawDescription: Patching one occurrence on the function call in Python's Mock


code:
{'17337': {'price': 14.0, 'name': 'Arber Hair & Body Wash', 'quantity': 3},
 '21381': {'price': 19.0, 'name': 'Vitamin E Illuminating Moisture Cream', 'quantity': 2}}

rawDescription: How to add two items in list of dictionaries

description: Add two items in list of dictionaries


code:
def is_yes(x):
    return str(x).lower() in ('1', 'true', 'yes', 'on')

for x in ['true', 'yes', 'Yes', 'on', 'On', '1', 1, True, False, None, 0, 'no', 'random']:
    print(is_yes(x))

rawDescription: Python regular expression for different words & number


code:
import functools

def run_through_drivers(driver_pool='drivers'):
    def wrapped(test_func):
        @functools.wraps(test_func)
        def decorated(test_case, *args, **kwargs):
            test_class = test_case.__class__
            web_driver_pool = getattr(test_class, driver_pool)
            for web_driver in web_driver_pool:
                setattr(test_case, 'selenium', web_driver)
                test_func(test_case, *args, **kwargs)
        return decorated
    return wrapped

rawDescription: How to run selenium tests using LiveServerTestCase in different browsers?

description: Run selenium tests using LiveServerTestCase in different browsers


code:
from urllib import urlencode

base_url = "http://en.wikipedia.org/w/api.php?"

arguments = dict(action="query",
                 meta="globaluserinfo",
                 guiuser="$cammer",
                 guiprop="groups|merged|unattached",
                 format="json")
url = base_url + urlencode(arguments)

rawDescription: Python url construction: escape characters other than regular letters


rawDescription: difference between numpy dot() and inner()

description: Difference between numpy dot() and inner()


code:
import locale
locale.setlocale(locale.LC_ALL, "nl_BE")
locale.str(234.2)

rawDescription: Localise float notation

description: Localise float notation


code:
a.set_instrument(0, 34)
a.set_instrument(1, 35)

a.play_Note(26, 0, 127)
a.sleep(0.5)
a.play_Note(26, 1, 127)
a.sleep(0.5)

rawDescription: How to set more than one instrument by Python plus Mingus?

description: Set more than one instrument by Python plus Mingus


code:
lists = list() # a list of lists

cur = 0 # index in the modified list
for idx, line in list(enumerate(lists)): # make a copy of the original
    if idx > 0:
        cur_val = line[0] # value of current line
        prev_val = lists[idx-1][0] # value of previous line

        if prev_val == cur_val:
            del lists[cur-1] # IndexError: list index out of range
        else:
            cur += 1
    else:
        cur += 1

rawDescription: Remove a specific index from a list while iterating in Python


code:
# check if the values are valid.
validRegex = re.compile(r'^mice$|^mouse$|^cat$|^dog$')

# if they aren't add them to a new list.
badAttrs = []
for attribute in attributes:
    if len(attribute) == 0:
        # if it's a zero length attribute, we punt
        continue
    if validRegex.search(attribute.lower()) == None:
        # if the attribute from the search isn't in the valid list
        if attribute not in badAttrs:
            # and the attribute isn't already in the list
            badAttrs.append(attribute)

rawDescription: Regex for finding valid sphinx fields

description: Regex for finding valid sphinx fields


code:
with open("file2") as fin:
    file2 = dict(imap(str.split, fin))

rawDescription: Two lists, if a common match is found print another list element


code:
True == 1
False == 0

rawDescription: max() function: how to get the item being iterated and pass to key=func()

description: Max() function: how to get the item being iterated and pass to key=func()


code:
import matplotlib.backends.backend_tkagg as backend
from matplotlib.figure import Figure

manager = backend.new_figure_manager(0)
fig = manager.canvas.figure
ax = fig.add_subplot(1,1,1)
ax.plot([1,2,3])
fig.show()
backend.show()

rawDescription: Interactive figure with OO Matplotlib

description: Interactive figure with OO Matplotlib


code:
def integral_rec(integrand,initial_value,dt):
    def int_rec():
        for x in cons_stream(initial_value,
                    add_streams(scale_stream(integrand,dt),int_rec())):
            yield x
    for x in int_rec():
        yield x

def cons_stream(a,b):
    yield a
    for x in b:
        yield x

def add_streams(a,b):
    while True:
        yield next(a) + next(b)

def scale_stream(a,b):
    for x in a:
        yield x * b

rawDescription: SICP "streams as signals" in Python

description: SICP "streams as signals" in Python


rawDescription: How to install Python module without setup.py?

description: Install Python module without setup.py


code:
df_x = pd.DataFrame([[1,2,1],[2,3,4]], columns=list('ABC'))
df_y = pd.DataFrame([[2,6,1],[4,9,4]], columns=list('ABC'))
pd.DataFrame({'x': df_x.stack(), 'y': df_y.stack()}).reset_index(level=1).pivot('x', 'level_1', 'y')

rawDescription: Plotting and GroupBy methods

description: Plotting and GroupBy methods


code: oldcppflags=env["CPPFLAGS"]

rawDescription: Strange behaviour appending/removing from array with SCons


code:
num = 6 # num is now 6
num = addFive(num) # num is now 11

rawDescription: Python number averages using lists and keys


code:
a = np.arange(1, 7).reshape(2, 3)
a

rawDescription: Numpy - slicing 2d row or column vector from array


code:
def f1(x, y):
    for i in range(min(x, y), max(x, y)):
        pass

def f2(x, y):
    for i in range(*sorted((x, y))):
        pass

def f3(x, y):
    for i in range(x, y) if x<y else range(y, x):
        pass

def f4(x, y):
    if x>y:
        x,y = y,x
    for i in range(x, y):
        pass

def f5(x, y):
    mn,mx = ((x, y), (y, x))[x>y]
    for i in range(x,y):
        pass

rawDescription: Best way to find max and min of two values

description: Find max and min of two values


rawDescription: How to use a variable within a class that will be independent of any objects created in python?

description: Use a variable within a class that will be independent of any objects created in python


rawDescription: Looping through nested list that contains dictionary


code: ('salad:', 1, 'hamburger:', 2, 'water:', 2)

rawDescription: how to omit parenthesis in return from a python def

description: Omit parenthesis in return from a python def


code:
class Test:

  def get_dynamic_value():
    return 'dynamic'

  dynamic_value = get_dynamic_value()
  del get_dynamic_value

rawDescription: Assigning class variable dynamic value from inside a classs


code:
df * weight[0]
(df * weight[0]).sum(1)

rawDescription: How to compute weighted sum of all elements in a row in pandas?

description: Compute weighted sum of all elements in a row in pandas


code:
import datetime
from dateutil.relativedelta import relativedelta

today = datetime.date.today()
age_25 = (today - relativedelta(years=25)).year
age_36 = (today - relativedelta(years=36)).year
Employees.objects.filter(birth_year__lte=age_25, birth_year__gte=36)

rawDescription: How to calculate if age is in range from the birth year ,while fetching the birth year from Db in Django ORM

description: Calculate if age is in range from the birth year ,while fetching the birth year from Db in Django ORM


code:
transposed = np.transpose(b, (2, 0, 1))
np.hstack((transposed[0][:, None], transposed[1][:, None]))[msk]

rawDescription: Reshaping/extending numpy mask

description: Reshaping/extending numpy mask


code: url(r'^$', views.home,  name="home")

rawDescription: Cannot pass variables to django home template from another template in app


code: {di['shape']:di for di in sorted(li1+li2, key=lambda d: d['priority'])}.values()

rawDescription: Merging a list of dictionaries in python based on one key/value pair?


rawDescription: how to iterate over all keys in dictionary python?

description: Iterate over all keys in dictionary python


code:
def calculate_length(ind):
    # Frist, let's transform the dictionary into a list of doc_id, tl_idf pairs; [[doc_id_1,tl_idf_1],...]
    data = [entry[0] for entry in ind.itervalues()] # use just ind.values() in python 3.X
    # Next, let's split that list into two, one for doc_id's, one for tl_idfs
    doc_ids, tl_idfs = zip(*data)
    # We can just assume that all the doc_id's are the same. you could check that here if you wanted
    doc_id = doc_ids[0]
    # Next, we calculate the length as per our formula
    length = sqrt(sum(tl_idfs**2 for tl_idfs in tl_idfs))
    # Finally, we return the output dictionary
    return {doc_id: length}

rawDescription: for information retrieval course using python, accessing given tf-idf weight

description: For information retrieval course using python, accessing given tf-idf weight


code: win_avg = np.mean(windowed_view(arr, win_size, win_overlap), axis=-1)

rawDescription: Window overlap in Pandas

description: Window overlap in Pandas


code:
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)

rawDescription: Opencv: detect mouse position clicking over a picture


code:
for count in range(100):
    numbers = random.randint(1, 100)
    print(numbers)
    if isEven(numbers):  # Notice we're using the helper function here
        even += 1
    else:
       odd += 1

rawDescription: Adding True/False Boolean expression into program. (Python)


rawDescription: Group data into specified intervals satisfying certain condition


code: pylab.rcParams['figure.figsize'] = (10.0, 8.0)

rawDescription: How to set the matplotlib figure default size in ipython notebook?

description: Set the matplotlib figure default size in ipython notebook


code: gloss = L2[1].rstrip('\n')

rawDescription: removing mysterious line break python

description: Removing mysterious line break python


code:
texts = [(span_i.text, span_vi.text) for span_i, span_vi in spans]
texts

rawDescription: Parsing web page in python using Beautiful Soup


rawDescription: Iterating through multiple values in a dictionary?


rawDescription: Select rows from a DataFrame based on presence of null value in specific column or columns


code:
re.search(r'word$', 'Line one word\nLine two\n', flags=re.M)
re.search(r'word\Z', 'Line one word\nLine two\n', flags=re.M) is None

rawDescription: REGEX - Differences between `^`, `$` and `\A`, `\Z`


code:
graphs = [graph] # start off with just one graph
for generation in range(n):
    graphs = (graph.add_edge(e) for graph in graphs for e in graph.possible_new_edges())

rawDescription: lookahead algorithm in Python

description: Lookahead algorithm in Python


code:
from deadparrot import voom

voom()

rawDescription: Execute a python separate application in a java application


rawDescription: Efficient way to calculate averages, standard deviations from a txt file


code: output = { i : [ r.match(i).group(0) for r in ref_re if r.match(i) ] for i in input }

rawDescription: Match two Python lists with regular expressions, and create dictionary output


code:
[[['point'], ['point']],
 [['point', 'floating'], ['floating', 'undefined', 'point']]]

rawDescription: Mapping two list of lists based on its items into list pairs in Python


code: return "{}, {}".format(a, numbersInbetween(a + 1, b))

rawDescription: A more optimized code in recursion exercise


code:
...

class DeckCreateView(CreateView):
    ...
    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect(self.success_url)
        else:
            return render(request, self.template_name, {'form': form})

rawDescription: How to access the Django forms.FileField file (*not models.FileField*)?

description: Access the Django forms.FileField file (*not models.FileField*)


rawDescription: Python Pandas get one text value

description: Python Pandas get one text value


code:
from setuptools           import setup, find_packages
from setuptools.extension import Extension
from Cython.Build         import cythonize

extensions = [
        Extension(
                "myPackage/myModule",
                ["myPackage/myModule.pyx"] ,
                include_dirs=['/some/path/to/include/'], # not needed for fftw unless it is installed in an unusual place
                libraries=['fftw3', 'fftw3f', 'fftw3l', 'fftw3_threads', 'fftw3f_threads', 'fftw3l_threads'],
                library_dirs=['/some/path/to/include/']), # not needed for fftw unless it is installed in an unusual place
]

setup(
    name        = "myPackage",
    packages    = find_packages(),
    ext_modules = cythonize(extensions)
)

rawDescription: Using setuptools to create a cython package calling an external C library


code:
from xhtml2pdf import pisa
from cStringIO import StringIO

content = StringIO('html goes here')
output = StringIO()
pisa.log.setLevel('DEBUG')
pdf = pisa.CreatePDF(content, output, encoding='utf-8')
pdf_data = pdf.dest.getvalue()

rawDescription: HTML to PDF conversion in app engine python


code: weightvalue = file_list.sheet.cell(3, 3).value

rawDescription: Read files from list of files

description: Read files from list of files


code:
import pkgutil

data = pkgutil.get_data("conf", "constants.cfg")

rawDescription: Python : How to access file from different directory


code:
import os
import urllib
from lxml import html
from urlparse  import urljoin
import grequests

def main():
    url = "http://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_IEC_14496-26_2010_Bitstreams/DVD1/mpeg4audio-conformance/compressedMp4/"

    page = html.fromstring(urllib.urlopen(url).read())
    reqs = (grequests.get((urljoin("http://standards.iso.org/", link))) for link in page.xpath("//a/@href"))
    for resp in grequests.imap(reqs):
        print(resp.content)

rawDescription: python download all files in a web page

description: Python download all files in a web page


rawDescription: Can I run multiple Ipython qt console in the same time?

description: Run multiple Ipython qt console in the same time


rawDescription: delete a part of pd.DataFrame with Python

description: Delete a part of pd.DataFrame with Python


code: func (lambda x, y = 8: x + y)

rawDescription: Python specify lambda arguments as a function argument


code: all_result = (attrgetter('usedBytes','total','aligned','encoding')(obj) for obj in keys.items())

rawDescription: Pythonic way to aggregate object properties in memory efficient way?


code:
if __name__ == '__main__':

    circle = Circle(x=3, y=4, r=5)
    print(circle.x)
    print(circle.y)
    print(circle.r)
    print(circle.area)
   # circle.area = 12
    print(circle.area)
    print(circle.circumference)
    print(circle.distance_to_origin)
    tests = [('circle.x = 12.3', "print('Setting circle.x to non-integer fails')"),
             ('circle.y = 23.4', "print('Setting circle.y to non-integer fails')"),
             ('circle.area = 23.4', "print('Setting circle.area fails')"),
             ('circle.circumference = 23.4', "print('Setting circle.circumference fails')"),
             ('circle.distance_to_origin = 23.4', "print('Setting circle.distance_to_origin fails')"),
             ('circle.z = 5.6', "print('Setting circle.z fails')"),
             ('print(circle.z)', "print('Printing circle.z fails')")]
    for test in tests:
        try:
            exec(test[0])
        except:
            exec(test[1])

rawDescription: Using descriptor class to raise RuntimeError when user tries to change object's value


code:
import pprint
from itertools import product

def myproduct():
    keys = 'abcdefg'
    values = [(0, 1) for k in keys]

    for value in product(*values):
        d = dict(zip(keys, value))
        # Skip: C and F that are 0 (False)
        if d['c'] == 0 or d['f'] == 0:
            continue

        # Skip: When A is false, E and G cannot be false
        if d['a'] == 0 and (d['e'] == 0 or d['g'] == 0):
            continue

        # Skip: When B is false, D cannot be false
        if d['b'] == 0 and d['d'] == 0:
            continue

        yield d  # This 'permutation' is good

for d in myproduct():
    pprint.pprint(d)

rawDescription: Permute a list using Python

description: Permute a list using Python


code:
import subprocess, re, csv

list_of_ips = ["facebook.com", "google.com"]
avgTimeList = []
for ip in list_of_ips:
    ping_process = subprocess.Popen(['ping', '-c', '5', ip], stdout=subprocess.PIPE)
    stdout = ping_process.stdout.read()
    match = re.search(r'\d*\.\d*\/(\d*\.\d*)\/\d*\.\d*\/\d*\.\d*', stdout)
    avg = match.group(1)
    avgTimeList.append([ip, avg])

with open('avgTimes.csv', 'w') as csvfile:
    csvWriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
    for data in avgTimeList:
        csvWriter.writerow(data)

rawDescription: Python write stdout to log file

description: Python write stdout to log file


code:
if any(value in list1 for value in list2):
    square = 77
else:
    square = 55

rawDescription: How to search for items in a list in python

description: Search for items in a list in python


code: a.viewitems() ^ b.viewitems()

rawDescription: Comparing two dictionaries and printing key value pair in python


code:
from matplotlib.dates   import  DateFormatter,    \
                                AutoDateLocator,   \
                                HourLocator,        \
                                MinuteLocator,       \
                                epoch2num
from matplotlib.ticker  import  ScalarFormatter, FuncFormatter

aPlotAX.xaxis.set_major_formatter( DateFormatter( '%Y%m' ) )  # OUGHT WORK

rawDescription: Reading a time list and make a plot using matplotlib


code:
dview.scatter('rank', rc.ids, flatten=True)

def mul_by_rank(x):
    return x * rank

dview.map_sync(mul_by_rank, range(len(rc)))

rawDescription: iPython parallel pushing every objects is messy

description: IPython parallel pushing every objects is messy


rawDescription: pandas - binning with bins definitions based on value in another column

description: Pandas - binning with bins definitions based on value in another column


code: backend : Agg

rawDescription: Using matplotlib *without* TCL

description: Using matplotlib *without* TCL


rawDescription: Understanding dict.copy() - shallow or deep?


code:
drange = [i//2 for i in xrange(j*2)]
drange

rawDescription: How can I repeat elements in place in an array in Python?

description: Repeat elements in place in an array in Python


code: plt.streamplot(xi, yi, vgrad[0], vgrad[1])

rawDescription: Generating gradient map of 2D array

description: Generating gradient map of 2D array


code:
import sip # you'll need this import (no worries, it ships with your pyqt install)
sip.delete(self.sv_widgets[purchase.id])

rawDescription: Removing custom widget from QVBoxLayout

description: Removing custom widget from QVBoxLayout


code:
# processing
# =====================================================
# robust regression
robust_estimator = RANSACRegressor(random_state=0)
robust_estimator.fit(np.vstack([a,b]).T, d)
d_pred = robust_estimator.predict(np.vstack([a,b]).T)

# calculate mse
mse = (d - d_pred.ravel()) ** 2

# get 50 largest mse, 50 is just an arbitrary choice and it doesn't assume that we already know there are 100 outliers
index = argsort(mse)
fig, axes = plt.subplots(ncols=2, sharey=True)
axes[0].scatter(a[index[:-50]], d[index[:-50]], c='b', label='inliers')
axes[0].scatter(a[index[-50:]], d[index[-50:]], c='r', label='outliers')
axes[0].set_xlabel('a')
axes[0].set_ylabel('d')
axes[0].legend(loc='best')
axes[1].scatter(b[index[:-50]], d[index[:-50]], c='b', label='inliers')
axes[1].scatter(b[index[-50:]], d[index[-50:]], c='r', label='outliers')
axes[1].legend(loc='best')
axes[1].set_xlabel('b')

rawDescription: Identifying chunks of outliers from a 1D and 2D data in Python


code:
import timeit
timeit.Timer( "'#'.join([s[a:a+6] for a in range(0,len(s),6)])", "s='x'*100").timeit()

rawDescription: How to print string in this way

description: Print string in this way


code:
write_html = """

<form name="input" action="copy_file.php" method="get">

<input type="hidden" name="path1" value="{0}" />
<input type="hidden" name="path2" value="{1}" />

<input type="button" name="button" value="onClick="copyfile('{0}', '{1}')"/>

<script> function moveFile(path1, path2){ ...} </script>

""".format(path1, path2)

rawDescription: How to pass python variable values to php inside html?

description: Pass python variable values to php inside html


code:
base_url = "http://www.leg.state.fl.us/Statutes/index.cfm?App_mode=Display_Statute&URL=0000-0099/00{chapter:02d}/00{chapter:02d}.html"
for chapter in range(1, 100):
    url = base_url.format(chapter=chapter)
    print(url)
    # make a request and parse the page

rawDescription: Python web scraping using BeautifulSoup, how to loop through complicated URL?


code:
tmp=min(x,y)
y=max(x,y)
x=tmp

rawDescription: Number sort using Min, Max and Variables


code:
import pickle

pickle.dump(save_state, open('dude.txt', 'wb'))

rawDescription: Can I create an RPG-esque save & quit, and then reload progress?

description: Create an RPG-esque save & quit, and then reload progress


rawDescription: Creating an overlap array with conditions - Python


code:
def acronyms():
    words = input("Please enter name: ").split()
    return ''.join(w[0].upper() for w in words)

rawDescription: convert input into acronym in def function?

description: Convert input into acronym in def function


code:
[
    (u'Jasvinder Tours And Travels', 0),
    ...
    (u'The Royal Tours & Travels', 2.9),
    (u'Preeti Travels & Transport', 4.4)
]

rawDescription: Beautiful Soup processing

description: Beautiful Soup processing


code:
from scipy.spatial import KDTree
# create some fake data
x = arange(20)
y = rand(20)
z = x**2
# put them togheter, should have a form [n_points, n_dimension]
data = np.vstack([x, y, z]).T
# create the KDTree
kd = KDTree(data)

rawDescription: Calculate euclidean distance with numpy

description: Calculate euclidean distance with numpy


code:
def msearch():
    es = get_es_instance()

    search_arr = []
    # req_head
    search_arr.append({'index': 'my_test_index', 'type': 'doc_type_1'})
    # req_body
    search_arr.append({"query": {"term" : {"text" : "bag"}}, 'from': 0, 'size': 2})

    # req_head
    search_arr.append({'index': 'my_test_index', 'type': 'doc_type_2'})
    # req_body
    search_arr.append({"query": {"match_all" : {}}, 'from': 0, 'size': 2})

    request = ''
    for each in search_arr:
        request += '%s \n' %json.dumps(each)

    # as you can see, you just need to feed the <body> parameter,
    # and don't need to specify the <index> and <doc_type> as usual
    resp = es.msearch(body = request)

rawDescription: How to create request body for Python Elasticsearch mSearch

description: Create request body for Python Elasticsearch mSearch


code:
food = driver.find_element_by_xpath("//a[contains(@href, 'category/food/')]/..")
hov = ActionChains(driver).move_to_element(food).move_by_offset(5, 45).perform()
# 45 is the Height of the 'FOOD' link plus 5

recipes = WebDriverWait(driver, 5).until(lambda driver: driver.find_element_by_xpath("//a[contains(@href, 'category/recipes-2/')]/.."))
recipes.click()

rawDescription: Selecting incorrect submenu item after hover action


rawDescription: Python and numpy - removing rows from a corresponding matrix


code:
f = open('ints','wb')
x = f.read()
x
numpy.fromstring(x, dtype=np.uint16, count=3)

rawDescription: How can I read and write binary files?

description: Read and write binary files


rawDescription: Hexlify an integer in Python

description: Hexlify an integer in Python


code:
# create snail element
snail = dom.createElement('snail')
snail_text = dom.createTextNode('2')
snail.appendChild(snail_text)

# add it in the right place
profile = dom.getElementsByTagName('profile')[0]
pineapples = dom.getElementsByTagName('pineapples')[0]
profile.insertBefore(snail, pineapples)

rawDescription: Sibling nodes in ElementTree in Python

description: Sibling nodes in ElementTree in Python


code:
with open('index.txt', 'r') as inf:
    text = inf.read()
while "*" in text:
    text = text.replace("*", str(number), 1)
    number += 1

rawDescription: Replace "*" (asterics) in HTML file with increasing number with python


code: pd.Series(a, a._fields)

rawDescription: How do I create pandas DataFrame (with index or multiindex) from list of namedtuple instances?

description: Create pandas DataFrame (with index or multiindex) from list of namedtuple instances


code:
@mock.patch('monitor.report.history_item.HistoryItem.compute_score')
def test_save_device_report(self, my_mock_compute_score):
    ...
    result = factory.create_history_item(jsn)
    self.assertFalse(my_mock_compute_score.called)
    ...

rawDescription: How to make sure that a function doesn't get called using Mock in a Django Application

description: Make sure that a function doesn't get called using Mock in a Django Application


code: df.value = df.value.astype(int)

rawDescription: How to copy pandas DataFrame values down to fill 0's?

description: Copy pandas DataFrame values down to fill 0's


code: [{a[index]: index} for index in range(len(a))]

rawDescription: Finding Index in string with recurring chars


code:
def cuts(s,i):
   return [ s[a:b] for a in range(i+1) for b in range(i+1,len(s)+1)]

rawDescription: Python set combinations of adjacent letters


code:
import inspect

def inheritdocstring(name, bases, attrs):
    if not '__doc__' in attrs:
        # create a temporary 'parent' to (greatly) simplify the MRO search
        temp = type('temporaryclass', bases, {})
        for cls in inspect.getmro(temp):
            if cls.__doc__ is not None:
                attrs['__doc__'] = cls.__doc__
                break

    return type(name, bases, attrs)

rawDescription: Inherit a parent class docstring as __doc__ attribute


code:
import re
str = "13480 D'AAA-BBB CCC..."
result = re.search("([\d]+)\s([\w\s\x27\x2E\x2C\x2D]+)",str)

print(result.group(1)) # will print "13480"
print(result.group(2)) # will print "D'AAA-BBB CCC..."

rawDescription: python and string extraction

description: Python and string extraction


rawDescription: How to find the shortest dependency path between two words in Python?

description: Find the shortest dependency path between two words in Python


code:
with open('my_file') as f:
    my_list = [json.loads(line) for line in f]

rawDescription: Append list of Python dictionaries to a file without loading it


rawDescription: scipy curve fitting negative value

description: Scipy curve fitting negative value


code:
class myclass(object):
    def __getattr__(self, attr):
        if attr=="age":
            self.age=21   #This can be a long computation
        return super(myclass, self).__getattribute__(attr)

rawDescription: Pythonic way to only do work first time a variable is called


code:
year, week, dow = datetime.today().isocalendar()
week_start = datetime.strptime(str(year) + "-" + str(week-2) + "-0", "%Y-%W-%w")
result = [(week_start + timedelta(days=x)).day for x in range(0,7)]
result
year, week, dow = datetime.today().isocalendar()
week = week + 1
week_start = datetime.strptime(str(year) + "-" + str(week-2) + "-0", "%Y-%W-%w")
result = [(week_start + timedelta(days=x)).day for x in range(0,7)]
result

rawDescription: Days/dates in a given week

description: Days/dates in a given week


code:
import operator
from functools import reduce
def concatenate(*lists):
    return reduce(operator.add, lists)

rawDescription: concatenate an arbitrary number of lists in a function in Python

description: Concatenate an arbitrary number of lists in a function in Python


code:
expected = selectEdge(positions, positions_u, originalMat, selectedMat)
result = alt_selectEdge(positions, positions_u, originalMat, selectedMat)
assert np.allclose(expected, result)

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


rawDescription: Regex negative matching with python

description: Regex negative matching with python


rawDescription: How to make a save/load game for a text based python rpg?

description: Make a save/load game for a text based python rpg


code:
class OfferView(TemplateView):

    template_name = "generic_app/offers.html"

    def get_context_data(self, **kwargs):
        context = super(OfferView, self).get_context_data(**kwargs)
        context['offers'] = load_offers(self.request)
        return context

rawDescription: Django Template Page Outputting Nothing

description: Django Template Page Outputting Nothing


code:
import Tkinter as Tk
root = Tk.Tk()
root.title('Program')
menuButton = Tk.Button(root, text='Menu')
menuButton.grid(row=0, column=0)
root.mainloop()

rawDescription: Python Tk app - Allow for multiple languages


code:
from sklearn.svm import LinearSVC
from sklearn.calibration import CalibratedClassifierCV
from sklearn.multiclass import OneVsRestClassifier
from sklearn.datasets import make_multilabel_classification

X, Y = make_multilabel_classification(n_classes=2, n_labels=1,
                                      allow_unlabeled=True,
                                      return_indicator=True,
                                      random_state=1)
clf0 = CalibratedClassifierCV(LinearSVC(), cv=10)
clf = OneVsRestClassifier(clf0)
clf.fit(X, Y)
proba = clf.predict_proba(X)

rawDescription: Multiclass linear SVM in python that return probability


code: x = grouped.agg({'Send_Amount':'mean','Pay_Amount':'mean','time_diff':'min','MTCN':'size','Send_Phone':'nunique','Refund_Flag':'count','Send_Amount':lambda txn1 : (txn1.Send_Amount.shift() == txn1.Send_Amount).cumsum()})

rawDescription: python Pandas calling a complex function in groupby.agg

description: Python Pandas calling a complex function in groupby.agg


code:
list0 = ["Test", "Test2", "More text", "Test123", "ttt", "abc", "okokok", "Hello"]
list1 = [ [0, 1], [2], [3], [4,5,6], [7]]
[''.join([list0[i] for i in indices]) for indices in list1]

rawDescription: concatenate strings based on ints from a list

description: Concatenate strings based on ints from a list


code: command = lambda each=each: saver(each)

rawDescription: Store the values of Radiobuttons and Checkbuttons


code: arithOperand <<= Optional('-') + (powerExpr | real | identifier | groupedArithExpr)

rawDescription: Parser failing - pyparsing

description: Parser failing - pyparsing


code:
from subprocess import PIPE,Popen

p = Popen(["ps","-u", numuid], stdout=PIPE)
out, err= p.communicate()
print(out)

rawDescription: How do I show processes for a specific uid or username using command line in python?

description: Show processes for a specific uid or username using command line in python


code:
list2 = [['This'], ['is'], ['a'], ['sentence'], ['I', "'d"], ['like'], ['to'], ['manipulate', '.']]
list1 = ['These', 'were', 'two', 'sentences', 'I', "'d", 'like', 'to', 'read','.']
it = iter(list1)
[[next(it) for i in el] for el in list2]

rawDescription: Python list comprehension to map from flat list to mimic a nested structure


code: s2 = dist[np.arange(4)[:, None], a]

rawDescription: Using NumPy argsort and take in 2D arrays


code: {k: bigdict[k] for k in bigdict.keys() & {'l', 'm', 'n'}}

rawDescription: best way to extract subset of key-value pairs from python dictionary object

description: Extract subset of key-value pairs from python dictionary object


code:
arg_minimas = argrelextrema(new_data, np.less, order=radius)[0] - radius
arg_minimas

rawDescription: numpy how find local minimum in neighborhood on 1darray

description: Numpy how find local minimum in neighborhood on 1darray


rawDescription: Passing multiple value_list in Django

description: Passing multiple value_list in Django


code:
import numpy
n = numpy.random.randint(0, 2, size=(3,3))
n
n.sum()

rawDescription: python count number of ones in a binary image

description: Python count number of ones in a binary image


code: file.write("%s \n %s \n %s \n" % (string1, string2, string3))

rawDescription: Python writing to file multiple lines at once


code:
import xml.etree.ElementTree as ET
context = ET.iterparse('file.xml', events=('end', ))
for event, elem in context:
    if elem.tag == 'row':
        title = elem.find('NAME').text
        filename = format(title + ".xml")
        with open(filename, 'wb') as f:
            f.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
            f.write(ET.tostring(elem))

rawDescription: Splitting XML file into multiple at given tags


code:
x = 5
[paragraph[i: i + x] for i in range(0, len(paragraph), x)]

rawDescription: Python Split string in a certain length

description: Python Split string in a certain length


rawDescription: How to communicate from python script to C# exposed interface?

description: Communicate from python script to C# exposed interface


code:
from functools import partial
test = {"a": {"b": {"c": 1}}}
def itemsetter(item):
    def f(name, value):
        item[name] = value
    return f
mypath = partial(itemsetter(test["a"]["b"]), "c")
mypath(2)
test

rawDescription: Storing dictionary path in Python

description: Storing dictionary path in Python


code:
principal = Principal()
secondary = principal.Secondary()
secondary

rawDescription: How can I acess a metod from an object inside a class in python 2.6?

description: Acess a metod from an object inside a class in python 2.6


rawDescription: I can't read a csv file in Python. The result has many rows instead of cells


code: non_zero_mask = array1 != 0

rawDescription: Replacing entries of an array with those of different array


code:
x = h.heap()
x.size

rawDescription: Simple way to get current memory usage from Guppy


code:
s = np.where(eigenvalues < 0)
eigenvalues[s] = eigenvalues[s] * -1.0
eigenvectors[:,s] = eigenvectors[:,s] * -1.0

rawDescription: Principal Component Analysis in Python: Analytical Mistake


code:
import re

datauri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='

imgstr = re.search(r'base64,(.*)', datauri).group(1)

output = open('output.png', 'wb')

output.write(imgstr.decode('base64'))

output.close()

rawDescription: Load an html5 canvas into a PIL Image with Django


code:
W = r"This is A String With A C:\Windows\Path"
get_paths(W, sep='\\')

rawDescription: Extract path like strings from string

description: Extract path like strings from string


code: monster.x += 1

rawDescription: How to continuously move an image in Pygame

description: Continuously move an image in Pygame


code:
def visit_displaymath(self, node):
    import sphinx.ext.mathjax
    sphinx.ext.mathjax.html_visit_displaymath(self, node)
def depart_displaymath(self, node):
    return
def visit_math(self, node):
    import sphinx.ext.mathjax
    sphinx.ext.mathjax.html_visit_math(self, node)
def depart_math(self, node):
    return

rawDescription: use custom html writer in sphinx

description: Use custom html writer in sphinx


rawDescription: Convert a flat tab-delimited file into Json nested structure


code: table=np.ndarray((9),int) #9 columns in my case

rawDescription: Python: write fitparameters into table

description: Python: write fitparameters into table


code:
import numpy as np
import tensorflow as tf

npc = np.array([[1.,2.],[3.,4.]])
tfc = tf.Variable(npc) # Use variable

row = np.array([[.1,.2]])

with tf.Session() as sess:
    tf.initialize_all_variables().run() # need to initialize all variables

    print('tfc:\n', tfc.eval())
    print('npc:\n', npc)
    for i in range(2):
        for j in range(2):
            npc[i,j] += row[0,j]
    tfc.assign(npc).eval() # assign_sub/assign_add is also available.
    print('modified tfc:\n', tfc.eval())
    print('modified npc:\n', npc)

rawDescription: Tensorflow: How to modify the value in tensor


code:
def animate(i):
    #Make a tuple or list of (x0,y0,c0,x1,y1,c1,x2....)
    newpoints = (matt[i][0],matt[i][1],'r',
                 matt[i][0],matt[i][3],'b',
                 matt[i][2],matt[i][3],'g',
                 matt[i][2],matt[i][1],'y')
    # Use the * operator to expand the tuple / list
    # of (x,y,c) triplets into arguments to pass to the
    # plot function
    animlist = plot(*newpoints,marker='o',markersize=8)
    return animlist

rawDescription: Plot points with different colors in a matplotlib animation


code: lambda name: (name[0], -len(name), name)

rawDescription: Custom sort in Python 3

description: Custom sort in Python 3


rawDescription: Adding dictionary values to a list?

description: Adding dictionary values to a list


code:
def replace_digits(text):
    return re.sub("(-?\d+)|(\+1)", lambda m: str(int(m.group(0)) - 1), text)

rawDescription: Replace numbers in string by respective result of a substraction


code: from flask import request

rawDescription: Context locals - how do they make local context variables global?


code:
def filtered_seqs():
    for seq in skbio.io.read('seqs.fna', format='fasta'):
        if seq.metadata['id'] in ['47P50SDHBQ1PA_0', '4OZ9UI889OL5V_1', '2EC8VWHQD1LW5_2']:
            yield seq

skbio.io.write(filtered_seqs(), format='fasta', into='output.fna')

rawDescription: Write multiple fasta entries using scikit-bio write


code:
from collections import defaultdict
mydict = defaultdict(lambda: "It's an elephant")
print(mydict["a"])

rawDescription: How do I assign the same value for each key?

description: Assign the same value for each key


code:
from dateutil.relativedelta import relativedelta
def next_7am(dt):
    relative_days = (dt.hour >= 7)
    absolute_kwargs = dict(hour=7, minute=0, second=0, microsecond=0)
    return dt + relativedelta(days=relative_days, **absolute_kwargs)

rawDescription: How do I find the next 7am in a timezone

description: Find the next 7am in a timezone


code:
df1
df2
pd.merge(df2, df1, left_index=True, right_index=True)

rawDescription: Inner Join list of DataFrames on Row Values


rawDescription: PyQt5 QIcon.hasThemeIcon(...) always true


code:
with open('results.txt', 'wb', 0) as file:
    subprocess.call(["perl", "myCode.pl"], stdout=file)

rawDescription: Run Perl code (with output to file) from Python


code: {'steve': {'emails': ['steve@steve.com'], 'addresses': ['456 house lane']}, 'bob': {'emails': ['bob@bob.com', '789 house lane'], 'addresses': ['123 house lane', 'bob2@bob2.com']}}

rawDescription: Python Dictionaries: Grouping Key, Value pairs based on a common key, value


code:
def foo(x,y,z):
    return x+y+z

a = [1,2,3]
foo(*a)

rawDescription: Passing several arguments from an array to a function in a easy way


code:
import subprocess

SCRIPT = """/usr/bin/osascript<<END
tell application "Finder"
set desktop picture to POSIX file "%s"
end tell
END"""

def set_desktop_background(filename):
    subprocess.Popen(SCRIPT%filename, shell=True)

rawDescription: How can I programatically change the background in Mac OS X?

description: Programatically change the background in Mac OS X


code: output = [{'x': x, 'y': y} for x, y in zip(*[iter(l)]*2)]

rawDescription: List of dictionaries from pairs in list

description: List of dictionaries from pairs in list


code: node1, node2, weight1 = line.strip().split("; ")

rawDescription: python 3 directed graph with labels from file

description: Python 3 directed graph with labels from file


code:
df
df['sent'] + df['tz_offset'].astype("timedelta64[s]")
df.dtypes

rawDescription: How to add x seconds to a Python datetime64[ns] field?

description: Add x seconds to a Python datetime64[ns] field


code:
def many_line(fname, many=15):
    for i, line in enumerate(open(fname)):
        if i > many:
            return True
    return False

rawDescription: Filter files in a very large folder

description: Filter files in a very large folder


rawDescription: Python Pandas is it possible to find the max value in a generated series without having to store the series into memory?


rawDescription: How to select QTableView index or row from inside of Model

description: Select QTableView index or row from inside of Model


code: model = SVC(probability=True)

rawDescription: How to get a classifier's confidence score for a prediction in sklearn?

description: Get a classifier's confidence score for a prediction in sklearn