code: int(codecs.encode(b'f483', 'hex'), 16)

rawDescription: python 2.7 equivalent of built-in method int.from_bytes

description: Python 2.7 equivalent of built-in method int.from_bytes


code:
it = enumerate(text.split('\n'))
next(i for i, x in it if x and re.search(pattern, x))
'\n'.join(x for _, x in it)

rawDescription: Given a list of strings, how to locate position of first string matching substring using RegEx?


code:
href = link.get('href')
if any(end in href for end in IMAGE_FORMAT):
    # do something
    pass

rawDescription: Python: How to test multiple values inside an if [multiple values] in list:


code:
import re
input = open('path/file').read()
result = re.search(r'.*(string match\s*.*)$', input, re.DOTALL)
print(result.group(1))

rawDescription: python return all lines after last regex match

description: Python return all lines after last regex match


code:
import timeit
import re

if_config_output = """
Mg0_RSP0_CPU0_0 Link encap:Ethernet  HWaddr 70:e4:22:32:53:42
          inet addr:20.200.130.1  Mask:255.255.0.0
          inet6 addr: fe80::72e4:22ff:fe32:5342/64 Scope:Link
          UP RUNNING NOARP MULTICAST  MTU:1514  Metric:1
          RX packets:147918 errors:0 dropped:0 overruns:0 frame:0
          TX packets:119226 errors:0 dropped:0 overruns:0 carrier:3
          collisions:0 txqueuelen:1000
          RX bytes:103741434 (98.9 MiB)  TX bytes:5320623 (5.0 MiB)

Tg0_0_0_7_0 Link encap:Ethernet  HWaddr 78:ba:f9:35:66:46
          inet addr:13.13.13.1  Mask:255.255.255.0
          inet6 addr: fe80::7aba:f9ff:fe35:6646/64 Scope:Link
          UP RUNNING NOARP MULTICAST  MTU:1514  Metric:1
          RX packets:26 errors:0 dropped:0 overruns:0 frame:0
          TX packets:5058 errors:0 dropped:0 overruns:0 carrier:3
          collisions:0 txqueuelen:1000
          RX bytes:1832 (1.7 KiB)  TX bytes:454625 (443.9 KiB)
"""

ma = re.compile("^\s?(\S+).*?inet addr:(\S+).*?Mask:(\S+)", re.MULTILINE|re.DOTALL)

def split(paragraph):
    """ ugly, but faster """
    interface = paragraph.split(" Link ")[0]
    inet_mask = paragraph.split("\n")[1].split(':')
    ip, mask = inet_mask[1], inet_mask[2]
    return [interface, ip, mask]

def regex(paragraph):

    result = ma.match(paragraph)
    if result:
        result = ma.match(paragraph)
        interface = result.group(1)
        ip = result.group(2)
        mac = result.group(3)
        return [interface, ip, mac]

def test_split():
    c = []
    for paragraph in if_config_output.split('\n\n'):
        c.append(split(paragraph))
    return len(c)

def test_regex():
    c = []
    for paragraph in if_config_output.split('\n\n'):
        c.append(regex(paragraph))
    return len(c)

print ("split", timeit.timeit(stmt=test_split, number=100000))
print ("regex", timeit.timeit(stmt=test_regex, number=100000))

rawDescription: Parsing ifconfig output with python

description: Parsing ifconfig output with python


code:
class MyView(generics.GenericAPIView):
    pagination_serializer_class = YourCustomPaginationSerializerClass

rawDescription: "get_paginated_response" in django-rest-framework 3.0


rawDescription: Round Integers in Python

description: Round Integers in Python


code:
#!/usr/bin/python
from sys import stdin, stdout

labels = [
    "Reading Comprehension", "Sentence Skills", "Arithmetic",
    "College Level Math", "Elementary Algebra"
]

for line in stdin:
    values = line.strip().split(',')
    stdout.write(','.join(values[:5]))
    for label in labels:
        stdout.write(',')
        stdout.write(next((i for i in values[5:] if i.startswith(label)), ''))
    stdout.write('\n')
stdout.flush()

rawDescription: Reorder Columns by String Variable

description: Reorder Columns by String Variable


code:
def __new__(self, tup, gridsize=100):
    return super(Point, self).__new__(self, (x % gridsize for x in tup))

rawDescription: python: representing square grid that wraps on itself (cylinder)

description: Python: representing square grid that wraps on itself (cylinder)


code: print (b),

rawDescription: Print horizontal with for in Python 2.7

description: Print horizontal with for in Python 2.7


rawDescription: Sort inter-dependant elements of a dictionary


code:
import re
re.sub(r'\s+', '-', word)

rawDescription: Inserting hyphens in python strings

description: Inserting hyphens in python strings


code:
y = stats.uniform.rvs(size = 100)
stats.normaltest(y)

rawDescription: Scipy Normaltest how is it used?

description: Scipy Normaltest how is it used


rawDescription: NLTK RegEx Chunker not capturing defined grammar patterns with wildcards


code:
def makeCoordinateMatrix(*coords) :
    dims = len(coords)
    coords = [np.array(a) for a in coords]
    shapes = tuple([len(a) for a in coords])
    ret = np.zeros(shapes + (dims,))
    for j, a in enumerate(coords) :
        ret[..., j] = a.reshape((len(a),) + (1,) * (dims - j - 1))
    return ret

coordinateMatrix = makeCoordinateMatrix(mapLatitude, mapLongitude,
                                        mapAltitude, mapTime)

rawDescription: Python: speed up matrix coordinate mapping through iteration


code: x.minutes = 40

rawDescription: Map variables to dictionary values, and call with reference to key?


code:
def shortsword():
    return randint(2, 7)

damage = shortsword()

rawDescription: Storing the value of a randomly generated integer


code:
results = []
for i in range(runs):
    results.append(model_solve(100))

rawDescription: Collecting results from a loop that returns NumPy Arrays


rawDescription: Accessing rows of an array, inside an array of arrays?


code:
df2 = df.pivot(index="time", columns="machine", values="status")
df2 = df2.fillna(method='ffill')
both_up = df2[(df2 == "up").all(axis=1)]

rawDescription: Detection of concurrent event appearances - pandas and DataFrame, but possibly pure-python related


code:
name = data1['item_list'][0]['name']['en']
description = data1['item_list'][0]['description']['en']
mag_cutter = Weapon(name=name, description=description,
                    **data['weapon_datasheet_list'][0])

rawDescription: Use Json data to initialize an object in python?


code:
df
copy.ix[0,'a'] = 100
copy
df

rawDescription: Assigning to parent DataFrame affects child DataFrame?


code:
from pprint import pprint
from itertools import chain
flatten = chain.from_iterable
ans = [list(flatten(c)) for i in range(2, len(lis)+1) for c in permutations(lis,i)]
pprint(ans)

rawDescription: How to use combinations

description: Use combinations


code:
class Foo(object):
    whatever = 'Hey Dawg!'

class Bar(object):
    whatever = 'I satisfy the interface too!'

rawDescription: When does a passed class instance require an import in python


code:
import dis
def test():
    ''.join([1,2,3])

dis.dis(test)

rawDescription: How to patch method ''.join using the mock library

description: Patch method ''.join using the mock library


rawDescription: How to concatenate strings in multiple lists at the same index

description: Concatenate strings in multiple lists at the same index


code:
from pprint import pprint
pprint(list(recursive_flatten(sample)))

rawDescription: Python recursion with dicts

description: Python recursion with dicts


rawDescription: How to print non-ascii characters to file in Python 2.7

description: Print non-ascii characters to file in Python 2.7


code:
import numpy as np
# define the lower and upper limits for x and y
minX, maxX, minY, maxY = 0., 20000., 10000., 50000.
# create one-dimensional arrays for x and y
x = np.linspace(minX, maxX, (maxX-minX)/2000.+1)
y = np.linspace(minY, maxY, (maxY-minY)/2000.+1)
# create the mesh based on these arrays
X, Y = np.meshgrid(x, y)

rawDescription: How to create matrix of points by X, Y coordinate in Python?

description: Create matrix of points by X, Y coordinate in Python


code: elapsed = now - dt

rawDescription: Calculate elapsed time

description: Calculate elapsed time


code:
contacts = {'Jennifer Craig': [30, Female], 'John Doe': [40, 'Male']}
contacts['Jennifer Craig']

rawDescription: Defining a variable with pre-entered information


code:
for root, dirs, files in os.walk(top_level_folder, topdown=True):
    if root != top_level_folder:
        # only recurse into level 3+ directories with the desired names
        dirs[:] = [d for d in dirs if d in ['inbox', 'sent']]
    if root.lower().endswith("inbox") or root.lower().endswith("sent"):
        for fn in files:
            with open(os.path.join(root, fn), 'r') as f:
                pass  # do something

rawDescription: Only enumerate files in folders with specific names


rawDescription: shorten the weekdays from texts

description: Shorten the weekdays from texts


rawDescription: Not sure why key press is not doing anything


code:
line = 'xxxx'
CONFIG = default_deconfig

if line == 'AAA':
    CONFIG =  AAA_defconfig
elif line == 'CCC':
    CONFIG =  CCC_defconfig
...

rawDescription: python to uncomment the right line

description: Python to uncomment the right line


code:
a = A()
a.logout
a.version = '2.0'
a.logout

rawDescription: python global decorator for class attributes

description: Python global decorator for class attributes


code: PREPEND_WWW = True  # Default value is False

rawDescription: Django Method of Forwarding Non-www to www?


code: crd = np.vstack((np.zeros_like(ax.get_yticks()), ax.get_yticks())).T

rawDescription: matplotlib get axis-relative tick positions

description: Matplotlib get axis-relative tick positions


code: master = [index_map.get(index, []) for index in range(max(index_map)+1)]

rawDescription: make new python lists with indexes from items in a single list

description: Make new python lists with indexes from items in a single list


code:
detected
track

rawDescription: regex: find all words with certain letters but not other

description: Regex: find all words with certain letters but not other


code:
def ordered_merge(lists, selector):
    its = [iter(l) for l in lists]
    for i in selector:
        yield next(its[i])

rawDescription: Merge two or more lists with given order of merging


code:
from flask import request
from werkzeug import url_encode

@app.template_global()
def modify_query(**new_values):
    args = request.args.copy()

    for key, value in new_values.items():
        args[key] = value

    return '{}?{}'.format(request.path, url_encode(args))

rawDescription: Modify query parameters in current GET request for new url


code:
import ImageChops

def equal(im1, im2):
    return ImageChops.difference(im1, im2).getbbox() is None

rawDescription: python code to compare images in python

description: Python code to compare images in python


code:
from smartfields import fields

class UserProfile(models.Model):
    avatar = fields.ImageField(upload_to='avatars', blank=True)

rawDescription: Django: how to automatically also delete file from storage when Clear Checkbox ticked?


code:
for i,c in enumerate('bob'):
    print('{}: {}'.format(c,i))

b: 0
o: 1
b: 2

rawDescription: Iterating over strings in python

description: Iterating over strings in python


code:
class Movie(Entity):
    title = Field(Unicode(30))
    year = Field(Integer)
    description = Field(UnicodeText)

rawDescription: is there an easy/efficient way to make a mysql database dynamically 'build it's own structure' as it saves name/value pairs to disc?

description: Is there an easy/efficient way to make a mysql database dynamically 'build it's own structure' as it saves name/value pairs to disc


code:
import win32gui
import win32con

rawDescription: How do I get the URL of the active Google Chrome tab in Windows?

description: Get the URL of the active Google Chrome tab in Windows


code:
import StringIO
s = 'Hello, World!'
sio = StringIO.StringIO(s)
sio.read(6)
sio.read()

rawDescription: How to remove first 4 bytes from s string in python

description: Remove first 4 bytes from s string in python


code:
def pre_process(dict_sequence):
    for d in dict_sequence:
        d['time'] = date2num(datetime.datetime.strptime(d['time'],"%d/%m/%y %H:%M:%S" ))
    yield d

rawDescription: How to convert an array of dates (format 'mm/dd/yy HH:MM:SS') to numerics?

description: Convert an array of dates (format 'mm/dd/yy HH:MM:SS') to numerics


code:
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon

point = Point(0.5, 0.5)
polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
print(polygon.contains(point))

rawDescription: What's the fastest way of checking if a point is inside a polygon in python


code:
for number, word in zip(list1, list2):
    print(number, word)

rawDescription: List indexing in Python with duplicates

description: List indexing in Python with duplicates


code:
def index_2d(myList, v):
    for i, x in enumerate(myList):
        if v in x:
            return (i, x.index(v))

rawDescription: Python: Return 2 ints for index in 2D lists given item


rawDescription: Last function code of 8puzzle in Python

description: Last function code of 8puzzle in Python


code:
replace_char("
Santa is fat
")
Out[457]: 'lt;pgt;Santa is fatlt;/pgt;'

rawDescription: Replacing characters in a string and returning in python


code:
app = Eve()
app.run()

rawDescription: Can't reach Eve REST API

description: Can't reach Eve REST API


rawDescription: Numpy, how to convert a 2D array to 3D (by grouping cols to 2 list)


code:
id = ['1','1','1','2','2','2','3','3','3']
a  = [1,2,3,4,5,6,7,8,9]
b  = [10,11,12,13,14,15,16,17,18]
c  = [20,21,22,23,24,25,26,27,28]

from collections import defaultdict
d = defaultdict(list)

# add as many lists as needed, here n == 3
lsts = [a, b, c]

for ki, kl in zip(id, zip(*lsts)):
    d[ki] += [kl]

for k, v in d.items():
    # if you don't mind using tuples, simply do this: d[k] = zip(*v)
    d[k] = map(list, zip(*v))

rawDescription: convert n equal length lists to dictionary with unique keys from one list

description: Convert n equal length lists to dictionary with unique keys from one list


code:
N = 1000
df = pd.DataFrame(np.random.randint(0, 10, (N, 3)), columns="A B C".split())
df.head()

rawDescription: How to find the top 10 pairs that appear the most in a pandas dataframe in python

description: Find the top 10 pairs that appear the most in a pandas dataframe in python


rawDescription: How to model a one-to-many?

description: Model a one-to-many


rawDescription: Parsing bits from a 128 byte block of hex in Python


code:
self.hand1 = Hand()
self.hand1.name = "hand 1"

rawDescription: Python: how to refer to an instance name?


code:
class Question(QtGui.QWidget):
    def __init__(self, label, parent=None):
        super(Question, self).__init__(parent)
        question = QtGui.QLabel(label)
        ...

question1 = Question('What is 5+5?', self)
question2 = Question('What is 45+10?', self)

rawDescription: How do I show a Test_Question (String) per page?? (PyQt/Python)

description: Show a Test_Question (String) per page?? (PyQt/Python)


code:
lst = []
for y in range(size):
    lst.append([' '] * size)

rawDescription: Python - Random output has a structure

description: Python - Random output has a structure


code:
import cv2
import numpy
img = cv2.imread("zebra.jpg")
triangle = numpy.array([[300, 0], [399, 0], [399, 100]])
color = [255, 255, 255] #white
cv2.fillConvexPoly(img, triangle, color)
cv2.imwrite("with_triangle.jpg", img)

rawDescription: Removing the upper corner part of the image


rawDescription: In Python, how do you find the index of the first value greater than a threshold in a sorted list?


code:
main_batch = pyglet.graphics.Batch()
background = pyglet.graphics.OrderedGroup(0)
# stuff_above_background = pyglet.graphics.OrderedGroup(1)
# ...

rawDescription: Pyglet Image Rendering

description: Pyglet Image Rendering


code:
for i in range(0,10):
    checkData.append(BooleanVar())
    conditionID.append(i)
    # we define a new function (10 times)
    # i is resolve at function definition (now)
    def call_onCheck(index=i):
        # the arguments of onCheck are resolved at function execution.
        # it will take what is in the lists at the execution time.
        # it may change or not (in your case : not)
        return onCheck(conditionID[index], checkData[index])
    l = ttk.Checkbutton(root, text ="",variable=checkData[i],command=call_onCheck, onvalue=True, offvalue=False)
    w=Message(root,background='ivory',text="test" + str(i),width=60)
    l.grid(column=1,row=i+1)
    w.grid(column=2,row=i+1)

rawDescription: Issue with generating ttk checkboxes in loops and passing arguments


code:
from inspect import getmembers
print( getmembers( clf.tree_ ) )

rawDescription: How do I find which attributes my tree splits on, when using scikit-learn?

description: Find which attributes my tree splits on, when using scikit-learn


code:
import struct

def u2s(v):
    return struct.unpack("i", struct.pack("I", v))[0]

def s2u(v):
    return struct.unpack("I", struct.pack("i", v))[0]

rawDescription: Sneaking unsigned values from Jython, through Java, to C and back again


code:
df['timeline']=df.index.to_native_types()
df.to_dict('records')
[{'timeline': '2014-10-01', 'total_prescriptions': 17.0},
 {'timeline': '2014-11-01', 'total_prescriptions': 14.0},
 {'timeline': '2014-12-01', 'total_prescriptions': 8.0},
 {'timeline': '2015-01-01', 'total_prescriptions': 4.0},
 {'timeline': '2015-02-01', 'total_prescriptions': 0.0},
 {'timeline': '2015-03-01', 'total_prescriptions': 10.0},
 {'timeline': '2015-04-01', 'total_prescriptions': 3.0}]

rawDescription: Fill missing timeseries data using pandas or numpy


code:
compCards = [ranCompCard, ranCompCard2]
while sum(compCards) < 15:
    compCards.append(random.choice(availableCards))

rawDescription: Python Blackjack Game how to carry a variable in a while loop


code:
cur1 = self.curr_start1.get()
cur2 = self.curr_start2.get()
amount = self.currAmount1.get()

rawDescription: Problems with tk entry and optionmenu widget in currency converter


code:
for (a,b) in zip(list1, list2):
  doSomething(a)
  doSomething(b)

rawDescription: Is there a way to have parallel for-each loops?


code:
parser = qparser.QueryParser("fieldname", my_index.schema)
parser.remove_plugin_class(qparser.PhrasePlugin)
parser.add_plugin(qparser.SequencePlugin())

rawDescription: python fuzzy text search

description: Python fuzzy text search


code: "SELECT * FROM {tablename} WHERE {field} LIKE '%{keyword}%'".format(**{"tablename":"UserTable","field":"NameField","keyword":"Wuliang"})

rawDescription: Use placeholder to delete rows code in mysql with python mysqldb


code:
class foo:
    def __init__(self, position=(0.0, 0.0), velocity=(1.0, 1.0)):
        self.position = vec2()
        self.velocity = vec2(*velocity)

    def update(self, dt):
        if isinstance(dt, tuple):
            dt = vec2(*dt)
        self.position += self.velocity * dt;

rawDescription: Method argument conversion: 'tuple' has no attribute 'attribute'


rawDescription: Assign new values to slice from MultiIndex DataFrame


code:
from operator import itemgetter
sorted(z, key=itemgetter(1))  # Sort by second item
sorted(z, key=itemgetter(2))  # Sort by third item

rawDescription: Sort multiple lists simultaneously

description: Sort multiple lists simultaneously


code:
class pagesByUrl(dict):
    "a cross reference of pages by url rather than object name"
    def __init__(self):
        dict.__init__(self)
        for page in dir(xxxPages):
            try:
                pgAttr=getattr(xxxPages, page)
                pg=pgAttr('dummybrowser')
                self[pg.url] = page
            except (KeyError, TypeError, AttributeError):
                pass

rawDescription: create a dictionary of class names by an attribute of each class

description: Create a dictionary of class names by an attribute of each class


code: video_url: '(.*)'

rawDescription: How to match string between '', that's followed by "video_url:" text

description: Match string between '', that's followed by "video_url:" text


code:
class Classname:
   def foo(self): pass

for name, fn in inspect.getmembers(Classname):
    if isinstance(fn, types.UnboundMethodType):
        setattr(Classname, name, decorator(fn))

rawDescription: python apply decorator to every method in a class without inspect

description: Python apply decorator to every method in a class without inspect


rawDescription: Create multiindex based on single index

description: Create multiindex based on single index


code:
import urllib
from scrapy.selector import Selector
url = 'http://www.propertyfinder.ae/en/buy/villa-for-sale-dubai-jumeirah-park-1849328.html?img/0'
h = urllib.urlopen(url).read()
root = Selector(text=h, type='html')
for url in root.xpath(".//*[starts-with(@id, 'propertyPhoto')]//img/@src").extract():
    print(url)

rawDescription: xpath works for just the first image

description: Xpath works for just the first image


code:
io = []
with open('input.txt') as file_:
    for line in file:
        key, value = line.rsplit(' | ', 1)
        io.append(tuple(key, value))

rawDescription: How do I use regular expressions in Python with placeholder text?

description: Use regular expressions in Python with placeholder text


code:
def read_features_from_file(filename):
    """ Read feature properties and return in matrix form. """
    if os.path.getsize(filename) <= 0:
        return np.array([]), np.array([])
    f = np.load(filename)
    if f.size == 0:
        return np.array([]), np.array([])
    f = np.atleast_2d(f)
    return f[:,:7], f[:,7:] # feature locations, descriptors

def write_features_to_file(filename, locs, desc):
    np.save(filename, np.hstack((locs,desc)))

rawDescription: Store the extracted SURF descriptors and keypoints in *.npy file


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot(range(10), color='red', lw=3, zorder=4)
# Placing the text in figure coordinates
ax.text(0.5, 0.5, 'Test', color='white', fontsize=45, transform=fig.transFigure,
        bbox={'facecolor':'black', 'pad':12})

plt.show()

rawDescription: How to put pylab.plot line over pylab.figtext?

description: Put pylab.plot line over pylab.figtext


code: list3 = list(set(list1)-set(list2))

rawDescription: In Python, how can I randomly chose an element of one list that's NOT in a second list?


code:
from django.utils import translation
translation.activate('fr')
reverse('produits_index')    # /fr/produits/
translation.activate('en')
reverse('produits_index')    # /en/products/

rawDescription: Django i18n_patterns: resolve() doesnt work as expected


code:
# This list comprehension filters out the non-seen vowels.
items = [item for item in aeiou.items() if item[1] > 0]

# Note that items looks something like this:  [('a', 3), ('b', 2), ...]
# so an item that gets passed to the key function looks like
# ('a', 3) or ('b', 2)
most_common = max(items, key=lambda item: item[1])
least_common = min(items, key=lambda item: item[1])

rawDescription: Python string vowel counter

description: Python string vowel counter


rawDescription: Calculate the elapsed time in python

description: Calculate the elapsed time in python


code:
with open("...", "wb") as out:
  xml = XmlWriter(out)
  xml.addNamespace("xhtml", "http://www.w3.org/1999/xhtml")
  xml.startTag("xhtml:html")
  xml.startTag("xhtml:body")
  xml.text("Hello world!")
  xml.tag("xhtml:img", {"src": "smile.png", "alt": ":-)"})
  xml.endTag()
  xml.endTag()
  xml.close()

rawDescription: Writing XML from Python : Python equivalent of .NET XmlTextWriter?


code:
import functools
print_with_hello = functools.partial(print, "Hello")
print_with_hello("World")
print_with_hello()

rawDescription: Python - Store function with parameters

description: Python - Store function with parameters


code: [x**2 for x in range(5)]

rawDescription: Difference between map and dict

description: Difference between map and dict


code:
g = df.groupby(['id', 'value'])
res = g['Time'].agg({'first': 'first', 'last': 'last'})
res = g['Time'].agg({'enter': 'first', 'exit': 'last'})
res['time_diff'] = res['exit'] - res['enter']
res

rawDescription: Pandas DataFrame groupby two columns and get first and last


rawDescription: Launch a webpage on a Firefox (win) tab using Python


code:
import pandas as pd
from matplotlib import rcParams
import matplotlib.pyplot as plt
from operator import itemgetter

rcParams.update({'figure.autolayout': True})
plt.figure(figsize=(14,9), dpi=600)

reso_names = ['A','B','C','D','E','F','G','H']
reso_values = [5,7,3,8,2,9,1,3]

N=3
sublists_names = [reso_names[x:x+N] for x in range(0, len(reso_names), N)]
sublists_values = [reso_values[x:x+N] for x in range(0, len(reso_values), N)]

size = int(len(reso_values))
fig, axs = plt.subplots(nrows=size//N+1, sharey=True, figsize=(14,18), dpi=50)

fig.suptitle('Graph',
          **{'family': 'Arial Black', 'size': 22, 'weight': 'bold'})

for ax, names, values in zip(axs, sublists_names, sublists_values):
    ax.bar(range(len(values)), values, align='center')
    ax.set_xlabel('X-Axis')
    ax.set_ylabel('Y-Axis')
    ax.set_xticks(range(len(names)))
    ax.set_xticklabels(names, rotation='vertical')
    ax.set_xlim(0, len(names))
    #ax.set_xlim(0, N)

fig.subplots_adjust(bottom=0.05, top=0.95)
plt.show()

rawDescription: Python Matplotlib: Splitting one Large Graph into several Sub-Graphs (Subplot)


code:
def set_foos(cls):
    foos = []
    for base in cls.__bases__:
        if hasattr(base, 'foos'):
            foos.extend(base.foos)
    cls.foos = foos + getattr(cls, 'foos', [])
    return cls

class FooClass(object):
    foos = ['foo', 'bar']

@set_foo
class SpecialFoo(FooClass):
    foos = ['spec']

rawDescription: Append to a member list when subclassing in Python


code:
list_of_strings = ['abc', 'def', 'ghi'] # give a list of strings

new_string = "".join(list_of_strings)   # join them into a new string

rawDescription: Python - Combine all items in a list into a string


code:
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.viewcode',
    'rst2pdf.pdfbuilder'
]

rawDescription: sphinx not to include source code during build

description: Sphinx not to include source code during build


code: df['B'] = df.groupby('A')['B'].transform(lambda x: 'Y' if x.nunique() > 1 else x)

rawDescription: Pandas conditionally replace value if >1 unique values for other column


rawDescription: Using Xpath in Scrapy to select any text below paragraph


code:
@app.route('/as/<keyword>', methods=['GET'])
@cache.cached(timeout=2592000)
@db_session
def auto_suggest(keyword):
    job = q.enqueue(find_keyword, keyword)
    while not job.result:
        time.sleep(1)
    return jsonify(word=job.result)

rawDescription: Storing a calculation in a flask route cache


code:
def jewel_list(lines):
    jewels = []
    for item in lines:
        jewels.append(item.split())
    jewels = sorted(jewels, reverse= True)
    jewel_dict = {}
    for item in jewels:
        jewel_dict[int(item[1])] = item[0]  # changed line
    return jewel_dict

rawDescription: Python Greedy Algorithm

description: Python Greedy Algorithm


code:
...
fd = open("report/path/report.csv")
report = fd.read()
...

rawDescription: Export a template information into an Excel and then download it in django


code:
#!/usr/bin/python
import apsw, random as rand, time

def populate(cu):
    cu.execute("""
CREATE TABLE feature ( -- 300k
    feature_id INTEGER PRIMARY KEY,
    mzMin DOUBLE, mzMax DOUBLE,
    rtMin DOUBLE, rtMax DOUBLE,
    lnk_feature INT);
CREATE TABLE spectrum ( -- 20k
    spectrum_id INTEGER PRIMARY KEY,
    mz DOUBLE, rt DOUBLE,
    lnk_spectrum INT);""")
    cu.execute("BEGIN")
    for i in range(300000):
        ((mzMin, mzMax), (rtMin, rtMax)) = (get_min_max(), get_min_max())
        cu.execute("INSERT INTO feature VALUES (NULL,%s,%s,%s,%s,%s)"
                    % (mzMin, mzMax, rtMin, rtMax, get_lnk()))
    for i in range(20000):
        cu.execute("INSERT INTO spectrum VALUES (NULL,%s,%s,%s)"
                    % (get_in_between(), get_in_between(), get_lnk()))
    cu.execute("COMMIT")
    cu.execute("ANALYZE")

def get_lnk():
    return rand.randint(1, 2)

def get_min_max():
    return sorted((rand.normalvariate(0.5, 0.004),
                   rand.normalvariate(0.5, 0.004)))

def get_in_between():
    return rand.normalvariate(0.5, 0.49)

def select(cu):
    sql = """
    SELECT feature_id, spectrum_id FROM spectrum, feature
    WHERE lnk_feature = lnk_spectrum
        AND rt >= rtMin AND rt <= rtMax
        AND mz >= mzMin AND mz <= mzMax"""
    start = time.time()
    cu.execute(sql)
    print ("%s rows; %.2f seconds" % (len(cu.fetchall()), time.time() - start))

cu = apsw.Connection('foo.db').cursor()
populate(cu)
select(cu)

rawDescription: Very slow select query, how can I speed this up?


code:
import types
isinstance(add, types.FunctionType)

rawDescription: How to check the type of an object against the type "function"

description: Check the type of an object against the type "function"


code:
Movie(title=u"Blade Runner", year=1982)
session.commit()

rawDescription: is there an easy/efficient way to make a mysql database dynamically 'build it's own structure' as it saves name/value pairs to disc?


code:
text ="(CLAUSE (NP Jack/NNP) (VP stayed/VBD) (NP in/IN London/NNP))"
tree = nltk.Tree.fromstring(text, read_leaf=lambda x: x.split("/")[0])
print(tree.leaves())

rawDescription: How can I remove POS tags before slashes in nltk?

description: Remove POS tags before slashes in nltk


code:
############ username case-insensitivity ############
class iunicode(unicode):
    def __init__(self, value):
        super(iunicode, self).__init__(value)
        self.value = value

    def __eq__(self, other):
        if isinstance(other, str) or isinstance(other, unicode):
            return self.value.lower() == other.lower()
        if isinstance(other, self.__class__):
            return other == self.value

def custom_getattribute(self, name):
    val = object.__getattribute__(self, name)
    if name == "username":
        val = iunicode(val)
    return val

def auth_user_save(self, *args, **kwargs): # Ensures lowercase usernames
    username = self.username
    if username and type(username) in [unicode, str, iunicode]:
        self.username = username.lower()   # Only lower case allowed
    super(User, self).save(*args, **kwargs)

User.__getattribute__ = custom_getattribute
User.save = MethodType(auth_user_save, None, User)
#####################################################

rawDescription: Django : Case insensitive matching of username from auth user?


code:
ABC
xABC
AxBC
ABxC
xxABC
xAxBC
xABxC
AxxBC
AxBxC
ABxxC

rawDescription: Generating combinations of two strings using Python


rawDescription: How to unzip lists in lists in a list

description: Unzip lists in lists in a list


code:
from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.found_links = []

    def handle_starttag(self,tag,attrs):
        if tag=="a":
            attrs = dict(attrs)
            if "href" in attrs and attrs["href"] not in self.found_links:
                self.found_links.append(attrs["href"])

def main():
    parser = MyHTMLParser()
    with open("index.html") as f:
        contents = f.read()
    parser.feed(contents)
    with open("index_link.txt","w") as f:
        f.write('\n'.join(parser.found_links) + '\n')
    with open("textfile.html","w") as f:
        f.write(contents)

if __name__=="__main__":
    main()

rawDescription: How to remove duplicate lines from a file and writing them in file in Python

description: Remove duplicate lines from a file and writing them in file in Python


code:
import numpy as np
import scipy.signal

def cross_image(im1, im2):
   # get rid of the color channels by performing a grayscale transform
   # the type cast into 'float' is to avoid overflows
   im1_gray = np.sum(im1.astype('float'), axis=2)
   im2_gray = np.sum(im2.astype('float'), axis=2)

   # get rid of the averages, otherwise the results are not good
   im1_gray -= np.mean(im1_gray)
   im2_gray -= np.mean(im2_gray)

   # calculate the correlation image; note the flipping of onw of the images
   return scipy.signal.fftconvolve(im1_gray, im2_gray[::-1,::-1], mode='same')

rawDescription: How to detect a shift between images

description: Detect a shift between images


rawDescription: Unable to scrape the text from a certain LI element


code:
import itertools as it

for key, values in original.items():
    target.update(zip(values, it.repeat(key)))

rawDescription: What is the pythonic way to reverse a defaultdict(list)?


code:
def dispatchTable( klass, prefix ):
    """
    Given a class and a method prefix string, collect all methods in the class
    that start with the prefix, and return a dict mapping from the part of the
    method name after the prefix to the method itself.

    e.g. you have a class Machine with methods opcode_foo, opcode_bar.
    create_dispatch_table( Machine, "opcode_" )
    yields a dict
    { "foo": Machine.opcode_foo, "bar": Machine.opcode_bar }
    """

    dispatch = {}
    for name, fun in inspect.getmembers( klass, inspect.ismethod ):
        if name.startswith(prefix):
            # print "found %s.%s"%(k.__name__,name)
            dispatch[ name.split(prefix)[1] ] = fun

    return dispatch

rawDescription: String vs. Enum for checking type of object in Python


rawDescription: Interchange ordering of 4-D Numpy array

description: Interchange ordering of 4-D Numpy array


code:
lhor = ax.axhline (0.5)
lver = ax.axvline (1)
def OnOver2(event):
   lhor.set_ydata(event.ydata)
   lver.set_xdata(event.xdata)
   plt.draw()

rawDescription: How can I delete plot lines that are created with Mouse Over Event in Matplolib?

description: Delete plot lines that are created with Mouse Over Event in Matplolib


code:
if hasattr(value, '__call__'):
    value = value()

rawDescription: Python getattr() member or function?

description: Python getattr() member or function


code: ratings = {team: [1500] for team in teams}

rawDescription: Python: How to have a user reference and access a variable?


code:
class X:
    name = 'bob'
    roll = 4

c = list()
c.append(X())
c[0].name = 'sam'
c[0].roll = 10

rawDescription: How use structures with arrays in python


code:
grouped = df1['DateTime'].groupby(df1['DateTime'].dt.to_period('M'))

grouped = df1['DateTime'].groupby(df1['DateTime'].dt.month)  # if you want Jan-2015 == Jan-2014

rawDescription: Plot bar graph using multiple groupby count in panda


code:
import urllib.parse as parse

paramstr = 'orderby=alphabetical&other=param&page=1234'
params = parse.parse_qsl(paramstr)
params = [(name, val) for name, val in params if name != 'page']
print(parse.urlencode(params))

rawDescription: Remove a parameter from string

description: Remove a parameter from string


code:
x
y

rawDescription: what is the equivalent of Matlab's typecast function in R / Python / Julia

description: What is the equivalent of Matlab's typecast function in R / Python / Julia


code:
import time,threading
interval = 5
next_run = 0
interruptEvent = threading.Event()
while True:
   interruptEvent.wait(max(0, next_run - time.time()))
   interruptEvent.clear()

   next_run = time.time() + interval
   action_print()

rawDescription: python process  takes 100% CPU

description: Python process  takes 100% CPU


code:
import shelve
kvdict = shelve.open('keywords')

rawDescription: Python : text replacemnt in two files using a keyword?


code: string = string.split(',', 1)[0]

rawDescription: How to delete some characters from a string by matching certain character in python

description: Delete some characters from a string by matching certain character in python


code: employee_expenses = Employee.objects.get(name='John Doe').expenses.all()

rawDescription: django model foreignkeys question

description: Django model foreignkeys question


code:
def normfilter(vecs, min_norm):
    for x,y in vecs:
        n = (x**2.+y**2.)**-0.5
        if min_norm < n:
            yield (x*n,y*n)

normalized = list(normfilter(vectors, 0.4))

rawDescription: Intermediate variable in a list comprehension for simultaneous filtering and transformation


code: df

rawDescription: How to df.groupby(cols).apply(my_func) for some columns, while leave a few columns not tackled?

description: Df.groupby(cols).apply(my_func) for some columns, while leave a few columns not tackled


code:
while row_num <= NUMBER_OF_FRAGMENTS:
        content_of_line = scoring_file.readline()
        if row_num == 0:
            content_of_line = scoring_file.readline()

rawDescription: how to skip the first line of a file in python

description: Skip the first line of a file in python


code:
needles = [
    "ls: cannot access fepu/*.elf: No such file or directory",
    "ls: cannot access mpu/*.elf: No such file or directory",
    "ls: cannot access sbmu/*.elf: No such file or directory",
]

rawDescription: How to cut short a long 'if' statement with multiple logical AND in Python?

description: Cut short a long 'if' statement with multiple logical AND in Python


code:
bytearray(int(x,16) for x in u.split())
Out[14]: bytearray(b'\x01\xa02\x00\x00\x00\x00\xfe\x12o\x04')

rawDescription: Transform string in a list with elements separated on Python


code:
p = Path('/etc')
q = p / 'init.d' / 'reboot'
q
q.resolve()

rawDescription: Is there a function corresponding to "\" in python?


code:
def __repr__(self):
    return '<Stats: description=%r, mystat=%r>' % (self.description, self.mystat)

rawDescription: Python __repr__ and None

description: Python __repr__ and None


code:
import lxml.etree as ET

content = '''\
<root xmlns:xsi="http://www.xxx.com/zzz/yyy" xmlns:idx="http://www.belscript.org/schema/index">
<idx:index xsi:schemaLocation="http://www.belscript.org/schema/index index.xsd" idx:belframework_version="2.0">
   <idx:namespaces>
      <idx:namespace idx:resourceLocation="http://resource.belframework.org/belframework/1.0/namespace/entrez-gene-ids-hmr.belns"/>
      <idx:namespace idx:resourceLocation="http://resource.belframework.org/belframework/1.0/namespace/hgnc-approved-symbols.belns"/>
      <idx:namespace idx:resourceLocation="http://resource.belframework.org/belframework/1.0/namespace/mgi-approved-symbols.belns"/>
      </idx:namespaces>
      </idx:index>
      </root>
      '''

root = ET.XML(content)
namespaces = {'xsi': 'http://www.xxx.com/zzz/yyy',
              'idx': 'http://www.belscript.org/schema/index'}
for item in root.xpath(
    '//*[local-name()="namespace"]/@idx:resourceLocation', namespaces=namespaces):
    print(item)

rawDescription: XPath - Return ALL nodes with certain string pattern


code: data_url = 'data:image/jpg;base64,' + base64.b64encode(im_data)

rawDescription: Is it possible to create encodeb64 from Image object?


code:
my_string = "This is a bytestring"
my_unicode = u"This is an Unicode string"

rawDescription: Unicode in python with Django and MongoEngine


rawDescription: using 3 variables in the beginning of an IF statement in python

description: Using 3 variables in the beginning of an IF statement in python


code:
class Getdata(models.Model):
    title = models.CharField(max_length=255, unique=True)
    state = models.CharField(max_length=2, choices=STATE, default="0")
    name = models.ForeignKey(School)
    created_by = models.ForeignKey(profile)

rawDescription: Django models avoid duplicates

description: Django models avoid duplicates


code:
for i, k in enumerate(sorted(d1.keys()), 1):
    print('table', i,  *d1[k])

rawDescription: How to create a function that loops through both the key and item of a dictionary using variables in Python?

description: Create a function that loops through both the key and item of a dictionary using variables in Python


code:
nsp=NumericStringParser()
result=nsp.eval('2^4')
print(result)
# 16.0

rawDescription: Evaluating a mathematical expression in a string


code:
def compose(f1, f2):
    def composition(*args, **kwargs):
        return f1(f2(*args, **kwargs))
    return composition

def compose_many(*funcs):
    return reduce(compose, funcs)

rawDescription: Python avoiding lambda for key which needs two callables (function composition)


code:
def squares(n):
    for i in range(n):
        yield i*i

def squares(n):
    class Iterator:
        def __init__(self):
            self.i = 0
        def __iter__(self):
            return self
        def __next__(self):
            i, self.i = self.i, self.i+1
            return i*i
    return Iterator(n)

rawDescription: Why callbacks are "ugly"?

description: Why callbacks are "ugly"


code:
import lxml.etree as etree
import lxml.html

html = "
this is the good stuff
"
tree = lxml.html.fromstring(html)
node = tree.xpath("//p")[0]

result = node.text + ''.join(etree.tostring(e) for e in node)
print(result)

rawDescription: Get inner text from lxml

description: Get inner text from lxml


code:
def foo4():
    data=[(a,b) for a in [i*i for i in range(1,101)] for b in [1,2,3,4,5] if a+b > 40]
    return data

rawDescription: How fast are nested python generators?

description: How fast are nested python generators


code:
mock_func = mock.Mock()
mock_func.return_value = itertools.cycle([1, 2])
a = mock_func()
next(a)
next(a)
next(a)
next(a)

rawDescription: Mock infinite generator in Python

description: Mock infinite generator in Python


code: whoosh.query.Phrase(fieldname, words, slop=1, boost=1.0, char_ranges=None)

rawDescription: python fuzzy text search

description: Python fuzzy text search


code:
for i in list_:
    dop = re.search("\[(.+)\]$", str(i))
    if dop:
        species=dop.group(0)

rawDescription: Python, regular expression, strings inside brackets [ ]


code:
test = "hallo"
test.replace("a", " ")
test

rawDescription: How to replace values in multidimensional array?

description: Replace values in multidimensional array


rawDescription: Ajax Autocomplete for Jquery : OnSelect Function redirect to url


code:
class GroupAdd(forms.Form):
    parent_id = forms.IntegerField(widget=forms.HiddenInput)
    choices = forms.ModelChoiceField(queryset=None)

    def __init__(self, *args, **kwargs):
        pid = kwargs.pop('parent_id', None)
        super(GroupAdd, self).__init__(*args, **kwargs)
        self.fields['choices'].queryset = Objtree.objects.filter(
                                              type__name='group', parent_id=pid
                                          )

rawDescription: Django access data passed to form

description: Django access data passed to form


code:
@main.route('/super_secret')
@require_api_token
def super_secret():
    return "Sssshhh, this is a secret"

rawDescription: How do you implement token authentication in Flask?

description: Implement token authentication in Flask


rawDescription: Find out indices of an array elements

description: Find out indices of an array elements


code:
class Market_data_router(object):
    def allow_migrate(self, db, model):
        if db == 'market_data':
            if model.__name__ != 'Market_data':
                return False
        return None

rawDescription: put installed app model in selected database

description: Put installed app model in selected database


code:
import wx
import gui

class MainApp(gui.MainFrame):
    def __init__(self, parent):
        gui.MainFrame.__init__(self, parent)

        self.panelOne = Panel1(self)
        self.panelTwo = Panel2(self)
        self.panelTwo.Hide()

class Panel1(gui.panel_one):
    def __init__(self, parent):
        gui.panel_one.__init__(self, parent)
        self.parent = parent

    def changeIntroPanel( self, event ):
        if self.IsShown():
            self.parent.SetTitle("Panel Two Showing")
            self.Hide()
            self.parent.panelTwo.Show()

class Panel2(gui.panel_two):
    def __init__(self, parent):
        gui.panel_two.__init__(self, parent)
        self.parent = parent

    def changeIntroPanel( self, event ):
        if self.IsShown():
            self.parent.SetTitle("Panel One Showing")
            self.parent.panelOne.Show()
            self.Hide()

def main():
    app = wx.App()
    window = MainApp(None)
    window.Show(True)
    app.MainLoop()

if __name__ == '__main__':
    main()

rawDescription: wxpython - One Frame, Multiple Panels, Modularized Code

description: Wxpython - One Frame, Multiple Panels, Modularized Code


code:
def find_by_val(col, k, fle, delim=","):
    with open(fle) as f:
        names = next(f).rstrip().split(delim)
        if col not in names:
            print("Column does not exist.")
            return
        r, found = csv.DictReader(f, fieldnames=names), False
        output = [",".join(d[n] for n in names) for d in r if d[col] == k ]
        if not output:
            print("No matching value for {} found".format(k))
        else:
            print(",".join(names))
            print("\n".join(output))

rawDescription: Python2.7 - Passing argument to command line to filter CSV according to parameter


code:
try:
    ET.parse(path)
except ET.ParseError:
    print('{} is corrupt'.format(path))

rawDescription: Identify corrupt .xml in python

description: Identify corrupt .xml in python


code:
def split_args(args):
   vargs = vars(args)
   alist = ['a','b','c']
   args1 = []
   for a in alist:
        v = vargs.pop(a)
        args1.append(v)
   return args1, vars

rawDescription: Neatly pass positional arguments as args and optional arguments as kwargs from argpase to a function


code:
for i in range(1, 100, 10): # i = 1, 11, 21, 31, 41,.....
  print(' '.join(['%6d' % getPentagonalNumber(n) for n in range(i, i+10)]))

rawDescription: Printing multiple strings on same line in a loop


code:
fragments = {"ab", "cde", "abcd", "a", "bcd", "cd", "e"}
list(concatenations("abcde", fragments))

rawDescription: Recursion - how do you extract from specific traversals


code:
d = dict(foo=10,bar=20,baz=30)

cur.execute(
    "insert into testins (%s) values (%s)"
        % (','.join(d), ','.join('%%(%s)s' % k for k in d)),
    d)

rawDescription: Insert into a large table in psycopg using a dictionary


code:
refParam = clr.Reference[System.Double](15.1)
result = GetValue(refParam)

rawDescription: Calling a .Net function in Python which has a reference parameter


code:
list1 = [1,2,3,4]
list2 = [1,2,3,4]
for x in range(0, len(list2)):
    print(list1[list2[x]-1])

rawDescription: Indices are not synchronous of using one lists indices in another


rawDescription: Python reference to regex in parentheses


code:
import requests

with requests.Session() as session:
    for page in range(1, 10):
        print("Page number #%s" % page)
        response = session.get("http://www.thedailybeast.com/politics.view.%s.json" % page)
        data = response.json()

        for article in data["stream"]:
            print(article["title"])

rawDescription: Get all links with BeautifulSoup from a single page website ('Load More' feature)


code:
import lxml.html

page = """<html>...</html>"""
page = lxml.html.document_fromstring(page)
lxml.html.tostring(page)

rawDescription: Python how to search and correct html tags and attributes?


code: kelime = list(content[0])

rawDescription: Python reading from file into list then use line as list too and reach each char


code:
def instruction_reader(op_string):
    opcode,values = op_string.split(" ")
    values_list = values.split(',')
    dest = values_list[0]
    src = values_list[1:]

    return (opcode,dest,src)

rawDescription: Python: Script to detect data Hazards

description: Python: Script to detect data Hazards


rawDescription: Converting Python (PyKinect) Skeleton data to Points (X,Y)


code:
def executeRemoteCommand(host, command):
  ssh = subprocess.Popen(["ssh", host, command])

rawDescription: Zombie ssh process using python subprocess.Popen


code:
d = []
for _ in range(10):
    d.append(Distance(_, unit=u.kpc).value)

rawDescription: Access float value from astropy Distance object


code:
class Something(object):
    @staticmethod
    def somethingElse():
        pass

fullyQualifiedName(Something.somethingElse)

rawDescription: Send method to subprocess

description: Send method to subprocess


code: sorted(A, key=sum)

rawDescription: How to sort a matrix in the ascending order by the sum of its row in Python?

description: Sort a matrix in the ascending order by the sum of its row in Python


code:
ccvb
ccbb #cannot distinguish between what was changed to b and the original b
ccvv #thus both are changed together

rawDescription: New to Python, replacing characters in a string


code:
import re

def match_words(words, string):
    re_words = '|'.join(map(re.escape, sorted(words, key=len, reverse=True)))
    return re.search(r"\b(?:{words})\b".format(words=re_words), string)

rawDescription: Python text search library

description: Python text search library


code:
for char in chars:
    return char + recurse(chars, depth - 1)

rawDescription: simple recursive function

description: Simple recursive function


code:
def convert(prefix, name, side, obj_type, user_conv='${Prefix}_${name}_${SIDE}_${type}'):
    # Let us parameterize user_conv instead of hardcoding it.
    # That makes for better testing, modularity and all that good stuff.
    # user_conv = '${Prefix}_${name}_${SIDE}_${type}'
    # Assigns keys to strings to be used by the user dictionary.
    subs = {'prefix': prefix, 'name': name, 'side': side, 'type': obj_type}

    # Converts all of user convention to lowercase, and substitutes the names from subs.
    new_name = CustomRenameTemplate(user_conv)  # Send the actual template, instead of it's lower()
    new_name = new_name.substitute(**subs)

    # Strips leading and trailing underscores, and replaces double underscores with a single
    new_name = new_name.strip('_')
    new_name = new_name.replace('__', '_')

    return new_name

rawDescription: Python String Templating with Case Sensitivity


code:
amount_of_raise *= 0.01
years -= 1

rawDescription: Should I do anything to make my code more pythonic?


code:
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111, ...)

rawDescription: How to learn Matplotlib without searching Google or Stackoverflow?

description: Learn Matplotlib without searching Google or Stackoverflow


code: {k: max(v, key=lambda i: i[-1]) for k, v in somedic.iteritems()}

rawDescription: Finding the max value of list in dictionary


rawDescription: Appending input from csv file to a dictionary including duplicate values for a unique key


code:
class GeneralField(messages.Field):
    """
    Allow for normal non-Message objects to be serialised to JSON.
    This allows for variable result objects or dictionaries to be returned (Note: these objects must be Json serialisable).
    """
    VARIANTS = frozenset([messages.Variant.MESSAGE])

    DEFAULT_VARIANT = messages.Variant.MESSAGE

    def __init__(self,
                             number,
                             required=False,
                             repeated=False,
                             variant=None):
        """Constructor.

        Args:
            number: Number of field.  Must be unique per message class.
            required: Whether or not field is required.  Mutually exclusive to
                'repeated'.
            repeated: Whether or not field is repeated.  Mutually exclusive to
                'required'.
            variant: Wire-format variant hint.

        Raises:
            FieldDefinitionError when invalid message_type is provided.
        """
        super(GeneralField, self).__init__(number,
                                                                             required=required,
                                                                             repeated=repeated,
                                                                             variant=variant)

    def __set__(self, message_instance, value):
        """Set value on message.

        Args:
            message_instance: Message instance to set value on.
            value: Value to set on message.
        """
        if isinstance(value, list):
            if len(value) > 0:
                self.type = type(value[0])
            else:
                self.type = type(self)
        else:
            self.type = type(value)
        self.__initialized = True

        super(GeneralField, self).__set__(message_instance, value)

    def __setattr__(self, name, value):
        """Setter overidden to allow assignment to fields after creation.

        Args:
            name: Name of attribute to set.
            value: Value to assign.
        """
        object.__setattr__(self, name, value)

    def value_from_message(self, message):
        """Convert a message to a value instance.

        Used by deserializers to convert from underlying messages to
        value of expected user type.

        Args:
            message: A message instance of type self.message_type.

        Returns:
            Value of self.message_type.
        """
        return message

    def value_to_message(self, value):
        """Convert a value instance to a message.

        Used by serializers to convert Python user types to underlying
        messages for transmission.

        Args:
            value: A value of type self.type.

        Returns:
            An instance of type self.message_type.
        """
        return value

rawDescription: how to return dynamic json as response from google cloud endpoint python

description: Return dynamic json as response from google cloud endpoint python


code:
is_palindrome('')
is_palindrome('a')
is_palindrome('b')
is_palindrome('aa')
is_palindrome('ab')
is_palindrome('ba')
is_palindrome('bb')
is_palindrome('aaa')
is_palindrome('aab')
is_palindrome('aba')

rawDescription: Palindromes function does not work

description: Palindromes function does not work


code:
with open('letter.txt') as l, open('fixed.txt', 'w') as f:
    for lines in l:
        if not lines.startswith("WOOF"):
            print(lines.strip(), file=f)

rawDescription: writing specific lines from one file to another file

description: Writing specific lines from one file to another file


code:
['200 g torskefilet', 'havsalt og friskkv\xc3\xa6rnet peber', '8 tynde skiver r\xc3\xb8get sp\xc3\xa6k', '150 g r\xc3\xb8dbede (ca. 2 stk.)', '\xc2\xbd dl blommeeddike', '1 spsk. olivenolie', '1 spsk. r\xc3\xb8rsukker', 'lidt r\xc3\xb8dbedeblade eller anden bitter salat']
['', 'Vask r\xc3\xb8dbederne, kom dem i en gryde med vand, og bring dem i kog. Kog r\xc3\xb8dbederne i ca. 30 min., til de er m\xc3\xb8re, men stadig har lidt bid.', '', 'Kom koldt vand p\xc3\xa5 r\xc3\xb8dbederne, s\xc3\xa5 de k\xc3\xb8ler lidt af, og \xe2\x80\x9dgnid\xe2\x80\x9d skindet af efterf\xc3\xb8lgende, s\xc3\xa5 du kommer ind til r\xc3\xb8dbedens silkebl\xc3\xb8de indre.', '', 'Sk\xc3\xa6r r\xc3\xb8dbeder ud i grove tern, og kom dem i en gryde med eddike, sukker og olivenolie.', '', 'Lad eddiken koge ind i r\xc3\xb8dbederne, s\xc3\xa5 de bliver glaserede, og lagen f\xc3\xa5r konsistens som sirup.', '', 'Tjek torskefileterne for evt. vildfarne ben og for friskhed (de skal dufte af hav \xe2\x80\x93 ikke af havn!).', '', 'Sk\xc3\xa6r torsken ud i helt sm\xc3\xa5 tern. Brug en skarp kniv, s\xc3\xa5 k\xc3\xb8det bliver sk\xc3\xa5ret \xe2\x80\x93 ikke moset.', '', 'Kom torsketataren i en sk\xc3\xa5l, krydr med salt og peber, og r\xc3\xb8r rundt.', 'Form tataren til 4 sm\xc3\xa5 b\xc3\xb8ffer, og s\xc3\xa6t dem i k\xc3\xb8leskabet i 10 min., s\xc3\xa5 tataren lige s\xc3\xa6tter sig inden den steges.', '', 'Varm en pande op, og steg de tynde skiver sp\xc3\xa6k, s\xc3\xa5 de bliver spr\xc3\xb8de og kr\xc3\xb8ller lidt sammen. Tag sp\xc3\xa6kket af panden, og l\xc3\xa6g det p\xc3\xa5 et stykke k\xc3\xb8kkenrulle.', 'H\xc3\xa6ld overskydende fedt af panden, og steg s\xc3\xa5 tatarb\xc3\xb8fferne i 30 sek. \xe2\x80\x93 bare p\xc3\xa5 den ene side. P\xc3\xa5 den m\xc3\xa5de f\xc3\xa5r de en flot steges korpe, samtidig med at de stadig er r\xc3\xa5.', '', 'Server b\xc3\xb8fferne med de lune, glaserede r\xc3\xb8dbeder, det spr\xc3\xb8de sp\xc3\xa6k, lidt salat og friskskrabet peberrods-sne (se n\xc3\xa6ste opskrift).', '', 'Jeg elsker klassisk kogetorsk med hele svineriet: syltede r\xc3\xb8dbeder, sp\xc3\xa6k, h\xc3\xb8vlet peberrod, fiskesennep og sm\xc3\xb8rsovs \xe2\x80\x93 og denne forret er min moderne variant af den evigtgode kombination.']

['200 blah', '400 bar', 'foobar bar']
['', 'Foobar', 'Bar']

rawDescription: Match everything until certain pattern

description: Match everything until certain pattern


code:
lst = []
for line in new_listes(poem_lines):
    k = "" # K needs to reset after each line
    for word in line.split():
        for sylables in word_to_phonemes[word]:
            for char in sylables:
                k = k + char
    lst.append(number_count(k))
return lst

rawDescription: Counting Syllables In String

description: Counting Syllables In String


code:
def help_stats(self):
    self.help_about = tkinter.Toplevel(relief=tkinter.GROOVE)
    self.help_about.attributes("-toolwindow",1)
    self.help_about.title('Statistika')
    self.help_about.config(width="350", height="300")
    self.help_about.resizable(width=tkinter.FALSE, height=tkinter.FALSE)
    self.help_about_label = tkinter.Label(self.help_about, text="Something")
    self.help_about_label.pack(side=tkinter.TOP, expand=1, fill=tkinter.BOTH, padx=20, pady=10)

rawDescription: Remove minimise and maximise Button

description: Remove minimise and maximise Button


rawDescription: Python csv new line character in field

description: Python csv new line character in field


code:
from django.core import serializers
data = serializers.serialize("yaml", SomeModel.objects.all())
with open('try.yaml', 'w') as f:
    f.write(data)

rawDescription: Django doesn't load fixtures

description: Django doesn't load fixtures


code:
import sys,imp

my_code = 'a = 5'
mymodule = imp.new_module('mymodule')
exec(my_code, mymodule.__dict__)

rawDescription: Load module from string in python

description: Load module from string in python


code:
class MonatlicherVerbrauchUpdateView(UpdateView):
    def get_success_url(self):
        return reverse('messstellen:messtelle_detail', args=[self.object.pk])

    # define these attributes in the view as well, to keep urls simple
    model=MonatlicherVerbrauch,
    form_class=MonatlicherVerbrauchForm,
    template_name='messstellen/monatlich_form.html',

rawDescription: Sucess_url based on pk in GenericView from urls.py


rawDescription: Python slice notation to take only the start and the end part of a list?


code: first5andPowerball = itertools.product(first5, range(1, 35+1))

rawDescription: Generating Combinations NOT Permutations. How?


code: bar(bin_edges[:-1], hist_data)

rawDescription: making binned boxplot in matplotlib with numpy and scipy in Python

description: Making binned boxplot in matplotlib with numpy and scipy in Python


code:
import sip
sip.setapi('QString', 2)

rawDescription: PyQt: new API with Python 2

description: PyQt: new API with Python 2


code:
def flatten_count(iterable, element):
    return sum(
        flatten_count(item, element) if isinstance(item, list) else item == element
        for item in iterable
    )

rawDescription: Python - Finding each occurrence of a value in a mixed array (integers, lists)


code:
import sys
from collections import Counter

c = "When I got the number of how many times of the words"
d = c.split() # make a string into a list of words
counts = Counter(d) # count the words
sys.stdout = open("C:/Users/Administrator/Desktop/out.txt", "w")
print(str(len(d)) + ' words') #this shows the number of total words
for i in counts:
    print(str(i), str(counts[i]) + ' counts')

rawDescription: How to save the output to txt file?

description: Save the output to txt file


code:
subscriptions = Subscription.objects.filter(subscriber=user) # all subscriptions for a given user

newsletter_ids = [subscription.newsletter.id for subscription in subscriptions]

Newsletter.objects.filter(id__in=newsletter_ids) # answer

rawDescription: django model manytomany filter

description: Django model manytomany filter


code: answer = str(random.randint(1,8))

rawDescription: Dictionary and elif

description: Dictionary and elif


rawDescription: Quickest way to make a get_dummies type dataframe from a column with a multiple of strings


code:
__init__.py
api
api/__init__.py
api/resources.py
api/views.py
static/interface/css/style.css
static/interface/js/app.js
static/interface/js/other_modules_etc.js
static/shared/js/angular.js
static/shared/js/restangular.js
templates/interface.html

rawDescription: how to develop a web app with angularjs at client-side and flask at backend?

description: Develop a web app with angularjs at client-side and flask at backend


code: lis[:] = [item for item in lis if "(page does not exist)" not in item]

rawDescription: Deleting elements with specific substring in python


code:
#maybe needs parameters or simple use now_playing_object = ObjectProperty(None)
now_playing_object = Sound()

rawDescription: How can one object instance stop sound that other instance is playing?


code:
for i in range(1,100):
    for j in range(1,100):
       break
    else:
       continue
    break

rawDescription: break two for loops

description: Break two for loops


code:
class BitArray(object):
    @classmethod
    def from_array(cls, bits=None):
        self = cls()
        if bits is None: bits = []
        self.val = 0
        for b in bits:
            self.val <<= 1
            self.val += b
        self.nbits = len(bits)
        return self

    @classmethod
    def from_int(cls, val, nbits=None):
        self = cls()
        if nbits is None: nbits = val.bit_length()
        self.val = val
        self.nbits = nbits
        return self

    # Define equality
    def __eq__(self,  other):
        if self.val   != other.val:   return False
        if self.nbits != other.nbits: return False
        return True

    # Better representation of BitArray object
    def __repr__(self):
        return "BitArray(nbits=%d, val=%d)" % (self.nbits, self.val)

    # Output a binary string of nbits width, or width if specified (width must be >= nbits)
    def binstr(self, width=None):
        if width is None: width = self.nbits
        assert width >= self.nbits
        return "{:b}".format(self.val).zfill(width)

    # Conversion to int e.g. int(BitArrayInstance)
    def __int__(self):
        return self.val

    # "in-line" left shift
    def __ilshift__(self, n):
        self.val <<= n
        self.nbits += 1
        return self

    # "in-line" bitwise or
    def __ior__(self, v):
        self.val |= v
        return self

    # Helper function to generate a bit mask
    def _mask(self):
        return (1 << self.nbits) - 1

    # Trim n bits off the left side (truncate n most significant bits)
    def ltrim(self, n):
        self.nbits = max(0, (self.nbits - n))
        self.val &= self._mask()

    # "Pops" off msb, shifts all bits up 1, sets lsb to v
    def rotate_in(self, v):
        v = int(v)
        assert v in [0,1]
        self.ltrim(1)
        self.__ilshift__(1)
        self.__ior__(v)
        return self

rawDescription: Python dynamic bit manipulation example

description: Python dynamic bit manipulation example


code: sys.stdout.write("\r                       \r")

rawDescription: progress bar is making new line, would like for it to reset to begining

description: Progress bar is making new line, would like for it to reset to begining


code:
from scipy import stats
xk = np.arange(1, 4)
pk = (0.8, 0.15, 0.05)
custm = stats.rv_discrete(name='custm', values=(xk, pk))
# Return 100 results (for instance)
return custm.rvs(size=100)

rawDescription: How to generate random sequence of numbers in python?

description: Generate random sequence of numbers in python


rawDescription: Regex not matching \t\n\r\f\v in Python

description: Regex not matching \t\n\r\f\v in Python


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

x = np.linspace(0, 10, 100)
y1 = 2 * x
y2 = 3 * x

xthresh = 4.5
diff = np.abs(y1 - y2)
below = diff < xthresh
above = diff >= xthresh

# Plot lines below threshold as dotted...
plt.plot(x[below], y1[below], 'b--')
plt.plot(x[below], y2[below], 'g--')

# Plot lines above threshold as solid...
plt.plot(x[above], y1[above], 'b-')
plt.plot(x[above], y2[above], 'g-')

plt.show()

rawDescription: Change matplotlib line style mid-graph

description: Change matplotlib line style mid-graph


code:
filter_string = self.delName.get("1.0","end-1c")

with open("userDatabase.csv","r") as myFile:
    with open("newFile.csv","w") as newFile:
        for row in myFile:
            if filter_string not in row:
                newFile.write(row)

rawDescription: Python 3.4 CSV Deleting items using the in function


code:
import numpy as np

x = np.dtype(('<f8', (200, 100)))

strides = x.base.itemsize * np.r_[1, np.cumprod(x.shape[::-1][:-1])][::-1]

rawDescription: How do I get the strides from a dtype in numpy?

description: Get the strides from a dtype in numpy


code: pd.concat([pd.read_json(file) for file in ...], ignore_index=True)

rawDescription: Create pandas dataframe from json objects


code: links = [i.attrs['href'] for i in soup.findAll("a",{"class":"hdp-link"})]

rawDescription: How to use BeautifulSoup Python to scrap a webpage url?

description: Use BeautifulSoup Python to scrap a webpage url


code:
big_list = []
for _ in range(10):
   # while stuff
   big_list.append(comp_list)

rawDescription: Generating a list of numbers based on a constraint-step procedure


code:
def list_range(offset, length, l):
    # this handles both negative offsets and offsets larger than list length
    start = offset % len(l)
    end = (start + length) % len(l)
    if end > start:
        return l[start:end]
    return l[start:] + l[:end]

rawDescription: Python, loop through list within a range


code:
import ctypes
import numpy as np

class _VectorType(ctypes.Structure):
    _fields_ = [('components',  ctypes.c_double*3)]

lib_gen_ctypes = 'lib_ctypes_vector.so'
try_ctypes = ctypes.CDLL(lib_gen_ctypes,ctypes.RTLD_GLOBAL)

class vector(object):

    _ctypes_newVect = try_ctypes['newVect']
    _ctypes_subVect = try_ctypes['subVect']
    _ctypes_getVect = try_ctypes['getVect']

    vector_pointer = ctypes.POINTER(_VectorType)

    _ctypes_getVect.argtypes = [vector_pointer,]
    _ctypes_getVect.restype  = _VectorType

    def __init__(self,*args):
        self._vector = _VectorType()
        self._newVect(*args)

    def _newVect(self,vectIn):
        c_vect = (ctypes.c_double*3)(*vectIn)
        self._ctypes_newVect(ctypes.byref(self._vector),ctypes.byref(c_vect))

    def subVect(self):
        c_vect =  _VectorType()
        self._ctypes_subVect(ctypes.byref(self._vector),ctypes.byref(c_vect))
        return np.array(c_vect.components[:])

    def getVect(self):
        c_vect = self._ctypes_getVect(ctypes.byref(self._vector))
        return np.array(vect.components[:])

rawDescription: Can't get fortran function output from ctypes


code: foo[foo > 2]

rawDescription: Adding elements in arrays that fall within a criteria in Python


code:
np_result = np.polyval(p, x)
new_result = faster_polyval(p, x)
np.allclose(np_result, new_result)

rawDescription: A faster numpy.polynomial?

description: A faster numpy.polynomial


rawDescription: python: open and read a file containing germanic umlaut as unicode

description: Python: open and read a file containing germanic umlaut as unicode


code:
import numpy as np
pix = np.arange(30)
pix

rawDescription: How to reshape pixel list into RGB matrix?

description: Reshape pixel list into RGB matrix


code:
# set things up
freq = "1h"
df = pd.DataFrame(
    [2,2,2,1,1,1,2,2,2,3,2,2,1,1],
    index=pd.date_range('00:00', freq=freq, periods=14)
)

# add a column saying if a row belongs to the same state as the one before it
df["is_first"] = pd.rolling_apply(df, 2, lambda x: x[0] != x[1]).fillna(1)

# the cumulative sum - each "clump" gets its own integer id
df["value_group"] = df["is_first"].cumsum()

# get the rows corresponding to states beginning
start = df.groupby("value_group", as_index=False).nth(0)
# get the rows corresponding to states ending
end = df.groupby("value_group", as_index=False).nth(-1)

# put the timestamp indexes of the "first" and "last" state measurements into
# their own data frame
start_end = pd.DataFrame(
    {
        "start": start.index,
        # add freq to get when the state ended
        "end": end.index + pd.Timedelta(freq),
        "value": start[0]
    }
)
# convert timedeltas to seconds (float)
start_end["duration"] = (
    (start_end["end"] - start_end["start"]).apply(float) / 1e9
)
# get average state length and counts
agg = start_end.groupby("value").agg(["mean", "count"])["duration"]
agg["mean"] = agg["mean"] / (60 * 60)

rawDescription: Calculate the duration of a state with a pandas Dataframe


code:
subprocess.Popen([
    'C:\\Program Files (x86)\\Notepad++\\notepad++.exe',
    'C:\\Python27\\Django_Templates\\QC\\postits.html'
])

rawDescription: Open Text File in Notepad++ using Subprocess.Popen


code:
from shutil import move

move(output_file, input_file)

rawDescription: Regex Search Replace for Multiple Files in a Directory using Python


code:
def resolve_path(dictionary, path):
    return reduce(dict.get, path, dictionary)

rawDescription: How to delete object in a dict by reference from another variable

description: Delete object in a dict by reference from another variable


rawDescription: Python: split float after 3rd decimal place


code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

Builder.load_string('''
<MyWidget>:
    file_chooser: file_chooser
    FileChooserListView:
        id: file_chooser
''')

class MyWidget(BoxLayout):
    def __init__(self, **kwargs):
        super(MyWidget, self).__init__(**kwargs)
        self.file_chooser.path = "D:\\"

class MyApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()

rawDescription: Python kivy: how to use filechooser access files outside C drive


code:
df.index = pandas.date_range(pandas.datetime.today().date(),
                             periods=df.shape[0], freq='H')

rawDescription: Summing sections of a 2d array python

description: Summing sections of a 2d array python


code:
import xlrd
import os.path

wb = xlrd.open_workbook(os.path.join('D:\TRB 2014 Data','SPS1 demo data.xlsx'))
wb.sheet_names()
sh = wb.sheet_by_index(0)
i = 1
with open("Output.txt", "a") as my_file:
    while sh.cell(i,11).value != 0:
        Load = sh.cell(i,11).value
        all_d = sh.col_values(i, 13, 19)
        DB1 = Load + " " + (" ".join(all_d))
        my_file.write(DB1 + '\n')
        i += 1

rawDescription: How to read data from Excel and write it to text file line by line?

description: Read data from Excel and write it to text file line by line


rawDescription: Using networkx bfs_tree to obtain a list of nodes of a directed graph in BFS order


code:
if not os.path.exists('out.dat'):
    x, y = generate_x_y() #your time consuming method
    with open('out.dat', 'wb') as pkl_file:
        pickle.dump([x,y], pkl_file, -1)
else:
    with open('out.dat', 'rb') as pkl_file:
        x,y = pickle.load(pkl_file)

rawDescription: processing a binary file containing an array using python

description: Processing a binary file containing an array using python


code:
namesToAssign = {"Allocated":"Allocated",
                 "Bought":"Bought",
                 "Sold":"Bought",
                 "Remaining":"Remaining"}

col_prefix = "Base (MW) "
for newCol, oldCol in namesToAssign.iteritems():
    treatment = None if newCol != 'Bought' else boughtColClipper
    df[newCol] = baseMultiply(df, col_prefix + oldCol, preTreat=treatment)

rawDescription: Refactoring a bad 'code smell' in multiplication of columns in a dataframe


code:
import os
import site
import sys

VE = '/home/nedbat/webapps/myapp/ve'

site.addsitedir(VE + '/lib/python2.7/site-packages')

os.environ['DJANGO_SETTINGS_MODULE'] = 'prod_settings'
os.environ['USE_PYPY'] = 'y'
os.environ['TMPDIR'] = '/home/nedbat/webapps/myapp/tmp'

from django.core.handlers.wsgi import WSGIHandler

application = WSGIHandler()

rawDescription: How does django work with virtualenv?

description: How does django work with virtualenv


code:
list1 = [3,2,4,1, 1]
list2 = ['three', 'two', 'four', 'one', 'one2']
list1, list2 = zip(*sorted(zip(list1, list2)))
list1
list2

rawDescription: Is it possible to sort two lists(which reference each other) in the exact same way?


code:
import csv
import math
import re

def convertRedis(format_input):
    """
        Coordinate format conversion
    degrees minutes seconds:
    decimal degrees = degrees + minutes}/60 + seconds/3600.
    """
    degrees, minutes, seconds = map(float, re.match("\w(\d+)-(\d+)-(\d+)\w", format_input).groups())
    degrees = degrees + minutes/60 + seconds/3600
    return math.radians(degrees)

with open("Technical Description.txt") as fp:
    root_r = csv.reader(fp)
    root_r = csv.reader(fp, delimiter='\t')
    with open("output.txt", "wb+") as fp2:
        root_w = csv.writer(fp2, delimiter='\t')
        for row in root_r:
            rads = convertRedis(row[1])
            new_row = list(row)
            distance = float(row[2])
            if "S" in row[1]:
                d_cos =  "%.2f"%(distance*math.cos(rads) * -1, )
            else:
                d_cos =  "%.2f"%(distance*math.cos(rads), )

            if "W" in row[1]:
                d_sin =  "%.2f"%(distance*math.sin(rads) * -1, )
            else:
                d_sin =  "%.2f"%(distance*math.sin(rads), )

            new_row.extend([d_sin, d_cos])
            root_w.writerow(new_row)

rawDescription: Converting degrees-minutes to radians from data in a text file


rawDescription: multiplying numpy arrays of different size

description: Multiplying numpy arrays of different size


rawDescription: analyzing a txt file in python by jumping the n_th element of a list

description: Analyzing a txt file in python by jumping the n_th element of a list


code:
class KConnectProtocol(Protocol):

    # Adds +1 to the client count whenever a new connection is made, while
    # also putting a log entry for the client IP and time stamp.
    def connectionMade(self):
        self.client = self.transport.client
        log.msg('K connected from: ' + self.client[0])
        self.factory.numProtocols = self.factory.numProtocols + 1
        log.msg('There are ' + str(self.factory.numProtocols) + ' k connected.')

        self.factory.kList.append(self)

        self.kUID = ""

rawDescription: How can I create a running list of connected protocols that have searchable attributes with twisted?

description: Create a running list of connected protocols that have searchable attributes with twisted


rawDescription: changing numpy array to float

description: Changing numpy array to float


code: super(Context, self).__init__(dict_)

rawDescription: Can you return a render() without a context?

description: Return a render() without a context


code:
def merge_feature_vector(traffic):
    result = []
    for id, data in enumerate(traffic):
        result.extend(json.loads(data['http_body%s' % id]))
    return result

rawDescription: scikit-learn multi dimensional features

description: Scikit-learn multi dimensional features


code:
def flatten_ingredients(d):
    # in-place version
    if isinstance(d.get('Ingredients'), list):
        for ingredient in d.pop('Ingredients'):
            d['Ingredients=%s' % ingredient] = True
    return d

RecipeData=[{'RecipeID':1,'Ingredients':['Flour','Milk'],'TimeToPrep':20}, {'RecipeID':2,'Ingredients':'Milk','TimeToPrep':5} ,{'RecipeID':3,'Ingredients':'Unobtainium','TimeToPrep':100}]
map(flatten_ingredients, RecipeData)

rawDescription: Can sklearn's LabelBinarizer act similarly to DictVectorizer?


code:
import operator
getter = operator.itemgetter(2, 3, 4, 5, -4)
getter(range(50))  # Note, returns a `tuple`

rawDescription: Slices with several intervals?

description: Slices with several intervals


code:
@init_args_preprocessor
def orderless(args, kwargs):
    return sorted(args), kwargs

@orderless
@flat
class G(Expression):
   pass

rawDescription: Python: Modifying passed arguments before class instance initialization


code:
texts = [f1, f2, f3]
for text in texts:
    text.delete(1.0, 'end')

rawDescription: Python tkinter: Handle multiple tabs

description: Python tkinter: Handle multiple tabs


rawDescription: How to find two consecutive positive-negative values in an array?

description: Find two consecutive positive-negative values in an array


rawDescription: Best way to extract datetime from string in python

description: Extract datetime from string in python


code:
def bind_args(f):
    # f will be b in the below example
    binder = MethodBinder(f)

    @wraps(f)
    def wrapper(*args, **kwargs):
        # The wrapper function will get called instead of b, so args and kwargs
        # contains b's arguments. Let's bind any unbound function arguments:
        kwargs = binder.set_defaults(args, kwargs)

        # All arguments have been turned into keyword arguments. Now we
        # may call the real method with the modified arguments and return
        # the result.
        return f(**kwargs)
    return wrapper

rawDescription: Make a membermethod a default parameter

description: Make a membermethod a default parameter


code:
GridSize = [3,4,2]
allG = [np.linspace(-0.5,0.5, G) for G in GridSize]
out[0]
out[1]
out[2]

rawDescription: numpy linspace and mesh grid for multiple dimensions

description: Numpy linspace and mesh grid for multiple dimensions


code: datetime.datetime(1582, 10, 4, 12, 34, 56, 123000, tzinfo=datetime.timezone.utc)

rawDescription: strptime, format and saving the milliseconds

description: Strptime, format and saving the milliseconds


code:
type([]) is list
type({}) is dict
type('') is str
type(0) is int
type({})
type([])

rawDescription: Determine the type of an object?

description: Determine the type of an object


code:
frame.resample('1H', how={'radiation': np.sum, 'tamb': np.mean,\
               'new_column': count()})

rawDescription: insert new non-existing column in how= of resample

description: Insert new non-existing column in how= of resample


code: lookup = df.groupby('m_srcaddr').sum()[['m_rev_bytes', 'm_fwd_bytes']] / 1000

rawDescription: Create New Columns in dataFrame using existing columns in Panda


code: sequence = db1.sequence.find_and_modify(query=({'name':'Seq_AlertId'}),fields={'value':1,'_id':0}, update={"$inc": { 'value': 1}},upsert= True, new = True)

rawDescription: How to hide _id from find_and_modify() - MongoDB?

description: Hide _id from find_and_modify() - MongoDB


code:
A = [1,2,3]
B = [4,5,6]
x = A
x = B if x == A else A
x
x = B if x == A else A
x
x = B if x == A else A
x

rawDescription: toggle a value in Python

description: Toggle a value in Python


code:
set_if_not_there(d, ['cnt1', 'cnt2'], int)
set_if_not_there(d, ['tags1', 'tags2'], list)

rawDescription: Problems with a shared mutable?

description: Problems with a shared mutable


code:
with open('/path/to/some/file', 'r') as fp:
    hex_list = ["{:02x}".format(ord(c)) for c in fp.read()]

rawDescription: Python: Read hex from file into list?

description: Python: Read hex from file into list


code:
from django.db import connection

table_info = []
tables = connection.introspection.table_names()
seen_models = connection.introspection.installed_models(tables)
for model in seen_models:
    table = model._meta.db_table
    columns = [field.column for field in model._meta.fields]
    table_info.append((table, columns))

rawDescription: Django: How do I get every table and all of that table's columns in a project?


code:
df = df.sort_index()
df

rawDescription: Groupby in pandas timeseries dataframe choosing most recent event


code:
import operator

ops = {'+': operator.add, '-': operator.sub,
       '*': operator.mul, '/': operator.floordiv}

rawDescription: Stack, Pop and Add

description: Stack, Pop and Add


code: grammar = Combine(Literal("from") + Literal(":") + Word(alphas))

rawDescription: How to disallow spaces in between literals in pyparsing?

description: Disallow spaces in between literals in pyparsing


code: a = soup.findAll("a", attrs={"name": "1"})[0]

rawDescription: How do I parse out the following HTML in python beautifulsoup?

description: Parse out the following HTML in python beautifulsoup


code:
r = wiki.sentiment.polarity

r = []     #creat empty list r
return [r] #return empty list

rawDescription: How to capture iterated output variable into list for analysis

description: Capture iterated output variable into list for analysis


code:
def matches(s):
    return len(s.split('.')) > 2

rawDescription: Recognizing valid IP addresses having 2 or 3 components


rawDescription: Adding column In table with Python

description: Adding column In table with Python


rawDescription: Counting the number of non-NaN elements in a numpy ndarray matrix in Python


code:
import gspread
headers = gspread.httpsession.HTTPSession(headers={'Connection':'Keep-Alive'})
con = gspread.Client(auth=('you@gmail.com','password'),http_session=headers)
con.login()
con.open_by_key('....')

rawDescription: python gspread google spreadsheet keeping connection alive

description: Python gspread google spreadsheet keeping connection alive


code:
from itertools import combinations
deck = range(9)
sum(1 for dealt in combinations(deck, 6) for _ in combinations(dealt, 3))

rawDescription: generate two sets of combination with one list in python

description: Generate two sets of combination with one list in python


rawDescription: How to assign values to individual elements of python igraph list attributes?

description: Assign values to individual elements of python igraph list attributes


code:
df
newdf
newdf.columns=pd.MultiIndex.from_product([['bar'], newdf.columns])
pd.concat([df, newdf], axis=1)

rawDescription: Add a calculated result with multiple columns to Pandas DataFrame with MultiIndex columns


code: cols_string = '(' + ','.join(cols) + ')'

rawDescription: Create a string for sql statement from function **keywords


code: re.sub(r"(?s).*?\b(cat|dog|rat)\b", "\\1", input_text, 1)

rawDescription: Delete all characters in a multline string up to a given pattern


rawDescription: Flatten OpenCV/Numpy Array

description: Flatten OpenCV/Numpy Array


code:
import itertools
s='abc'
[''.join(u) for u in itertools.permutations(s, 3)]
[''.join(u) for u in itertools.product(*3*[s])]

rawDescription: Influence of choosing string as seed of random on the output


code: User.profile = property(lambda u: Configs.objects.get_or_create(user=u)[0])

rawDescription: What is the new approach to get user profile in Django 1.6?


code:
from mmtimer import mmtimer
import time

def tick():
    print("{0:.2f}".format(time.clock() * 1000))

t1 = mmtimer(150, tick, periodic=False)
time.clock()
t1.start()

rawDescription: How to implement high speed, consistent sampling?

description: Implement high speed, consistent sampling


rawDescription: Average time series with missing time value


rawDescription: Drop range of columns by labels

description: Drop range of columns by labels


code:
fig3, (ax1, ax2, ax3) = plt.subplots(1,3)

fig = plt.gcf()
fig.set_size_inches(16, 9)

convolution_locale = convolve(RotatePlot, Gaussian2DKernel(stddev=4)) # AFFICHAGE DE LA CARTE DE DENSITE CONVOLUEE POUR 2'
fig_smoothed_heatmap_locale = ax1.imshow(convolution_locale, interpolation='nearest')
ax1.set_title("Carte de densite convoluee 2'")
ax1.set_xlabel("X (arcmin)")
ax1.set_ylabel("Y (arcmin)")
divider = make_axes_locatable(ax1)
cax1 = divider.append_axes("right", size="5%", pad=0.05)
fig3.colorbar(fig_smoothed_heatmap_locale,cax=cax1)
ax1.invert_yaxis()

convolution_grande = convolve(RotatePlot, Gaussian2DKernel(stddev=32)) # AFFICHAGE DE LA CARTE DE DENSITE CONVOLUEE POUR 8'
fig_smoothed_heatmap_grande = ax2.imshow(convolution_grande, interpolation='nearest')
ax2.set_title("Carte de densite convoluee 16'")
ax2.set_xlabel("X (arcmin)")
ax2.set_ylabel("Y (arcmin)")
divider = make_axes_locatable(ax2)          ### I changed this line
cax2 = divider.append_axes("right", size="5%", pad=0.05)
fig3.colorbar(fig_smoothed_heatmap_grande,cax=cax2)
ax2.invert_yaxis()

convolution_diff = convolution_locale - convolution_grande # AFFICHAGE DE LA CARTE DE DENSITE CONVOLUEE 2' - 8'
fig_smoothed_tab_diff = ax3.imshow(convolution_diff, interpolation='nearest')
ax3.set_title("Carte 2' - Carte 16'")
ax3.set_xlabel("X (arcmin)")
ax3.set_ylabel("Y (arcmin)")
divider = make_axes_locatable(ax3)          ### I changed this line too
cax3 = divider.append_axes("right", size="5%", pad=0.05)
fig3.colorbar(fig_smoothed_tab_diff,cax=cax3)
ax3.invert_yaxis()

# Create space for labels between subplots
fig3.tight_layout()

fig3.savefig(outname3)

rawDescription: Set colorbar resized beside each subplots


code:
# Register your new serializer methods into kombu
from kombu.serialization import register
from .myjson import my_dumps, my_loads

register('myjson', my_dumps, my_loads,
    content_type='application/x-myjson',
    content_encoding='utf-8')

# Tell celery to use your new serializer:
CELERY_ACCEPT_CONTENT = ['myjson']
CELERY_TASK_SERIALIZER = 'myjson'
CELERY_RESULT_SERIALIZER = 'myjson'

rawDescription: Celery: is there a way to write custom JSON Encoder/Decoder?


code:
def pxlocal(line, cell):
    ip = get_ipython()
    ip.run_cell_magic("px", line, cell)
    ip.run_cell(cell)
get_ipython().register_magic_function(pxlocal, "cell")

rawDescription: How to work with interactively-defined classes in IPython.parallel?

description: Work with interactively-defined classes in IPython.parallel


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

Operating System

Linux

Debian

Fedora

Ubuntu

Windows

OS X

Programming Languages

Python

C#

Ruby

""")
ul = soup.body.ul
from pprint import pprint
pprint(dictify(ul), width=1)

rawDescription: Parsing nested HTML list with BeautifulSoup


code:
data[0]['price']
data[0]['name']

rawDescription: Values Hidden From Source Code- Webscraping Python


code:
with open('January.txt', 'r') as f1, open('February.txt', 'r') as f2:
    for x, y in zip(f1.read().splitlines()[1::2], f2.read().splitlines()[1::2]):
        print(float(x) / int(y))

rawDescription: Divide Every Other Line Between Two Files


code:
class MyFuzzyTerm(FuzzyTerm):
     def __init__(self, fieldname, text, boost=1.0, maxdist=2, prefixlength=1, constantscore=True):
         super(MyFuzzyTerm, self).__init__(fieldname, text, boost, maxdist, prefixlength, constantscore)

rawDescription: Fuzzy String Searching with Whoosh in Python


code:
grouper = {}
for d in data:
    grouper[d["foo"]] = grouper.get(d["foo"], 0) + d["bar"]

grouper

rawDescription: aggregating an array of objects by attribute

description: Aggregating an array of objects by attribute


code:
import readchar

inputStr = ""

while len(inputStr) != 8:
    inputStr += str(readchar.readchar())

# Quote: "Save it in variable"

variable = inputStr

# Clean
inputStr = ""

rawDescription: Python - Loop waiting for input

description: Python - Loop waiting for input


code: [(e['lat'], e['lon']) for e in elements if e['type'] == 'node']

rawDescription: How to access way coordinates from a large (.json-based) list structure

description: Access way coordinates from a large (.json-based) list structure


code:
cur.executemany('insert into Counts (email, count) values (?,?)',Counts)
conn.commit()

rawDescription: Python - Inserting list of tuples into SQLite


code:
# define a list of your words (call it 'words')

# define the string you want to search through (call it 'jumble')

# Define an empty dictionary that will hold your results. You can use a regular
# dictionary, or a cool thing in Python called "DefaultDict", in the collections module.
# Call it 'count'.

# Now loop through each of your words

   # Start searching at the beginning of your jumble, by
   # specifying a start position of 0. (This will make sense later.)

   # Add another loop here, that keeps looping until we're sure there's no
   # more words to be found.

       # Try to find (hint: check out the 'string' module) the word inside of jumble.

       # If we did NOT find a word
           # We just 'break' out of the inner loop

       # Else If we DID find a word, let's save the position of that word.
       # Call that 'index'.
           # If this is the first time, we put the word in our dictionary
           # with a count of 1
           # Else If this is not the first time, add 1 to the dictionary entry
           # for that word.

       # Now we search AGAIN through the jumble, but start AFTER the
       # position where we saw the first time.

# Now we've exited the entire thing, let's just print out our 'count' dictionary.

rawDescription: Count occurrences of array in string

description: Count occurrences of array in string


code:
import datetime as dt
# same week
In [1]: week_difference(dt.datetime(2012, 8, 1),  dt.datetime(2012, 8, 1))
Out[1]: 0

# your example (see note below)
In [2]: week_difference(dt.datetime(2012, 8, 1),  dt.datetime(2012, 8, 13))
Out[2]: 2

# across years
In [3]: week_difference(dt.datetime(2011, 8, 1),  dt.datetime(2012, 8, 13))
Out[3]: 54

# year boundary: second last business week of 2011, to first business week of 2012
# which is the same business week as the last business week of 2011
In [4]: week_difference(dt.datetime(2011, 12, 20),  dt.datetime(2012, 1, 1))
Out[4]: 1

In [5]: week_difference(dt.datetime(2011, 12, 18),  dt.datetime(2012, 1, 1))
Out[5]: 2

rawDescription: python count business weeks

description: Python count business weeks


code:
req = urllib2.Request('http://httpbin.org/basic-auth/foouser/barpw')
base64string = base64.encodestring("%s:%s" % ("foouser", "barpw")).replace("\n", "")
req.add_header("Authorization", "Basic %s" % base64string)
response = urllib2.urlopen(req)
response.getcode()

rawDescription: Python - urllib2 how to know if our authorization is successful


code:
for row in inputArray:
    print(f(*row)),
arr = np.array(inputArray)
f(arr[:,0], arr[:,1])

rawDescription: Improving Performance - Symbolic function applied to each row of numpy array


code:
def validate_inp(fun):
    def wrapper(self, inp):
        return fun(self, inp) if inp else False
    return wrapper

class Foo(object):
    @validate_inp
    def func(self, inp):
        return int(inp['value']) + 1 if inp else False

foo = Foo()
print(foo.func(False))
print(foo.func({'value': 1}))

rawDescription: Looking for idiomatic way to evaluate to False if argument is False in Python 3


code:
import re

# Example url
url = 'http://www.cnbc.com/2016/03/13/financial-times-china-rebuts-economy-doomsayers-on-debt-and.html'
# Create a regex match pattern
pattern = r'http://www.cnbc.com/(.+)/(.+)/(.+)/(.+).html'
# Find match
m = re.match(pattern, url)
# Get Groups
m.groups()

rawDescription: compare url with a customized pattern in python

description: Compare url with a customized pattern in python


code:
from cProfile import Profile
from pstats import Stats
prof = Profile()

prof.disable()  # i.e. don't time imports
import time
prof.enable()  # profiling back on

def fast():
    print("Fast!")

def slow():
    time.sleep(3)
    print("Slow!")

def medium():
    time.sleep(0.5)
    print("Medium!")

fast()
slow()
medium()

prof.disable()  # don't profile the generation of stats
prof.dump_stats('mystats.stats')
with open('mystats_output.txt', 'wt') as output:
    stats = Stats('mystats.stats', stream=output)
    stats.sort_stats('cumulative', 'time')
    stats.print_stats()

rawDescription: cProfile with imports

description: CProfile with imports


code:
def f(seq=[]):
    seq.append('x') #append one 'x' to the argument
    print(seq) # print it
f() # as expected
f() # but this appends 'x' to the same list
f() # again it grows
f()
f()

rawDescription: class getting kwargs from enclosing scope

description: Class getting kwargs from enclosing scope


code:
import csv
with open('a.csv','r') as f:
    reader = csv.reader(f)
    lst = []
    for row in reader:
            row.pop(0)
            if row[0] == 'B':
                    row[0] = 0
            else:
                    row[0] = 1
            lst.append(list(map(float, row)))
lst

rawDescription: changing given text to list of lists

description: Changing given text to list of lists


code:
def my_decorator(function):
    def outer():
        print('outer')
        return function()
    return outer

@my_decorator
def my_method():
    print('inner')

try:
    # Python2
    my_method.func_closure[0].cell_contents()
except AttributeError:
    # Python3
    my_method.__closure__[0].cell_contents()

rawDescription: Introspection on a python decorated method


code:
import csv
from collections import OrderedDict

filenames = "file1.csv", "file2.csv"
data = OrderedDict()
fieldnames = []
for filename in filenames:
    with open(filename, "rb") as fp: # python 2
        reader = csv.DictReader(fp)
        fieldnames.extend(reader.fieldnames)
        for row in reader:
            data.setdefault(row["id"], {}).update(row)

fieldnames = list(OrderedDict.fromkeys(fieldnames))
with open("merged.csv", "wb") as fp:
    writer = csv.writer(fp)
    writer.writerow(fieldnames)
    for row in data.itervalues():
        writer.writerow([row.get(field, '') for field in fieldnames])

rawDescription: How do I merge two CSV files based on field and keep same number of attributes on each record?

description: Merge two CSV files based on field and keep same number of attributes on each record


code: bs_reduced = bs[(var < 0.1) & (var >=0)]

rawDescription: Replacing loop with List Comprehension instead of loop getting a function to return a new array within the list comprehension


code:
from sklearn.externals.joblib import Parallel, delayed
from time import sleep, time

def solve_one_task(task):
    # Solves one task at a time
    print("%d. Task #%d is being solved"%(time(), task))
    sleep(5)
    return task

def task_gen(max_task):
    current_task = 0
    while current_task < max_task:
        print("%d. Task #%d was dispatched"%(time(), current_task))
        yield current_task
        current_task += 1

Parallel(n_jobs=2, backend = 'multiprocessing', batch_size=1, pre_dispatch=3)(
        delayed(solve_one_task)(task) for task in task_gen(10))

rawDescription: What batch_size and pre_dispatch in joblib exactly mean


code:
def place_player_1(self,start_turn_pos_1,number):
    self.c.after(1000, self.move_1, start_turn_pos_1, number) # call in a sec

def move_1(self,i, limit):
    e1=streets_x[i]
    g1=streets_y[i]
    self.label_player1.place(x=e1,y=g1)
    if i < limit: # schedule the next call
       self.c.after(1000, self.move_1, i + 1, limit)

rawDescription: self." ". after() does not work properly?

description: Self." ". after() does not work properly


rawDescription: How do I secure an AWS API Gateway with Cognito?

description: Secure an AWS API Gateway with Cognito


code:
results = ( foo() for _ in xrange(10) )
results
list(results)

rawDescription: how to use python list comprehensions replace the function invoke inside of "for" stmt?

description: Use python list comprehensions replace the function invoke inside of "for" stmt


code:
subprocess.call('java', ['-jar', 'GeoNetCWBQuery-4.0.2-bin.jar', '-s', 'NZMQZ..HH...', '-d', '3600',
'-event:time', date, time,  '-event:lat', lat, '-event:lon', lon,
'-event:depth', depth, '-o', '%c%s%y%M%D%z'])

rawDescription: Call an external command in python and inserting values into the command


rawDescription: PHP equivalent for Python's repr()

description: PHP equivalent for Python's repr()


code:
dictionary = create_dictionary()
searchT = input("What are you searching for? ")
dictionary.get(searchT)   # returns None if searchT is not in dictionary

rawDescription: Why is my if else statement being ignored


code:
['aaabbbccc', 'aaabbbcac', 'aaabbbccb', 'aaababccc', 'aaababcac', 'aaababccb',
 'aaabbcccc', 'aaabbccac', 'aaabbcccb', 'ababbbccc', 'ababbbcac', 'ababbbccb',
 'abababccc', 'abababcac', 'abababccb', 'ababbcccc', 'ababbccac', 'ababbcccb',
 'aacbbbccc', 'aacbbbcac', 'aacbbbccb', 'aacbabccc', 'aacbabcac', 'aacbabccb',
 'aacbbcccc', 'aacbbccac', 'aacbbcccb']

rawDescription: All possible combinations of dictionary values given input string. Python


code:
data_one
data_two

rawDescription: In Python how do I create a data frame with a list that contains multiple levels of dictionaries?


code:
class MyOwnClass:
  # a template dict
  @property
  def template_query():
      return {'name':'default','age':-1}

rawDescription: issue in list of dict

description: Issue in list of dict


rawDescription: Generate multiple independent random streams in python


code:
rez_dict = {d['id']:d for d in rez}
rez_ordered = [rez_dict[id] for id in ids]

rawDescription: Pythonic sort a list of dictionaries in a tricky order


code:
def cleanup(dirty_data):
    if isinstance(dirty_data, dict):
        for key in dirty_data:
            value = dirty_data[key]
            dirty_data[key] = cleanup(value)
        return dirty_data
    elif isinstance(dirty_data, str) or isinstance(dirty_data, unicode):
        if dirty_data in ["nan", "inf", "-inf"]:
            return float(dirty_data)
    else:
        return dirty_data

test_object = {"test": 123, "a": {"b": "nan"}}

print(cleanup(test_object))

rawDescription: python - replace value of unknown key in json

description: Python - replace value of unknown key in json


code:
import matplotlib.pyplot as plt

plt.annotate(r'Testing\nThis\nOut', xy=(0.5, 0.5))

plt.show()

rawDescription: Python : Matplotlib annotate line break (with and without latex)


code:
import pygtk
pygtk.require('2.0')
import gtk
import wnck

screen = wnck.screen_get_default()
while gtk.events_pending():
    gtk.main_iteration()

windows = screen.get_windows()
print (windows)

rawDescription: python wnck not returning any data until after a pdb.set_trace()

description: Python wnck not returning any data until after a pdb.set_trace()


code: data['mass']

rawDescription: how to find avg of column of csv file

description: Find avg of column of csv file


code:
def len(x):
    return x.__len__()

rawDescription: Python multimethods using isinstance

description: Python multimethods using isinstance


code:
def fast(wxf, wyf, wzf):
    return np.einsum('if,jf,kf->ijk', wxf, wyf, wzf)

def slow(wxf, wyf, wzf):
    N = len(wxf)
    W = np.zeros((N, N, N))
    for i in range(N):
        for j in range(N):
            for k in range(N):
                W[i,j,k] = np.sum([wxf[i,f]*wyf[j,f]*wzf[k,f] for f in range(N)])
    return W

def gen_ws(N):
    wxf = np.random.random((N,N))
    wyf = np.random.random((N,N))
    wzf = np.random.random((N,N))
    return wxf, wyf, wzf

rawDescription: How can I efficiently expand a factored tensor in numpy?

description: Efficiently expand a factored tensor in numpy