code:
for farm in USA:
    for animal in farm:
        pass #do something here

rawDescription: python multiple nested classes

description: Python multiple nested classes


rawDescription: Hierarchical index multi index containing edge values. Rearrange it?


code:
def memo(f):
    cache = {}
    def func(*args):
        if args not in cache:
            cache[args] = f(*args)
        return cache[args]
    return func

rawDescription: Nesting functions inside of functions

description: Nesting functions inside of functions


code: count(readFile('path/to/file'))

rawDescription: Python txt file- Reading and using information in file


code: linets = datetime.strptime(line.strip()[:17], '%Y%m%d_%H:%M:%S')

rawDescription: Check if file line sttime is older than 2 days - Python


code:
Name,Age,Gender,Varsity,GPA,Town,State
John,18,Male,YES,3.2,Tacoma,WA
Tyler,18,Male,YES,2.9,Tacoma,WA
Jane,17,Jane,YES,3.5,Tacoma,WA
Michelle,18,Female,NO,3.1,Tacoma,WA
Jamie,17,Male,NO,2.6,Tacoma,WA
Robert,17,Male,YES,4.0,Tacoma,WA
Danielle,18,Female,NO,3.0,Tacoma,WA
Dustin,18,Male,NO,3.2,Tacoma,WA
Angela,16,Female,NO,2.9,Tacoma,WA
Barbara,17,Female,YES,3.5,Tacoma,WA
Megan,18,Female,NO,3.4,Tacoma,WA
Michael,18,Male,YES,3.0,Tacoma,WA
Craig,17,Male,NO,3.1,Tacoma,WA
Jackson,18,Male,NO,2.8,Tacoma,WA
Bill,18,Male,YES,3.2,Tacoma,WA
Matthew,17,Male,YES,3.0,Tacoma,WA
Karen,16,Female,NO,3.4,Tacoma,WA
Sarah,17,Female,YES,3.2,Tacoma,WA
Charles,18,Male,NO,3.5,Tacoma,WA

rawDescription: Making changes to CSV and writing to a new file


code:
import textwrap

abstract = textwrap.wrap(text, 100)[0]

rawDescription: Computing article abstracts

description: Computing article abstracts


code:
counting=0
for comb in combinations(range(1,10),3):
    print (comb)
    counting+=1
print ("The number of counts is:",counting)

rawDescription: Count the number of results

description: Count the number of results


code:
# config.py
param = 7 # some default

rawDescription: Is there a way to get importer's variable in importee?


code:
class PS2(object):
    def __repr__(self):
        windll.Kernel32.SetConsoleTextAttribute(std_output_hdl, greenText)
        sys.stdout.write("         ... ")
        windll.Kernel32.SetConsoleTextAttribute(std_output_hdl, defaultText)
        return ""

rawDescription: Colored Python Prompt in Windows?

description: Colored Python Prompt in Windows


code:
from scrapy import signals
from scrapy.exceptions import DropItem

class DuplicatesPipeline(object):

    def __init__(self):
        self.author_ids_seen = set()

    def process_item(self, item, spider):
        if item['author_id'] in self.author_ids_seen:
            raise DropItem("Duplicate item found: %s" % item)
        else:
            self.ids_seen.add(item['author_id'])
            return item

rawDescription: Item caching in Scrapy

description: Item caching in Scrapy


code:
data = [list(unpack(fmt_s, section[:size_s])) + [list(unpack(fmt_spec, section[size_s:]))]
    for section in chunked(bytes, size)]

rawDescription: Reading a binary file into a struct in Python


code:
import json
json.dumps(combine(dict1, dict2))

rawDescription: Python - convert strings into json and combine


code:
from PIL import Image
import numpy as np

col = Image.open("cat-tied-icon.png")
gray = col.convert('L')

# Let numpy do the heavy lifting for converting pixels to pure black or white
bw = np.asarray(gray).copy()

# Pixel range is 0...255, 256/2 = 128
bw[bw < 128] = 0    # Black
bw[bw >= 128] = 255 # White

# Now we put it back in Pillow/PIL land
imfile = Image.fromarray(bw)
imfile.save("result_bw.png")

rawDescription: Convert RGB to black OR white

description: Convert RGB to black OR white


code:
dataFrame = (df0.join(df1, how='outer').
                 join(df2, how='outer').
                 join(df3, how='outer'))

rawDescription: How to split multiple commands according to PEP8?

description: Split multiple commands according to PEP8


code: answer = [r[max(enumerate(row), key=operator.itemgetter(1))[0]] for r,row in zip(b,a)]

rawDescription: How to extract data in one array according to the values in another array in Python

description: Extract data in one array according to the values in another array in Python


code:
class Vertex(Base):
    # ...

    def _validate_successors_impl(self, value):
        return True

    @validates('successors')
    def validate_successors(self, key, value):
        self._validate_successors_impl(value)
        return value

class A(Vertex):
    __mapper_args__ = {'polymorphic_identity': 'A'}

    def _validate_successors_impl(self, value):
        if type(value) == B:
            assert check_value, 'Invalid Edge: not allowed to link from [{fr}] to [{to}]'.format(fr=type(self).__name__, to=type(value).__name__)

class B(Vertex):
    __mapper_args__ = {'polymorphic_identity': 'B'}

rawDescription: type dependant edge creation in polymorphic graph structure with sqlalchemy

description: Type dependant edge creation in polymorphic graph structure with sqlalchemy


rawDescription: Getting multiple DataFrame cross-sections


rawDescription: How to construct a matrix of all possible differences of a vector in numpy

description: Construct a matrix of all possible differences of a vector in numpy


code:
db1 = sq.connect('temp.db')

db1.execute('CREATE TABLE tbl (col INTEGER)')
db1.execute('CREATE TABLE tbl2 (col INTEGER)')
db1.executemany('INSERT INTO tbl (col) VALUES (?)', [(0,), (1,), (2,)])
db1.commit()

print('count=' + str(db1.execute('SELECT count(*) FROM tbl').fetchone()[0]))

db2 = sq.connect('temp.db')

# Read and print the values just inserted into tbl
for col in db1.execute('SELECT col FROM tbl').fetchall():
    print(col)
    db2.execute('INSERT INTO tbl2 VALUES (?)', col)
    db2.commit()

print('count=' + str(db1.execute('SELECT count(*) FROM tbl').fetchone()[0]))

rawDescription: Python, SQLite3: cursor returns duplicates when a commit intervenes


rawDescription: Numpy: how to get the items that are different of 2 matrices?


code: vector = np.array( (1 for ele in long_list if condition(ele)) )

rawDescription: better way to vectorize using numpy

description: Better way to vectorize using numpy


code:
import csv

with open("myfile.csv", "wb") as outf:                 # Python 2.x
# with open("myfile.csv", "w", newline="") as outf:    # Python 3.x
    outcsv = csv.writer(outf)

    # header row
    outcsv.writerow(columns)

    # data
    outcsv.writerows(table)

rawDescription: scraping a table then writing to csv

description: Scraping a table then writing to csv


code:
ROMANS = {
  str(r): r for r in (
    roman(i) for i in range(1, 1000 + 1)
    )
  }

rawDescription: Instantiate multiple objects of a class most efficiently


code:
a = [3, 1, 4, 1, 5, 9, "X"]

def get_checksum(a):
    seed = 113
    limit = 10000007
    result = 0

    for i in range(len(a) - 1):
        result += a[i]
        result *= seed
        result %= limit

    return result

print(get_checksum(a))
#>>> 8921379

rawDescription: Array Checksum Algorithm - Python 3

description: Array Checksum Algorithm - Python 3


code:
find = 7
[x[0] for x in enumerate(lst) if find in x[1]]

rawDescription: Find which row/sublist a value is in

description: Find which row/sublist a value is in


code:
def returnName(self):
    '''return the name of the player first last'''
    return(self.first + ' ' + self.last)

def returnReverseName(self):
    '''return the name of the player as last, first'''
    return self.last, self.first

def __eq__ (self, other):
    '''determine if this persons name is the same as the other personsname'''
    return self.returnReverseName() == other.returnReverseName()

def __lt__(self,other):
    '''determine if this persons name is less than the other persons name alphabetically'''
    return self.returnReverseName() < other.returnReverseName()

def __gt__ (self, other):
    '''determine if this persons name is greater than the other persons name alphabetically'''
    return self.returnReverseName() > other.returnReverseName()

def __str__(self):
    '''return a string of the persons name and their rating in a nice format'''
    return '%-20s %10.2f' % (self.returnName(), self.rating)

rawDescription: Alphabetizing a list through class methods


code:
def make_sort_key(key_string):
    # make index
    index = {}
    for i,ch in enumerate(key_string):
        index[ch] = i
    # sort any char not in index following any char in index
    omitted = len(index)
    val = index.get

    def key_fn(s):
        return [val(ch, omitted) for ch in s]

    return key_fn

rawDescription: Sort a list based on a string- Python

description: Sort a list based on a string- Python


code: kind = {'Alpha': 'Attackers', 'Beta': 'Attackers', 'Gamma': 'Defenders'}

rawDescription: How to generate continuous record from incomplete data in Pandas Dataframe

description: Generate continuous record from incomplete data in Pandas Dataframe


code:
class FooAdmin(admin.ModelAdmin):
    form = FooForm

rawDescription: how to modify choices on admin pages - django

description: Modify choices on admin pages - django


code: reduce(getitem, lis[:-1], DictOfVehiclePrices)[lis[-1]] = 'cheap'

rawDescription: How can I change the value of a node in a python dictionary by following a list of keys?

description: Change the value of a node in a python dictionary by following a list of keys


code: import tkSimpleDialog, tkMessageBox

rawDescription: Threading with Twisted with Tkinter

description: Threading with Twisted with Tkinter


code:
# This SConstruct orchestrates building 2 subdirs
import os

Import('env')
subdirs = ['src', 'test']

for subdir in subdirs:
    SConscript(os.path.join(subdir, 'SConscript'), exports = ['env'])

rawDescription: Real Hierarchical Builds with SCons?

description: Real Hierarchical Builds with SCons


code:
d={ u'job_27301': [{u'auto_approve': u'0',
                 u'body_src': u'some text1'}],

  u'job_27302': [{u'auto_approve': u'0',
                 u'body_src': u'some text2'}],

  u'job_27303': [{u'auto_approve': u'0',
                 u'body_src': u'some text3'}] }

for k,v in d.iteritems(): # items in python 3
    print(v[0]["body_src"])

rawDescription: json dict - python how to access

description: Json dict - python how to access


code:
units = dict(K=1024, M=1024*1024, G=1024*1024*1024)
def parse_size(s):
    times = units.get(s[-1:], 1)
    if times == 1:
        return float(s)
    else:
        return float(s[:-1]) * times

rawDescription: find files more than 100 MB from ls -1hl command's output

description: Find files more than 100 MB from ls -1hl command's output


code:
for player in players_i_care_about:
    tournament.players.add(player) #(only adds these players, doesn't remove any players)

rawDescription: Save() in ManyToMany relation

description: Save() in ManyToMany relation


code:
bbox = fig.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width*fig.dpi, bbox.height*fig.dpi

rawDescription: How to get matplotlib figure size

description: Get matplotlib figure size


tag: org

type: folder

type: file

rawDescription: Filesytem tree to json

description: Filesytem tree to json


rawDescription: divide ways on a map in parts of length one

description: Divide ways on a map in parts of length one


code:
[9, 8, 7, 'Hello from Func1!']
[9, 8, 7, 'Hello from Func1!', 2]

rawDescription: Python 2.7 Local Variables are acting like global variables


code:
with validator(validation):
    x = input("10 or less: ")

x = input("10 or less (unpatched): ")
print("done")

rawDescription: Context manager to validate data

description: Context manager to validate data


code: friend = dict(line.split(":", 1) for line in open("file"))

rawDescription: How do I take info from a text file and put it into a dictionary (Python)

description: Take info from a text file and put it into a dictionary (Python)


rawDescription: term by term division in python (division termino a termino en python )

description: Term by term division in python (division termino a termino en python )


code:
def profile_view(request):
    if request.user.get_profile().type == 'foo':
        template = 'path/to/foo_profile.html'
    elif request.user.get_profile().type == 'bar':
        template = 'path/to/bar_profile.html'
    else:
        template = 'path/to/generic_profile.html' # if you want a default

    return render_to_response(template, {'data': 'data'}, context_instance=RequestContext(request))

rawDescription: Show different profile based on user type


code: tuple(a) == tuple(b)

rawDescription: Elegant way to compare sequences

description: Elegant way to compare sequences


code:
combination = {
    'item1': 3.14,
    'item2': 42,
    'items': [
        'text text text',
        {
            'field1': 'a',
            'field2': 'b',
            },
        {
            'field1': 'c',
            'field2': 'd',
            },
        {
            'field1': 'e',
            'field3': 'f',
            },
        ]
    }
print(list(ComboParser(combination).item1))
# [3.1400000000000001]
print(list(ComboParser(combination).items))
# ['text text text', {'field2': 'b', 'field1': 'a'}, {'field2': 'd', 'field1': 'c'}, {'field3': 'f', 'field1': 'e'}]
print(list(ComboParser(combination).items[0]))
# ['text text text']
print(list(ComboParser(combination).items.field1))
# ['a', 'c', 'e']

rawDescription: Complex transforming nested dictionaries into objects in python


code:
x.py
#!python3
import ctypes

class FileParams(ctypes.Structure):
    _fields_ = [('val1',ctypes.c_float),
                ('pMarker',ctypes.c_void_p)]

    x = ctypes.WinDLL('x')
    x.Function1.argtypes = [ctypes.c_char_p,ctypes.c_char_p,ctypes.POINTER(FileParams)]
    x.Function1.restype = ctypes.c_int

    fp = FileParams(1.234,None)
    x.Function1(b'abc',b'def',ctypes.byref(fp))

rawDescription: Unable to load C++ dll in python

description: Unable to load C++ dll in python


code: ats1,ats2 = ts1.align(ts2)

rawDescription: How to calculate ts1 - ts2.interpolate(index=ts1.index)

description: Calculate ts1 - ts2.interpolate(index=ts1.index)


code:
class Foo(object):
    def appender(self, bar):
        self.__setattr__('Number' + str(bar), bar)

rawDescription: Create class instance variables using a locals()['some_string'] like approach


code:
print("{:>3s} {:20s} {:>12s}".format("Id", "State", "Population"))
print("{id:3d} {name:20s} {population:12d}".format(**state))

rawDescription: Python3 .format() align usage

description: Python3 .format() align usage


code:
from twisted.internet.protocol import Factory
from twisted.application.service import Application
application = Application("test")
def showPortNumber(n):
    print("The port number is: %d" % (n,))
PortReporter(Factory(), showPortNumber).setServiceParent(application)

rawDescription: twisted - get OS-chosen listen port

description: Twisted - get OS-chosen listen port


code:
def _setattr(obj, query, val):
    """
    This is a special setattr function that will take in a string query,
    interpret it, add the appropriate data structure to obj, and set val.

    We only define two actions that are available in our query string:
    .x -- dict.__setitem__(x, ...)
    [x] -- list.__setitem__(x, ...) OR dict.__setitem__(x, ...)
           the calling context determines how this is interpreted.
    """
    instructions = build_instructions(obj, query)
    for i, (_, arg) in enumerate(instructions[:-1]):
        _type = instructions[i + 1][0]
        obj = _set(obj, _type, arg)

    _type, arg = instructions[-1]
    _set(obj, _type, arg, val)

def _set(obj, _type, arg, val=None):
    """
    Helper function for calling obj.__setitem__(arg, val or _type()).
    """
    if val is not None:
        # Time to set our value
        _type = type(val)

    if isinstance(obj, dict):
        if arg not in obj:
            # If key isn't in obj, initialize it with _type()
            # or set it with val
            obj[arg] = (_type() if val is None else val)
        obj = obj[arg]
    elif isinstance(obj, list):
        n = len(obj)
        arg = int(arg)
        if n > arg:
            obj[arg] = (_type() if val is None else val)
        else:
            # Need to amplify our list, initialize empty values with _type()
            obj.extend([_type() for x in range(arg - n + 1)])
        obj = obj[arg]
    return obj

rawDescription: Python recursive setattr()-like function for working with nested dictionaries


code:
from collections import defaultdict
sample = '''\
1  123  something else
2  234  something else
3  500  something else
1  891  something else
2  234  something else
3  567  something else
'''.splitlines()
sums = defaultdict(int)
for line in sample:
    col1, col2, rest = line.split(None, 2)
    sums[col1] += int(col2)

sums

rawDescription: Summation of specific items in a nested list


code:
#! /usr/bin/env python
from __future__ import print_function

addr = 204
val = 123
print('%s, %s' % (hex((addr << 1) & 0x7E), hex(val)))

rawDescription: Python print formatted byte(s)

description: Python print formatted byte(s)


code:
import sys
import csv
from io import StringIO
sample = StringIO('''\
Keyword,Source,Number
Lions Tigers Bears,US,3
Dogs Zebra,Canada,5
Sharks Guppies,US,2
''')
output = StringIO()
reader = csv.DictReader(sample)
writer = csv.DictWriter(output, fieldnames=reader.fieldnames)
for row in reader:
    words = row['Keyword'].split()
    row['Keyword'] = words[0]
    writer.writerow(row)
    writer.writerows({'Keyword': w} for w in words[1:])

print(output.getvalue())

rawDescription: Find a specific header in a CSV file using python 3 code


code:
json_data = '{"bear": 2, "apple": 1}'
d = json.loads(json_data)
d['bear']

rawDescription: Import a exported dict into python

description: Import a exported dict into python


rawDescription: How to remove specific directory names from path list

description: Remove specific directory names from path list


code:
from tkinter.filename import askopenfilename as ask
fname = ask()  # you might want to pass a beginning directory

rawDescription: How to open a text file with Python GUI?

description: Open a text file with Python GUI


code: sorted(d,key=lambda x: [int(y) for y in x.split('-')])

rawDescription: Sort python dictionary by Keys formatted as strings


code:
def normal(sent):
    return ".".join(" " + s if i > 0 and s[0].isalpha() else s for i, s in enumerate(sent.split(".")))

rawDescription: operating over strings, python

description: Operating over strings, python


code:
def countcalls(f):
    "Decorator that makes the function count calls to it."
    def _f(*args, **kwargs):
        _f._count += 1
        return f(*args, **kwargs)
    _f._count = 0
    return _f

@countcalls
def g(x): return x

@countcalls
def f1(x): return 0

@countcalls
def f2(x): return x

def report_calls(*funcs):
    print(' | '.join(['{} calls to {}'.format(f._count, f.func_name)
                      for f in funcs]))

L = range(10)[::-1]

L.sort(key=make_lazy(f1, g))
report_calls(f1, g)

g._count = 0
L.sort(key=make_lazy(f2, g))
report_calls(f2, g)

rawDescription: Avoiding unnecessary key evaluations when sorting a list


code:
import argparse
import sys

def parse_args(lists):
    funcs = {
        'createCsv': (createCsv, lists['file_list']),
        'resizeImage': (resizeImage, lists['resized']),
        'optimiseImage': (optimiseImage, lists['size_issues']),
        'dimensionIssues': (dimensionIssues, lists['dim_issues']),
        'controlInput': (controlInput, lists)
    }
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-l", "--list",
        dest='funcs', action="append_const", const=funcs['createCsv'],
        help="Create CSV of images",)
    parser.add_argument(
        "-c", "--convert",
        dest='funcs', action="append_const", const=funcs['resizeImage'],
        help="Convert images from 1500 x 2000px to 900 x 1200px ",)
    parser.add_argument(
        "-o", "--optimise",
        dest='funcs', action="append_const", const=funcs['optimiseImage'],
        help="Optimise filesize for 900 x 1200px images",)
    parser.add_argument(
        "-d", "--dimensions",
        dest='funcs', action="append_const", const=funcs['dimensionIssues'],
        help="Copy images with incorrect dimensions to new directory",)
    parser.add_argument(
        "-i", "--interactive",
        dest='funcs', action="append_const", const=funcs['controlInput'],
        help="Run script in interactive mode",)
    args = parser.parse_args()
    if not args.funcs:
        args.funcs = [funcs[task] for task in
                      ('createCsv', 'resizeImage', 'optimiseImage', 'dimensionIssues')]
    return args

if __name__ == '__main__':
    lists = analyseImages()

    if not lists:
        sys.exit('No jpegs found')

    args = parse_args(lists)
    statusTable(lists)
    for func, args in args.funcs:
        func(args)

rawDescription: python argparse set behaviour when no arguments provided

description: Python argparse set behaviour when no arguments provided


code: terms = np.power(x, degrees)

rawDescription: Calculating "generating functions" with numpy


code:
import os
import glob
import pandas as pd

def get_merged_csv(flist, **kwargs):
    return pd.concat([pd.read_csv(f, **kwargs) for f in flist], ignore_index=True)

path = 'C:/Users/csvfiles'
fmask = os.path.join(path, '*nba*.csv')

df = get_merged_csv(glob.glob(fmask), index_col=None, usecols=['rank', 'name'])

print(df.head())

rawDescription: Reading multiple csv files, concatenate list of file names them into a singe DataFrame


code:
def myValue(self, whatever):
    pass
myAppObjDict['myValue'] = myValue

# Assume that myAppObjDict is already initialized.
myAppObj=type("myAppClass", (object,),myAppObjDict)

rawDescription: Adding methods in type() generated objects in python


code:
# script
rf = open("wordlist.txt")
wf = open("newwordlist.txt","w")
for line in rf:
    newline = line.rstrip('\r\n')
    wf.write(newline)
    wf.write('\n')  # remove to leave out line breaks
rf.close()
wf.close()

rawDescription: Delete newline / return carriage in file output


code:
#! /usr/bin/env python3
import argparse
import socket

def main():
    parser = argparse.ArgumentParser(description='Execute a UDP client demo.')
    parser.add_argument('host', type=str, help='computer where data is sent')
    parser.add_argument('port', type=int, help='location where server listens')
    arguments = parser.parse_args()
    address = arguments.host, arguments.port
    client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    for _ in range(5):
        message = input('>>> ').encode('ascii')
        client.sendto(message, address)
        response = client.recv(1 << 12).decode('ascii')
        print(response)

if __name__ == '__main__':
    main()

rawDescription: Repeating Communications Over UDP

description: Repeating Communications Over UDP


code:
user = Profile.objects.get(pk=1)
hobbies = user.hobbies.all()

rawDescription: Defining class relations in django

description: Defining class relations in django


code:
for url in my_list:
    soup = BeautifulSoup(urllib2.urlopen(url).read())
    # then parse each page individually here

rawDescription: Web crawler - following links

description: Web crawler - following links


code:
from PySide import QtGui

class MainController(object):

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

    # called from view class
    def change_running(self, checked):
        # put control logic here
        self.model.running = checked
        self.model.announce_update()

rawDescription: MVC design with QtDesigner and PySide

description: MVC design with QtDesigner and PySide


code:
from matplotlib import rc

rc('font', **{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)

rawDescription: Typing Greek letters etc. in Python plots


code:
def VisitNode(self, node, target):
    # Base case. If we found the target, return target in a list
    if node == target:
        return [node]

    # If we're at a leaf and it isn't the target, return None
    if len(self.neighbors(node)) == 0:
        return None

    # recursively iterate over children
    for i in self.neighbors_iter(node):
        tail = self.VisitNode(i, target)
        if tail: # is not None
            return [node] + tail # prepend node to path back from target
    return None #none of the children contains target

rawDescription: Finding the (guaranteed unique) path between two nodes in a tree


code:
urlpatterns = [
    url(r'^permalink/(?P<id>\d+)/foo/$',
        RedirectView.as_view(pattern_name="target_view"),
        name="original_view"),
    url(r'^permalink/(?P<id>\d+)/$', views.permalink, name="target_view"),
]

rawDescription: How to redirect url pattern with variables from urls.py in Django?

description: Redirect url pattern with variables from urls.py in Django


rawDescription: Create multiple plots using pyplot and gridspec on separate 'windows'?


code:
def foo(bar):
    def spam():
        return bar + 42
    return spam

foo(0)
foo(0)()
def ham(eggs):
    result = foo(eggs + 3)()
    return result

ham(38)

rawDescription: How to call a function that is nested in python

description: Call a function that is nested in python


code:
def checkEqual1(iterator):
  try:
     iterator = iter(iterator)
     first = next(iterator)
     return all(first == rest for rest in iterator)
  except StopIteration:
     return True

rawDescription: check if all elements in a list are identical

description: Check if all elements in a list are identical


code:
import pickle

lst = [1,2,3,4,5]

with open('file.pkl', 'wb') as pickle_file:
    pickle.dump(lst, pickle_file, protocol=pickle.HIGHEST_PROTOCOL)

rawDescription: What's the fastest way to save/load a large list in Python 2.7?


code:
class MyForm(ModelForm):
    # whatever you have there, then
    class Media:
        css = {
            'screen': ('foo.css', 'bar.css'),
        }
        js = ('jquery.js', 'myform.js')

rawDescription: How to include js and css only once

description: Include js and css only once


rawDescription: How to sort similar values in a sorted list (based on second value) of tuples based on another value(third value) in the tuple in descending order

description: Sort similar values in a sorted list (based on second value) of tuples based on another value(third value) in the tuple in descending order


code:
fig, ax = plt.subplots()
ax.bar(center, hist, align='center', width=width)
fig.savefig("1.png")

rawDescription: Histogram Matplotlib

description: Histogram Matplotlib


rawDescription: How to convert a word in string to binary

description: Convert a word in string to binary


code: names = list(filter(_f, names))

rawDescription: How to extract a common name from multipal filenames and delete something I don't want

description: Extract a common name from multipal filenames and delete something I don't want


code: soup.find_all('a', href=lambda x: 'Table_of_Contents' not in x)

rawDescription: Matching Against Unwanted Links

description: Matching Against Unwanted Links


code: {k:v for v in userplays.values() for k in v.keys()}.keys()

rawDescription: Build list using only list comprehensions, no function


rawDescription: Model friends table in Django

description: Model friends table in Django


code:
def f(x):
    "return the square of x"
    return x * x
f.__doc__
help(f)
f.__doc__ = "Return the argument squared"
help(f)

rawDescription: Is there a way to keep docstrings separate from the functions they document?


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

rawDescription: Python3, a lazy print

description: Python3, a lazy print


code:
data['a']        # Column with header 'a'
data[0]          # First row
data['c'][2]     # Specific element
data[['a', 'c']] # Two columns

rawDescription: Most Pythonic way to read csv values into dict of lists


code:
import urllib2
import cookielib
from BeautifulSoup import BeautifulSoup

cookiejar = cookielib.CookieJar()
opener = urllib2.build_opener(
    urllib2.HTTPRedirectHandler(),
    urllib2.HTTPHandler(debuglevel=0),
    urllib2.HTTPSHandler(debuglevel=0),
    urllib2.HTTPCookieProcessor(cookiejar),
)

rawDescription: Data from a custom Google Map

description: Data from a custom Google Map


code:
import urllib2
url = "http://graph.facebook.com/4/picture"
req = urllib2.Request(url)
res = urllib2.urlopen(req)
finalUrl = res.geturl()
finalUrl

rawDescription: Resolve FB GraphAPI picture call to the final URL


code:
encoded = unicodevalue.encode('utf8')
sliced = encoded[:1000]

rawDescription: python : read first 1000 bytes from a unicode string

description: Python : read first 1000 bytes from a unicode string


code:
df = pd.DataFrame(columns=["col1","col2","col3"]) #not necessary if every col appears
#at least once in the data
df = df.append([{"idx_col":2,"col1":2,"col2":3},{"idx_col":-1,"col3":22,"col1":4}])
#column order preserved

df = df.set_index("idx_col",drop=True).sort() #index order preserved now

rawDescription: Fastest Way to Populate a Pandas DataFrame When Order Matters


code:
from random import random

def slicer(longitude):
    alphabet = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    result = ""
    x = 0

    for i in range(1, int(longitude)):
        x = int(62 * random())
        string_section = alphabet[x]
        result = result + string_section
    return result

print(str(slicer(10)))  # get a 10 digit string

rawDescription: slicing dynamically in python

description: Slicing dynamically in python


rawDescription: Python tuple instead of list

description: Python tuple instead of list


rawDescription: How to replace prefix and postfix with regex in python

description: Replace prefix and postfix with regex in python


code:
if any(k == 'mohammed' and v == '123456789' for k,v in d.items()):
    print("Match")
else:
    print("No Match")

rawDescription: Unexpected Behaviour of if statement inside loop over d.items()


code:
from itertools import groupby
from operator import attrgetter
my_lists = [list(g) for _, g in groupby(sorted(objects, key=attrgetter('date')), attrgetter('date'))]

rawDescription: Turn list into list of lists using an object attribute


code:
from pygame.locals import *
flags = FULLSCREEN | DOUBLEBUF
screen = pygame.display.set_mode(resolution, flags, bpp)

rawDescription: Any way to speed up Python and Pygame?

description: Any way to speed up Python and Pygame


code:
raw_letters = raw_input('Input the letters: ')

# read out the entire contents of the file to search over
with open('TextFile.txt', 'r') as g:
    full_file = g.read()

# print each permutation that occurs somewhere in the file
for p in permutations(raw_letters):
    p_as_string = ''.join(p)
    if p_as_string in full_file:
        print(p_as_string)

rawDescription: searching the strings in a text file in another string

description: Searching the strings in a text file in another string


code:
#!/usr/bin/env python

import csv

little_ip_filename = "littleListIPs.csv"
big_ip_filename = "BigListIPs.csv"
output_filename = "results.csv"

# Load all the entries from BigListIPs into a set for quick lookup.
big_ips = set()

with open(big_ip_filename, 'r') as f:
    big_ip = csv.reader(f)
    for csv_row in big_ip:
        big_ips.add(csv_row[0])

# print big_ips

with open(little_ip_filename, 'r') as input_file, open(output_filename, 'w') as output_file:
    input_csv = csv.reader(input_file)
    output_csv = csv.writer(output_file)
    for csv_row in input_csv:
        ip = csv_row[0]
        status = "Present" if ip in big_ips else "Not Present"
        output_csv.writerow([ip, status + " in BigListIPs.csv"])

rawDescription: Comparing CSV matching rows with Python

description: Comparing CSV matching rows with Python


code:
from collections import defaultdict
output = defaultdict(TemporaryFile)
...
output[length].write(line)

rawDescription: Sorting csv by number of columns in each row


rawDescription: Python 2.5 - Update folder of text files from values stored in a lookup list


code:
lons, lats = m.shiftdata(lon, lat)
m.plot(lons, lats, color="blue", latlon=True, marker='.', linestyle='None')

rawDescription: Plotting a wrapped path in Basemap

description: Plotting a wrapped path in Basemap


rawDescription: Why is hardcoding this list slower than calculating it?


code: pd.DataFrame(np.where(df=='yes', 1, 0), columns=df.columns, index=df.index)

rawDescription: Converting strings into

description: Converting strings into


code:
class Student(models.Model):
    name = models.TextField()
    location = models.TextField(default="sample")

rawDescription: Django admin form overrding the default value


code:
from string import Template
class CustomTemplate(Template):
    delimiter = '{{'
    pattern = r'''
    \{\{(?:
    (?P<escaped>\{\{)|
    (?P<named>[_a-z][_a-z0-9]*)\}\}|
    (?P<braced>[_a-z][_a-z0-9]*)\}\}|
    (?P<invalid>)
    )
    '''

    def safe_substitute(self, *args, **kws):
        if len(args) > 1:
            raise TypeError('Too many positional arguments')
        if not args:
            mapping = kws
        elif kws:
            mapping = _multimap(kws, args[0])
        else:
            mapping = args[0]
        # Helper function for .sub()
        def convert(mo):
            named = mo.group('named') or mo.group('braced')
            if named is not None:
                try:
                    # We use this idiom instead of str() because the latter
                    # will fail if val is a Unicode containing non-ASCII
                    return '%s' % (mapping[named],)
                except KeyError:
                    return mo.group()
            if mo.group('escaped') is not None:
                return self.delimiter
            if mo.group('invalid') is not None:
                return mo.group()
            raise ValueError('Unrecognized named group in pattern',
                             self.pattern)
        return self.pattern.sub(convert, self.template)

replacement_dict = {
    "test": "hello"
}

tpl = '''{
    "escaped": "{{{{",
    "unaltered": "{{foo}}",
    "replaced": "{{test}}",
    "invalid": "{{az"
}'''

a = CustomTemplate(tpl)
b = a.safe_substitute(replacement_dict)

print (b)

rawDescription: Python template safe substitution with the custom double-braces format


rawDescription: How elegantly to call methods with various order?


code:
with open(file) as f:
    for line in f:
        # slice the next 6 lines from the iterable, as a list.
        lines = [line] + list(itertools.islice(f, 6))
        jfile = json.loads(''.join(lines))

        # do something with jfile

rawDescription: Python: Trying to Deserialize Multiple JSON objects in a file with each object spanning multiple but consistently spaced number of lines


code:
from scrapy.contrib.loader.processor import MapCompose
from scrapy.item import Item, Field
from w3lib.html import remove_tags

class MyItem(Item):
    my_field = Field(input_processor=MapCompose(remove_tags))

rawDescription: Get xpath() to return empty values

description: Get xpath() to return empty values


rawDescription: Comparing List to Dictionary in Python

description: Comparing List to Dictionary in Python


rawDescription: Use parentheses or not for multiple variable assignment in Python?


code:
import collections
with open(p) as f:
    indx = collections.Counter()
    buffer = f.read(1024)
    while buffer:
        indx.update(buffer)
        buffer = f.read(1024)

rawDescription: Count every character from file

description: Count every character from file


rawDescription: Python: List is a int, TypeError

description: Python: List is a int, TypeError


code:
from IPython import get_ipython
ipython = get_ipython()

rawDescription: How to run an IPython magic from a script (or timing a Python script)

description: Run an IPython magic from a script (or timing a Python script)


code:
with open('inFile.txt', 'r') as inFile, open('outfile.txt', 'w') as outFile:
    outFile.writelines(line + '\n' for line in inFile.readline().split('\t'))

rawDescription: Write first row from .txt-file as a column in new .txt-file


code:
from collections import Counter
counter = Counter(deck)
the_same = []
for i in counter:
    if counter[i] > 1:
        the_same.extend([i] * counter[i])

rawDescription: how to make a script recognize number which are the same in python 3.3

description: Make a script recognize number which are the same in python 3.3


rawDescription: how to access key values in a json files dictionaries with python

description: Access key values in a json files dictionaries with python


code:
color_labels = index[:int_colors.size]
key_labels = index[-len(color2ind):]

rawDescription: Convert a 3D array to 2D array based on dictionary


code: gdata.service.RequestError: {'status': 400, 'body': 'You cannot request beyond item 1000.', 'reason': 'Bad Request'}

rawDescription: How to get all YouTube comments with Python's gdata module?

description: Get all YouTube comments with Python's gdata module


code:
# Return the longest prefix of all list elements.
def commonprefix(m):
    "Given a list of pathnames, returns the longest common leading component"
    if not m: return ''
    s1 = min(m)
    s2 = max(m)
    for i, c in enumerate(s1):
        if c != s2[i]:
            return s1[:i]
    return s1

rawDescription: Return leading string common to (the start of) words in a list in python


code:
def compare( fileA, fileB ):
    a_file = open(fileA, 'r')
    a_data = a_file.read()
    a_file.close()

    b_file = open(fileB, 'r')
    b_data = b_file.read()
    b_file.close()

    # compare the contents
    a_set = set(a_data.split(','))
    b_set = set(b_data.split(','))

    return list(a_set.intersection(b_set))

compare('more.csv', 'less.csv')

rawDescription: Compare two csv file content and store the similar into variable


code: numpy.ma.average(numpy.ma.masked_invalid(x).reshape(-1, 2, x.shape[-1]), 1)

rawDescription: Average two rows in Python while ignoring NaN


code: posts = relationship('Post', back_populates='article', lazy='dynamic', query_class=PostClassQuery)

rawDescription: SQLAlchemy dynamic & customized Collection Class


code: df = pd.read_csv('qs.d.ieutio1m.csv', sep=';', header=4, na_values=['ND']).dropna()

rawDescription: pandas: skip strings when loading a csv

description: Pandas: skip strings when loading a csv


code:
import numpy as np

a = np.array([True, False])
b = np.array([1, 2, 3, 4])
b.shape = (2,2)
print(b[a])
# [[1 2]]

rawDescription: numpy: broadcasting ndarray of booleans

description: Numpy: broadcasting ndarray of booleans


code:
mults = itertools.cycle([1,-1])
answer = 0
for elem, mult in zip(L, mults):
    answer += elem, mult

rawDescription: Alternating sum of integers in Python using lambda


code:
global theserver
theserver = ForwardServer(('', local_port), SubHander)
theserver.serve_forever()

rawDescription: Shutting Down SSH Tunnel in Paramiko Programatically


code:
from sqlalchemy import func
func.avg(...)
func.sum(...)
func.max(...)

rawDescription: Database-Independent MAX() Function in SQLAlchemy


code:
def output_format(the_dict):

    output = ''
    for k, v in the_dict.iteritems():
        output += '{} : {}\n'.format(k, the_dict[k])

    return output + '\n'

rawDescription: Python text file data extraction

description: Python text file data extraction


code:
a, b = Foo(5), Foo(7)
Foo.crunch_all()
a.new_value
b.new_value

rawDescription: Apply a function to all instances of a class


code:
from collections import defaultdict

solution = defaultdict(list) # create defaultdict with default value []
for item in my_problem:
    solution[item[0]].append(list(item[1:]))

rawDescription: List of three-tuples to a dictionary of list of lists


code:
class CommonNames(object):
    C1 = 'c1'
    C2 = 'c2'
    C3 = 'c3'

[value for name, value in vars(CommonNames).iteritems() if not name.startswith('_')]

rawDescription: Getting all constants within a class in python


code:
# import required modules
import numpy as np
from scipy.cluster.vq import kmeans2

# generate clouds of 2D normally distributed points
N = 6000000 # number of points in each cluster

# cloud 1: mean (0, 0)
mean1 = [0, 0]
cov1  = [[1, 0], [0, 1]]
x1,y1 = np.random.multivariate_normal(mean1, cov1, N).T

# cloud 2: mean (5, 5)
mean2 = [5, 5]
cov2  = [[1, 0], [0, 1]]
x2,y2 = np.random.multivariate_normal(mean2, cov2, N).T

# merge the clouds and arrange into data points
xs, ys = np.concatenate( (x1, x2) ), np.concatenate( (y1, y2) )
points = np.array([xs, ys]).T

# cluster the points using k-means
centroids, clusters = kmeans2(points, k=2)

rawDescription: Parse list of x,y coordinates and detect continious areas


rawDescription: Zeroing-out array values outside of a centered slice


rawDescription: Simple ajax request to save variable to django backend from template


code:
def f(a, b, c):
    return a and b and c

def g(a, b, c):
    return a and (b and c)

from dis import dis
dis(f)
dis(g)

rawDescription: When has ast.BoolOp more than two values?


code: [i for i in json_object[u'results'] if any(w in i[u'format'] for w in wanted)]

rawDescription: Python JSON How to filter returned data

description: Python JSON How to filter returned data


code: deck.append(Card(num, suite))

rawDescription: How to approach implementing 'class Card' as required by Python textbook

description: Approach implementing 'class Card' as required by Python textbook


code:
for x, y in zip(g1, g2):
    print(x[0], y[0])

rawDescription: How to join/merge two generators output using python

description: Join/merge two generators output using python


code:
def f(x, y, n=3):
    return int(min(x, y) * n) + 1

rawDescription: How to return value for different layers of (x,y) levels

description: Return value for different layers of (x,y) levels


code: m = re.compile(r'\d{%d}:\d{%d}' % (var1, var2))

rawDescription: How to use in python regular expression

description: Use in python regular expression


code:
@timeit
def tst_1():
    for i in range(1000000):
        dt = datetime.datetime.now()
        mystr=""
        mystr+=hex(dt.year)
        mystr+=hex(dt.month)
        mystr+=hex(dt.day)
        mystr+=hex(dt.hour)
        mystr+=hex(dt.minute)
        mystr+=hex(dt.second)
        #print mystr

@timeit
def tst_2():
    for i in range(1000000):
        dt = datetime.datetime.now()
        dt = dt.strftime('%Y%m%d%H%M%S')
        t = dt.decode("hex")
        #print list(t)

rawDescription: Convert time-string into individual hex bytes


rawDescription: How to forbid two conflicting options

description: Forbid two conflicting options


code: {pnum:{c['comment_id']:c['comment'] for c in cs} for pnum,cs in temp.items()}

rawDescription: Pythonic ways to re-group / pivot database output


code:
def mywidget(field, value):
    return CAT(INPUT(_name=field.name,
                     _id='%s_%s' % (field._tablename, field.name),
                     _class=field.type,
                     _value=value, requires=field.requires),
               A('Add', _onclick='add()'),
               A('Remove', _onclick='remove()'))
...

Field('yourref', type='string', label=T('Your reference'),
      widget=mywidget)

rawDescription: web2py CRUD.create() field represenation in forms

description: Web2py CRUD.create() field represenation in forms


code: first_td = table.find('td')

rawDescription: Beautiful Soup [Python] and the extracting of text in a table


rawDescription: Creating random binary files

description: Creating random binary files


code: Document = namedtuple('Document', 'title metadata data')

rawDescription: psycopg2 + stored procedure + compound type

description: Psycopg2 + stored procedure + compound type


code:
class StoppableThread(threading.Thread):

    def __init__(self, target, timeout):
        super(StoppableThread, self).__init__()
        self._target = target
        self._timeout = timeout
        self._stop = threading.Event()

    def run(self):
        while not self.stopped():
            self._stop.wait(self._timeout)  # instead of sleeping
            if self.stopped():
                continue
            self._target()

    def stop(self):
        self._stop.set()

    def stopped(self):
        return self._stop.isSet()

rawDescription: Python terminate a thread when it is sleeping


code:
Person().sayHello
Person().sayHello

rawDescription: Why does the 'is' operator say these methods aren't the same?


code: b = spread(a,2,j)

rawDescription: broadcast an array to different shape (adding "fake" dimensions)

description: Broadcast an array to different shape (adding "fake" dimensions)


code:
from binascii import hexlify, unhexlify
input1 = "1c0111001f010100061a024b53535009181c"
input2 = "686974207468652062756c6c277320657965"
bytes1, bytes2 = unhexlify(input1), unhexlify(input2)
xor_bytes = bytes([b1 ^ b2 for b1, b2 in zip(bytes1, bytes2)])
xor_bytes
hexlify(xor_bytes).decode('ascii')

rawDescription: How to convert from binary to bytes to hex in Python 3?

description: Convert from binary to bytes to hex in Python 3


code:
from scrapy.contrib.downloadermiddleware.useragent import UserAgentMiddleware
from scrapy.exceptions import IgnoreRequest
from scrapy import log

class FilterURLs(object):
    def process_response(self,request, response, spider):
        if response.status == 301 :
            return response
        else:
            headers = ['text/html; charset=UTF-8', 'text/html; charset=utf-8', 'text/html;charset=UTF-8', 'text/html;charset=utf-8','text/html;charset=ISO-8859-1','application/xhtml+xml; charset=utf-8']
            log.msg("In Middleware " + repr(response.headers['Content-Type']), level=log.INFO)
            for header in headers:
                if response.headers['Content-Type'] != header:
                    log.msg("Ignoring response %r" % request)
                    raise IgnoreRequest()
                else:
                    return response

rawDescription: Allow redirects in Scrapy

description: Allow redirects in Scrapy


code:
from io import BytesIO
import PIL
from IPython.display import display, Image

def display_img_array(ima):
    im = PIL.Image.fromarray(ima)
    bio = BytesIO()
    im.save(bio, format='png')
    display(Image(bio.getvalue(), format='png'))

for ima in images:
    display_img_array(ima)

rawDescription: Display multiple images in one IPython Notebook cell?


code:
A-B
A-C
A-D
A-E
B-C
B-D
B-E
C-D
C-E
D-E

rawDescription: Python non-repeat loop

description: Python non-repeat loop


code: f"{GLOBAL_VAR} {local_var}" # No format(), locals(), or globals()!

rawDescription: Templating with both local and global variables using Python `format`


rawDescription: Numpy: Multiple Outer Products

description: Numpy: Multiple Outer Products


code: User.query.filter_by(id=post.id).first() # Does Not return user_name but returns the user object

rawDescription: Referencing values using foreign key on flask sql-alchemy


code:
spam = 'print(3)'
eggs = compile(spam, '<string>', 'exec')
exec(eggs)

rawDescription: Possible to execute Python bytecode from a script?


code:
QColor(.3* color1.red()   + .7 * color2.red(),
       .3* color1.green() + .7 * color2.green(),
       .3* color1.blue()  + .7 * color2.blue(),
       .3* color1.alpha() + .7 * color2.alpha()
      )

rawDescription: Mixing colors in PyQt?

description: Mixing colors in PyQt


code:
im = Image.open(path).convert("RGBA")
separateB = separateBlobs(im, blobs)

rawDescription: Selecting circle areas on image for further processing


code:
class TestSomeFeatureWithDataXY(testbase.TestSomeFeature):
    test_data_A = XY

rawDescription: A long definition of an object inside a Python unit test


code:
class Main(list):

    def doObjects(self, list1):
        self.list1 = list1
        mib = Mib()
        self.list1.append(MibObject('MY-MIB', 'testDescription', mib.getTestDescription))
        self.list1.append(MibObject('MY-MIB', 'testCount', mib.getTestCount))
        return self.list1

rawDescription: Return the list is empty python

description: Return the list is empty python


rawDescription: Python access to first element in dictionary


code: assert getattr(MyClass.my_method, "__wrapped__").__name__ == 'my_method'

rawDescription: How to assert that a method is decorated with python unittest?

description: Assert that a method is decorated with python unittest


code:
string = ''.join([chr(i) for i in range(0x100)])
string.encode('latin-1') == bytes(map(ord, string))

rawDescription: Why is it true that string.encode('utf-8') != bytes(map(ord, string))?


code:
def main():
    beanstalk = beanstalkc.Connection(host='localhost', port=11300)
    jid = beanstalk.put('foo', delay=5)

if __name__ == '__main__':
    main()

rawDescription: How can I schedule an email to be sent at some point in the future in django?

description: Schedule an email to be sent at some point in the future in django


code:
not cached
9
cached
9
cached
cached
9
not cached
10
cached
10

rawDescription: Memoize a NumPy vectorized function

description: Memoize a NumPy vectorized function


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

# simulate some artificial data
# =====================================
df = pd.DataFrame( { 'Age' : np.random.rand(25) * 160 } )

df['Length'] = df['Age'] * 0.88 + np.random.rand(25) * 5000

# plot those data points
# ==============================
fig, ax = plt.subplots()
ax.scatter(df['Length'], df['Age'])

# Now add on a line with a fixed slope of 0.03
slope = 0.03

# A line with a fixed slope can intercept the axis
# anywhere so we're going to have it go through 0,0
x_0 = 0
y_0 = 0

# And we'll have the line stop at x = 5000
x_1 = 5000
y_1 = slope (x_1 - x_0) + y_0

# Draw these two points with big triangles to make it clear
# where they lie
ax.scatter([x_0, x_1], [y_0, y_1], marker='^', s=150, c='r')

# And now connect them
ax.plot([x_0, x_1], [y_0, y_1], c='r')

plt.show()

rawDescription: Adding a line to a matplotlib scatterplot based on a slope


code:
import socket
import re
f = open('/etc/hosts')
host_name =  socket.gethostname()
host_name
for x in f:
    print(x)
    if re.search(host_name,x):
        print("found")

rawDescription: Python - using variable in regex

description: Python - using variable in regex


code:
not cmp(x, y)
not cmp(x, z)

rawDescription: Equality without using operator

description: Equality without using operator


code: u = urllib.unquote(s).decode('utf-8')

rawDescription: Convert multichar %xx escapes to unicode


code:
-- sent_message_id - usercellphone_id
-- 38 - 45
-- 38 - 67

rawDescription: Send messages to multiple users

description: Send messages to multiple users


code:
expected = re.compile(r'session \d+: running task\(s\)')
str= "session 1234567890: running(s)"
re.match(expected, str)

rawDescription: Match number with variable number of digits


code:
ip_subtasks = group(
        [resolve_hostname.s(hostname, resolver=resolver)
         for hostname in required_hosts.REQUIRED_HOSTS.keys()]
    ).delay()

rawDescription: Celery: One subtask in group always timesout


message: [encoded data, 12108 characters]

rawDescription: How to Define Google Endpoints API File Download Message Endpoint


code:
DCOM_ERROR_CONSTANTS = {
    1726:'RPC_S_CALL_FAILED',
    0:'WBEM_NO_ERROR',
    0x40001:'WBEM_S_ALREADY_EXISTS',
    0x40002:'WBEM_S_RESET_TO_DEFAULT',
    0x40003:'WBEM_S_DIFFERENT',
    0x40004:'WBEM_S_TIMEDOUT',
    0x40005:'WBEM_S_NO_MORE_DATA',
    0x40006:'WBEM_S_OPERATION_CANCELLED',
    0x40007:'WBEM_S_PENDING',
    0x40008:'WBEM_S_DUPLICATE_OBJECTS',
    0x40009:'WBEM_S_ACCESS_DENIED',
    0x40010:'WBEM_S_PARTIAL_RESULTS',
    0x40011:'WBEM_S_NO_POSTHOOK',
    0x40012:'WBEM_S_POSTHOOK_WITH_BOTH',
    0x40013:'WBEM_S_POSTHOOK_WITH_NEW',
    0x40014:'WBEM_S_POSTHOOK_WITH_STATUS',
    0x40015:'WBEM_S_POSTHOOK_WITH_OLD',
    0x40016:'WBEM_S_REDO_PREHOOK_WITH_ORIGINAL_OBJECT',
    0x40017:'WBEM_S_SOURCE_NOT_AVAILABLE',
    0x80041001:'WBEM_E_FAILED',
    0x80041002:'WBEM_E_NOT_FOUND',
    0x80041003:'WBEM_E_ACCESS_DENIED',
    0x80041004:'WBEM_E_PROVIDER_FAILURE',
    0x80041005:'WBEM_E_TYPE_MISMATCH',
    0x80041006:'WBEM_E_OUT_OF_MEMORY',
    0x80041007:'WBEM_E_INVALID_CONTEXT',
    0x80041008:'WBEM_E_INVALID_PARAMETER',
    0x80041009:'WBEM_E_NOT_AVAILABLE',
    0x8004100A:'WBEM_E_CRITICAL_ERROR',
    0x8004100B:'WBEM_E_INVALID_STREAM',
    0x8004100C:'WBEM_E_NOT_SUPPORTED',
    0x8004100D:'WBEM_E_INVALID_SUPERCLASS',
    0x8004100E:'WBEM_E_INVALID_NAMESPACE',
    0x8004100F:'WBEM_E_INVALID_OBJECT',
    0x80041010:'WBEM_E_INVALID_CLASS',
    0x80041011:'WBEM_E_PROVIDER_NOT_FOUND',
    0x80041012:'WBEM_E_INVALID_PROVIDER_REGISTRATION',
    0x80041013:'WBEM_E_PROVIDER_LOAD_FAILURE',
    0x80041014:'WBEM_E_INITIALIZATION_FAILURE',
    0x80041015:'WBEM_E_TRANSPORT_FAILURE',
    0x80041016:'WBEM_E_INVALID_OPERATION',
    0x80041017:'WBEM_E_INVALID_QUERY',
    0x80041018:'WBEM_E_INVALID_QUERY_TYPE',
    0x80041019:'WBEM_E_ALREADY_EXISTS',
    0x8004101A:'WBEM_E_OVERRIDE_NOT_ALLOWED',
    0x8004101B:'WBEM_E_PROPAGATED_QUALIFIER',
    0x8004101C:'WBEM_E_PROPAGATED_PROPERTY',
    0x8004101D:'WBEM_E_UNEXPECTED',
    0x8004101E:'WBEM_E_ILLEGAL_OPERATION',
    0x8004101F:'WBEM_E_CANNOT_BE_KEY',
    0x80041020:'WBEM_E_INCOMPLETE_CLASS',
    0x80041021:'WBEM_E_INVALID_SYNTAX',
    0x80041022:'WBEM_E_NONDECORATED_OBJECT',
    0x80041023:'WBEM_E_READ_ONLY',
    0x80041024:'WBEM_E_PROVIDER_NOT_CAPABLE',
    0x80041025:'WBEM_E_CLASS_HAS_CHILDREN',
    0x80041026:'WBEM_E_CLASS_HAS_INSTANCES',
    0x80041027:'WBEM_E_QUERY_NOT_IMPLEMENTED',
    0x80041028:'WBEM_E_ILLEGAL_NULL',
    0x80041029:'WBEM_E_INVALID_QUALIFIER_TYPE',
    0x8004102A:'WBEM_E_INVALID_PROPERTY_TYPE',
    0x8004102B:'WBEM_E_VALUE_OUT_OF_RANGE',
    0x8004102C:'WBEM_E_CANNOT_BE_SINGLETON',
    0x8004102D:'WBEM_E_INVALID_CIM_TYPE',
    0x8004102E:'WBEM_E_INVALID_METHOD',
    0x8004102F:'WBEM_E_INVALID_METHOD_PARAMETERS',
    0x80041030:'WBEM_E_SYSTEM_PROPERTY',
    0x80041031:'WBEM_E_INVALID_PROPERTY',
    0x80041032:'WBEM_E_CALL_CANCELLED',
    0x80041033:'WBEM_E_SHUTTING_DOWN',
    0x80041034:'WBEM_E_PROPAGATED_METHOD',
    0x80041035:'WBEM_E_UNSUPPORTED_PARAMETER',
    0x80041036:'WBEM_E_MISSING_PARAMETER_ID',
    0x80041037:'WBEM_E_INVALID_PARAMETER_ID',
    0x80041038:'WBEM_E_NONCONSECUTIVE_PARAMETER_IDS',
    0x80041039:'WBEM_E_PARAMETER_ID_ON_RETVAL',
    0x8004103A:'WBEM_E_INVALID_OBJECT_PATH',
    0x8004103B:'WBEM_E_OUT_OF_DISK_SPACE',
    0x8004103C:'WBEM_E_BUFFER_TOO_SMALL',
    0x8004103D:'WBEM_E_UNSUPPORTED_PUT_EXTENSION',
    0x8004103E:'WBEM_E_UNKNOWN_OBJECT_TYPE',
    0x8004103F:'WBEM_E_UNKNOWN_PACKET_TYPE',
    0x80041040:'WBEM_E_MARSHAL_VERSION_MISMATCH',
    0x80041041:'WBEM_E_MARSHAL_INVALID_SIGNATURE',
    0x80041042:'WBEM_E_INVALID_QUALIFIER',
    0x80041043:'WBEM_E_INVALID_DUPLICATE_PARAMETER',
    0x80041044:'WBEM_E_TOO_MUCH_DATA',
    0x80041045:'WBEM_E_SERVER_TOO_BUSY',
    0x80041046:'WBEM_E_INVALID_FLAVOR',
    0x80041047:'WBEM_E_CIRCULAR_REFERENCE',
    0x80041048:'WBEM_E_UNSUPPORTED_CLASS_UPDATE',
    0x80041049:'WBEM_E_CANNOT_CHANGE_KEY_INHERITANCE',
    0x80041050:'WBEM_E_CANNOT_CHANGE_INDEX_INHERITANCE',
    0x80041051:'WBEM_E_TOO_MANY_PROPERTIES',
    0x80041052:'WBEM_E_UPDATE_TYPE_MISMATCH',
    0x80041053:'WBEM_E_UPDATE_OVERRIDE_NOT_ALLOWED',
    0x80041054:'WBEM_E_UPDATE_PROPAGATED_METHOD',
    0x80041055:'WBEM_E_METHOD_NOT_IMPLEMENTED',
    0x80041056:'WBEM_E_METHOD_DISABLED',
    0x80041057:'WBEM_E_REFRESHER_BUSY',
    0x80041058:'WBEM_E_UNPARSABLE_QUERY',
    0x80041059:'WBEM_E_NOT_EVENT_CLASS',
    0x8004105A:'WBEM_E_MISSING_GROUP_WITHIN',
    0x8004105B:'WBEM_E_MISSING_AGGREGATION_LIST',
    0x8004105C:'WBEM_E_PROPERTY_NOT_AN_OBJECT',
    0x8004105D:'WBEM_E_AGGREGATING_BY_OBJECT',
    0x8004105F:'WBEM_E_UNINTERPRETABLE_PROVIDER_QUERY',
    0x80041060:'WBEM_E_BACKUP_RESTORE_WINMGMT_RUNNING',
    0x80041061:'WBEM_E_QUEUE_OVERFLOW',
    0x80041062:'WBEM_E_PRIVILEGE_NOT_HELD',
    0x80041063:'WBEM_E_INVALID_OPERATOR',
    0x80041064:'WBEM_E_LOCAL_CREDENTIALS',
    0x80041065:'WBEM_E_CANNOT_BE_ABSTRACT',
    0x80041066:'WBEM_E_AMENDED_OBJECT',
    0x80041067:'WBEM_E_CLIENT_TOO_SLOW',
    0x80041068:'WBEM_E_NULL_SECURITY_DESCRIPTOR',
    0x80041069:'WBEM_E_TIMED_OUT',
    0x8004106A:'WBEM_E_INVALID_ASSOCIATION',
    0x8004106B:'WBEM_E_AMBIGUOUS_OPERATION',
    0x8004106C:'WBEM_E_QUOTA_VIOLATION',
    0x8004106D:'WBEM_E_RESERVED_001',
    0x8004106E:'WBEM_E_RESERVED_002',
    0x8004106F:'WBEM_E_UNSUPPORTED_LOCALE',
    0x80041070:'WBEM_E_HANDLE_OUT_OF_DATE',
    0x80041071:'WBEM_E_CONNECTION_FAILED',
    0x80041072:'WBEM_E_INVALID_HANDLE_REQUEST',
    0x80041073:'WBEM_E_PROPERTY_NAME_TOO_WIDE',
    0x80041074:'WBEM_E_CLASS_NAME_TOO_WIDE',
    0x80041075:'WBEM_E_METHOD_NAME_TOO_WIDE',
    0x80041076:'WBEM_E_QUALIFIER_NAME_TOO_WIDE',
    0x80041077:'WBEM_E_RERUN_COMMAND',
    0x80041078:'WBEM_E_DATABASE_VER_MISMATCH',
    0x80041079:'WBEM_E_VETO_DELETE',
    0x8004107A:'WBEM_E_VETO_PUT',
    0x80041080:'WBEM_E_INVALID_LOCALE',
    0x80041081:'WBEM_E_PROVIDER_SUSPENDED',
    0x80041082:'WBEM_E_SYNCHRONIZATION_REQUIRED',
    0x80041083:'WBEM_E_NO_SCHEMA',
    0x80041084:'WBEM_E_PROVIDER_ALREADY_REGISTERED',
    0x80041085:'WBEM_E_PROVIDER_NOT_REGISTERED',
    0x80041086:'WBEM_E_FATAL_TRANSPORT_ERROR',
    0x80041087:'WBEM_E_ENCRYPTED_CONNECTION_REQUIRED',
    0x80041088:'WBEM_E_PROVIDER_TIMED_OUT',
    0x80041089:'WBEM_E_NO_KEY',
    0x8004108a:'WBEM_E_PROVIDER_DISABLED',
    # not dcom, but frequently seen
    0x000006be: 'OPERATION_COULD_NOT_BE_COMPLETED',
}

rawDescription: In python, can a whole file be just a variable?


code:
from types import FunctionType

def isalambda(v):
    return isinstance(v, FunctionType) and v.__name__ == '<lambda>'

rawDescription: What is islambda function in python

description: What is islambda function in python


rawDescription: Extracting duplicate from array of dictionaries


code:
input = 'DEFAULT_GATEWAY=192.168.88.1&DELVRY_AGGREGATION_INTERVAL0=1&DELVRY_AGGREGATION_INTERVAL1=1&DELVRY_SCHEDULE0=1&DELVRY_SNI0=192.168.88.158&DELVRY_USE_SSL_TLS1=0&'
input.split('&')
[keyval.split('=') for keyval in input.split('&') if keyval]
dict(keyval.split('=') for keyval in input.split('&') if keyval)

rawDescription: Python Regex match string between specific string and end character


rawDescription: using an integer in a string to create a dictionary (or list) with that many numbers

description: Using an integer in a string to create a dictionary (or list) with that many numbers


code:
from pprint import pprint
t = (
  (1, -1, 'python'),
  (2, -1, 'ruby'),
  (3, -1, 'php'),
  (4, -1, 'lisp'),
  (5,  1, 'flask'),
  (6,  1, 'django'),
  (7,  1, 'webpy'),
  (8,  2, 'rails'),
  (9,  3, 'zend'),
  (10, 6, 'dblog')
)
l = []
entries = {}
for id, fid, title in t:
    entries[id] = entry = {'id': id, 'fid': fid, 'title': title}
    if fid == -1:
        l.append(entry)
    else:
        parent = entries[fid]
        parent.setdefault('son', []).append(entry)

pprint(l)

rawDescription: how to change a tuple into dictionary tree in python

description: Change a tuple into dictionary tree in python


code:
import os
from subprocess import Popen, PIPE
rfd, wfd = os.pipe()
p1 = Popen(['cat', 'some/file'], stdout=wfd)
p2 = Popen(['ls', 'some/path'], stdout=wfd)
os.close(wfd)
p3 = Popen(['wc', '-l'], stdin=rfd, stdout=PIPE)
print(p3.communicate()[0].decode())
os.close(rfd)

rawDescription: Python sh: merge results and pipe

description: Python sh: merge results and pipe


code:
s = "some\x00string. with\x15 funny characters"
import string
printable = set(string.printable)
filter(lambda x: x in printable, s)

rawDescription: How can I remove non-ASCII characters but leave periods and spaces using Python?

description: Remove non-ASCII characters but leave periods and spaces using Python


rawDescription: Does Python copy references to objects when slicing a list?


rawDescription: Best way to work out if a path is in an include or exclude list in python

description: Work out if a path is in an include or exclude list in python


code:
from bs4 import BeautifulSoup
import csv
import glob
import os

DATA_PATH = "c:\\file_path\\"
FILESPEC  = "*.htm"
OUTFILE   = "data.csv"

def main():
    data = []
    for fname in glob.glob(os.path.join(DATA_PATH, FILESPEC)):
        with open(fname) as inf:
            pg = BeautifulSoup(inf.read())
            for person in pg.findAll('td', {'class':'principal-col'}):
                data.append(get_data(person))
    data.sort()

    with open(os.path.join(DATA_PATH, OUTFILE), 'wb') as outf:
        outcsv = csv.writer(outf)
        outcsv.writerow(["Name", "Born", "Hired"])
        outcsv.writerows(data)

if __name__ == "__main__":
    main()

rawDescription: Parsing HTML Python, BeautifulSoup

description: Parsing HTML Python, BeautifulSoup


code: servqual != "great" or "good" or "lacking" or "poor"

rawDescription: Python: Repeating a function when raw_input is not valid


code:
def myfunc2(x, y):
    return myfunc(x) - y

rawDescription: Python find root for non-zero level

description: Python find root for non-zero level


code:
# Prints "ABCD"
for ch in map(chr,[65,66,67,68]):
    print(ch)

rawDescription: Getting a map() to return a list in Python 3.x


rawDescription: Compare rows then take rows out if neccessary


code:
import sys
with open(sys.argv[1]) as src, open(sys.argv[2]) as dest:
    for line in src:
        dest.write(line)

rawDescription: In python, how could I make this three line code into a one line code?


code:
from socket import socket, gethostname, error, SO_REUSEADDR, SOL_SOCKET
from sys import argv
import  errno

sock = socket()

# Create a socket object
host = gethostname()
# /proc/sys/net/ipv4/ip_local_port_range is  32768  61000 on my Ubuntu Machine
port = 60001
# allow connection in TIME_WAIT
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

try:
    sock.bind((host, port))
    sock.connect((host, port))
except error as e:
    # [Errno 99] Cannot assign requested address
    if e.errno == errno.EADDRNOTAVAIL:
        print("{} is already running".format(argv[0]))
        exit(1)
    # else raise the error
    else:
        raise e

# main body
from time import sleep

while True:
    print(1)
    sleep(2)

sock.close()

rawDescription: Checking running python script within the python script


code:
def reduce(function, arguments, initializer):
    a = initializer
    for b in arguments:
        a = function(a, b)
    return a

rawDescription: How to get values with any depth in dict via *args parameter? (python)

description: Get values with any depth in dict via *args parameter? (python)


rawDescription: Losing DST information using pytz and UTC conversions


code:
from itertools import combinations
def get_support(df):
    pp = []
    for cnum in range(1, len(df.columns)+1):
        for cols in combinations(df, cnum):
            s = df[list(cols)].all(axis=1).sum()
            pp.append([",".join(cols), s])
    sdf = pd.DataFrame(pp, columns=["Pattern", "Support"])
    return sdf

rawDescription: best way to implement Apriori in python pandas

description: Implement Apriori in python pandas


code:
def worst_indices(hash_size, key_list):
    # require at least one empty hash bucket
    assert(len(key_list) < hash_size)

    buckets = [False] * hash_size
    for key in key_list:
        index = key % hash_size
        index2 = index
        while buckets[index2]:
            index2 += 1
            if index2 == hash_size:
                index2 = 0
        buckets[index2] = True

    # find some empty bucket
    ix0 = buckets.index(False)

    # count the chain lengths
    lengths = [None] * hash_size
    ix = ix0
    length = 0
    while True:
        length = length + 1 if buckets[ix] else 0
        lengths[ix] = length
        ix = hash_size - 1 if ix == 0 else ix - 1
        if ix == ix0:
            break

    max_length = max(lengths)

    return [ix for ix in xrange(hash_size)
               if lengths[ix] == max_length]

rawDescription: Python Hash: Function to determine longest probe sequence


rawDescription: Regenerate vector of randoms in Python

description: Regenerate vector of randoms in Python


code:
def _template_func(setup, func):
    """Create a timer function. Used if the "statement" is a callable."""
    def inner(_it, _timer, _func=func):
        setup()
        _t0 = _timer()
        for _i in _it:
            _func()
        _t1 = _timer()
        return _t1 - _t0
    return inner

rawDescription: How can I capture return value with Python timeit module?

description: Capture return value with Python timeit module


code:
from IPython import parallel
from IPython import parallel as p

rc = p.Client()
rc[:].execute('import sys,os')
rc[:].execute('sys.path.append("../utils/")')
rc[:].execute('import Timezone as Timezone; tz = Timezone.Timezone()')

dview = rc[:] # A DirectView of all engines
dview.block = True

rawDescription: Passing class into iPython Parallel

description: Passing class into iPython Parallel


code:
def get_new_index(string, char_index):
    chars = 0
    for i, char in enumerate(string):
        if char != '-':
            chars += 1
        if char_index == chars:
            return i+1

rawDescription: How to process character by character in a line

description: Process character by character in a line


code:
with open("/etc/os-release") as f:
    d = {}
    for line in f:
        k,v = line.rstrip().split("=")
        d[k] = v
print(d)

rawDescription: module to parse a simple syntax in python

description: Module to parse a simple syntax in python


code: for a in list: print(a)

rawDescription: How do I make my list without brackets, commas, and have every element start on a new line?

description: Make my list without brackets, commas, and have every element start on a new line


code:
import scrapy
selector = scrapy.Selector(text="""Rue de Trazegnies 41
6031
      Monceau sur Sambre
BELGIQUE	""")
selector.xpath('.//td//text()').extract()
selector.xpath('string(.//td)').extract()

rawDescription: Scrapy get all children / ignore <br>?

description: Scrapy get all children / ignore <br>


code:
def decipher(s):
    options = [[rot(c, n) for c in s] for n in range(26)]
    scored_options = [[sum(map(letter_prob, x)), x] for x in options]
    best_option = max(options)
    return ''.join(best_option)

rawDescription: Deciphering My Cipher: Python Wizardry

description: Deciphering My Cipher: Python Wizardry


code:
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))
coord1, coord2 = xx1.ravel(), xx2.ravel()

rawDescription: Scikit-learn and data visusalisation: Why do I have to use ravel when I use predict?


rawDescription: beautiful soup get children that are Tags (not Navigable Strings) from a Tag

description: Beautiful soup get children that are Tags (not Navigable Strings) from a Tag


rawDescription: Extract date ("05/Jan/2014") from string


code: ls -1

rawDescription: Batch rename directories in reverse order


code:
s = ttk.Style()
bg = s.lookup('TFrame', 'background')

rawDescription: get default background of ttk.Frame

description: Get default background of ttk.Frame


code:
ip = get_ipython()
ip.config
ip.config['IPythonWidget']['font_family']

rawDescription: Getting Ipython QtConsole's current config infomation in it's interactive shell


code:
from sqlalchemy import Table
from sqlalchemy.orm import MetaData, mapper

metadata = MetaData()
metadata.bind = engine

person_table = Table(metadata, "tablename", autoload=True)

class Person(object):
    pass

mapper(Person, person_table)

rawDescription: SQLAlchemy - Models - using dynamic fields - ActiveRecord


code: g.WLPer.rank(pct=True, ascending=False)

rawDescription: percentile rank in pandas in groups

description: Percentile rank in pandas in groups


code:
@app.route('/web/account', methods=["GET"], endpoint="account_path")
@verify_session  #make sure to use any decorators after the route decorator
def account():
    return render_template('account')

rawDescription: How do you break Python Flask controller flow when calling return inside a function?

description: Break Python Flask controller flow when calling return inside a function


code:
def get_next(con):
    con.execute_query('UPDATE tableA SET done=1 OUTPUT INSERTED.ID WHERE ID=(SELECT TOP(1) ID FROM tableA WHERE done=0)')
    for row in con:
        #row['ID'] is exactly one ID where the done bit wasn't set, but now is.
        current_id = row['ID']
    return current_id

def start_function(id):
    #do something here with the id.
    pass

rawDescription: While mssql query returns an affected ID use it in a while loop


code: from scipy.ndimage import maximum_filter

rawDescription: python: Faster local maximum in 2-d matrix

description: Python: Faster local maximum in 2-d matrix


code:
for i in range(len(mylist)/size_x):
    print(mylist[i*size_x:(i+1)*size_x])

rawDescription: Printing list with set width in python

description: Printing list with set width in python


code: frame.bind("<Key>", key)

rawDescription: Binding number and operator buttons to calculator buttons


code:
def list_comp(l):
    return [x+1 for x in l]

def dict_comp(l):
    return {x+1:0 for x in l}

def set_comp(l):
    return {x+1 for x in l}

def generator(l):
    return (x+1 for x in l)

rawDescription: How do python Set Comprehensions work?

description: How do python Set Comprehensions work


code: value &= ~flag

rawDescription: Python equivalent of C# Enum.HasFlag

description: Python equivalent of C# Enum.HasFlag


code:
df_sub = df2.xs('y',level='variable3',axis=1,drop_level=False).ffill()
df_sub
df2.loc[:,df_sub.columns] = df_sub
df2

rawDescription: pandas - selecting a lower level in a DataFrame to do a ffill

description: Pandas - selecting a lower level in a DataFrame to do a ffill


code:
l = symbols('x1 x2 x3')
mat = diag(*l)-eye(3)+ones(3)

rawDescription: How to replace the the diagonal elements of a matrix by a vector in SymPy?

description: Replace the the diagonal elements of a matrix by a vector in SymPy


code:
from django.shortcuts import render

def quiz_score(request):
    context = {'score': request.GET['Score']}
    return render(request, 'quiz_score.html', context=context)

rawDescription: Accessing GET Form data from - Javascript Form in Django


rawDescription: Check for open text file

description: Check for open text file


code:
import nltk
s2 = 'at the Shift Series national conference, Compass Partners and fashion designer Kenneth Cole'
tokens2 = nltk.word_tokenize(s2)
tags = nltk.pos_tag(tokens2)
res = nltk.ne_chunk(tags)

rawDescription: regex approach to capture both 1-word and 2-word Proper Nouns

description: Regex approach to capture both 1-word and 2-word Proper Nouns


code:
isinstance(my_row, tuple)
# True

rawDescription: Iterating List of SQL.Row with PySpark

description: Iterating List of SQL.Row with PySpark


code: del a[:]

rawDescription: How to empty a Python list without doing list = []?

description: Empty a Python list without doing list = []


rawDescription: Removing empty elements from an array in Python


code:
#import requests library for making REST calls
import requests

#specify url
url = 'YOUR URL GOES HERE'
token = "THIS WAS WHERE I STORED MY TOKEN"

headers = {'Authorization': 'Bearer ' + token}

response = requests.get(url, headers=headers)
#Print Response
print (response.text)

rawDescription: How do I setup Python for RESTApi abilities

description: Setup Python for RESTApi abilities


code:
from functools import wraps

def italic(f):
    @wraps(f)
    def decorated():
        return "<italic/>" + f() + "</italic>"
    return decorated

rawDescription: A better way to write python closures?

description: A better way to write python closures


code: l = [x for x in n if x > 3]

rawDescription: How to find the length of a "filter" object in python

description: Find the length of a "filter" object in python


code: print(my_function(4, 5))

rawDescription: How to return multiple values in Python?

description: Return multiple values in Python


rawDescription: Make a dictionary from two lists after applying a function


code: [True, False, True, False, True, False, True, False, True, False]

rawDescription: How can I efficiently implement multithreading/multiprocessing in a Python web bot?

description: Efficiently implement multithreading/multiprocessing in a Python web bot


rawDescription: Formatting a replacement from dictionary


code:
from difflib import SequenceMatcher

s1 = "Bob's Bagel Shop"
s2 = "Bill's Bagel Shop"

matcher = SequenceMatcher(a=s1, b=s2)
match = matcher.find_longest_match(0, len(s1), 0, len(s2))

rawDescription: Use Regular Expressions (or another python module) to compare text/characters?


rawDescription: How to calculate the area of a polygon on the earth's surface using python?

description: Calculate the area of a polygon on the earth's surface using python


rawDescription: How can I scrape the value/text of an exact <td> using its xpath, after selecting a drop-down using selenium?

description: Scrape the value/text of an exact <td> using its xpath, after selecting a drop-down using selenium


code:
in_string = False
current_string = ""
strings = []

with open("test.txt") as f:
    for line in f:
        if "test" in line:
            for character in line:
                if character == '"':
                    if in_string:
                        strings.append(current_string)
                    in_string = not in_string
                    current_string = ""
                    continue
                elif in_string:
                    current_string += character

rawDescription: Extract text enclosed in quotes when reading a file


code:
serialData = [ b'468095384\r\n', b'0.01\r\n'] * 10
tmp = list(map(lambda d: float(d), serialData))
radarData = tmp[0::2]
timedata = tmp[1::2]
print(radarData)
print(timeData)

rawDescription: Python doesn't parse Serial data to an array


code:
import os
import urllib

path = urllib.unquote(path)
filename = os.path.splitext(os.path.basename(path))[0]

rawDescription: Python - Getting Filename from Long Path


code: my_func = lambda x: 2*x

rawDescription: Numerical integration Loop Python

description: Numerical integration Loop Python


code: fields = struct.unpack('!BBI4H20sIB', data)

rawDescription: Decoding packed data into a structure

description: Decoding packed data into a structure


rawDescription: What is the meaning of the phrase "registering a callback" with Python APIs?


rawDescription: Port MATLAB bounding ellipsoid code to Python


code:
idx = list(H.flatten()).index(H.max())
x, y = idx / H.shape[1], idx % H.shape[1]

rawDescription: Find peak of 2d histogram

description: Find peak of 2d histogram


code: web = QtWebkit.QWebView()

rawDescription: PyQt4 new modul

description: PyQt4 new modul


code: map(lambda x: dict(x, date=datetime.datetime.strptime(x['date'], '%Y-%m-%dT%H:%M:%S.%fZ')), data)

rawDescription: time.strptime got TypeError: function takes at most 8 arguments (9 given)

description: Time.strptime got TypeError: function takes at most 8 arguments (9 given)


code:
import numpy as np
# Note that this ignores your column names, and attempts to
# convert all values to a float...
data = np.loadtxt('input_filename.txt', delimiter=',', skiprows=1)

# Access the first column
workers = data[:,0]

rawDescription: How to remove 'None' from an Appended Multidimensional Array using numpy

description: Remove 'None' from an Appended Multidimensional Array using numpy


rawDescription: Counting number of strings in a List with Python


rawDescription: Need to take average of long, strangely formatted set of data in Python


rawDescription: Move some part of column to another python


rawDescription: What is the fastest way to combine and sort lists of tuples?


rawDescription: Threading advice for web crawler - scheduling with single list


code:
res = df.groupby('login').agg({'transaction_id': ['size', 'max']})
res.columns = ['transaction_count', 'last_transaction_id']
res

rawDescription: pandas: find newest value against index in time series data

description: Pandas: find newest value against index in time series data


rawDescription: Matplotlib updating axis

description: Matplotlib updating axis


code:
import random
with open('dist.all.last') as inputfile:
    name = None
    for i, line in enumerate(inputfile):
        r = random.randint(0, i)
        if not r and line.strip():
            name = line.split()[0]

rawDescription: Effectively parsing plain text

description: Effectively parsing plain text


code:
if args.no_log:
    args.log_file = None

rawDescription: How can I easily create a python argparse argument with an inverse?

description: Easily create a python argparse argument with an inverse


code:
for topic, func in zip(topic_ids, data_process_fcns):
    url = 'wss://mywebsocket.com/feed?topic_id[]=' + topic
    factory = myFactory(url, func)
    reactor.connectSSL(factory.host, factory.port, factory, ssl.ClientContextFactory())

rawDescription: Using different functions to process messages in a single autobahn WebSocketProtocol


code: handle_httpstatus_list = [200, 302, 404] # any other if you want

rawDescription: Count number of redirects in Scrapy

description: Count number of redirects in Scrapy


code:
newsItems = []
exec('newsItems.append("foo")', {}, {'newsItems': newsItems})
newsItems

rawDescription: pass list to exec and fill it

description: Pass list to exec and fill it


code: cons = set(cons)

rawDescription: Python removing items from a list that exist in another list but keeping duplicates that aren't in that intersect


rawDescription: How to match an OR expression without grouping it?

description: Match an OR expression without grouping it


code:
import demjson

data = demjson.decode(contents, strict=False)

rawDescription: Format of a .json file to be loaded in python


code:
cdic = default_attribute_dict.from_dictionaries(dic, default=lambda: 100)
cdic
cdic.two.four

rawDescription: Python 2.7 how to define a super powerful class-style dict object?


code:
viewsets.py
from rest_framework import mixins
from rest_framework import viewsets

class MyUserViewSet(mixins.UpdateModelMixin,
                    mixins.CreateModelMixin,
                    mixins.ListModelMixin,
                    viewsets.GenericViewSet):

    authentication_classes = (TokenAuthentication, SessionAuthentication)
    permission_classes = (AllowAny, )
    serializer_class = UserProfileSerializer
    queryset = UserProfile.objects.all()

rawDescription: How to implement nested serializer in django rest framework?

description: Implement nested serializer in django rest framework


code:
from itertools import product
def my_gen(letters, powers):
    for power in powers:
        for cartesian in product(letters, repeat=power):
            yield cartesian

rawDescription: Python Cartesian power generator over a list of powers


code:
lines = infile.readlines()
max_conc = max(cols[1] for cols in lines)

rawDescription: For loop position in csv reader_Python

description: For loop position in csv reader_Python


code:
words = ['ab', 'cd', 'ef']
abfrage_list = []
for w in words:
    # Generate a query
    query = """ SELECT BO_INDEX FROM GeoTest.dbo.Tabelle_Bohrung
        WHERE BO_BEMERKUNG LIKE '%%%s%%' """ % w
    # Execute that query and get results
    cur.execute(query)
    result_all = cur.fetchall()
    # Add those results to your final list
    for i in result_all:
        abfrage_list.append(i)

rawDescription: Give a list of strings to a sql-query [Python]


code:
def isRed(n):
    if n is None:
        return False
    else:
        return n.color == RED

rawDescription: Slow Python Red Black Tree Performance

description: Slow Python Red Black Tree Performance


code:
class ModelBase(models.Model):
    if python3:
        def __str__(self):
            return self._infoMethod()
    else:
        def __unicode__(self):
            return self._infoMethod()

rawDescription: is it possible to dynamically define a method's name?

description: Is it possible to dynamically define a method's name


code: any(keyword in s for s in json_data)

rawDescription: Finding text in json with python

description: Finding text in json with python


code:
VOWELS = {'A','E','I','O','U','a','e','i','o','u'}
# I'm assuming this is what isvowel checks, unless you're doing something
# fancy to check if 'y' is a vowel
with open('filename.txt') as f:
    vowel = sum(ch in VOWELS for line in f for ch in line.strip())

rawDescription: How to while loop until the end of a file in Python without checking for empty line?

description: While loop until the end of a file in Python without checking for empty line


code:
ar[ar == "replaceme"] = 2012
ar

rawDescription: Using mask to replace string in numpy

description: Using mask to replace string in numpy


code:
outputfile.write(value1 + "_NOMINAL" * (type(value1) is str)
                        + "_NUMERIC" * (type(value1) in (float, int)))

rawDescription: Pythonic way to make string dependend on type of variable


rawDescription: Concatenate 2 dataframes with uneven lengths and no index


code: (new_spin == cluster).all(axis = 1).any()

rawDescription: Detect ordered pair in numpy array

description: Detect ordered pair in numpy array


code:
import re
p = re.compile(r'(?<!#)\b(?:promocode|promo code|promo|coupon code|code|coupon)\b')
test_str = "promo #promo "
print(p.sub('', test_str))

rawDescription: NOT operator for regex

description: NOT operator for regex


code:
n = 4
word = "Wow"
symb = "!"
print("\n".join(map(lambda x:x[0]+x[1],zip([word]*(n-1),map(lambda i:symb*i,range(1,n))))))

rawDescription: Shortest way to add more characters to a string with each successive line


code:
class profiled(object):
    __count=0  # Class attribute shared for all @profiled functions
    def __init__(self,f):
        self.__f=f
        self.__name__=f.__name__
    def __call__(self,*args,**dargs):
        type(self).__count+=1  # Increment __count on the type, not the instance
        return self.__f(*args,**dargs)

    # Use a classmethod here, since we don't need self at all
    @classmethod
    def reset(cls):
        cls.__count=0

rawDescription: Global Variable In a Decorator

description: Global Variable In a Decorator


code:
WebDriverWait(driver, 60).until(
    text_match((By.XPATH, "//tr[5]/td[11]/div"), r"[0,1]{1}.[0-9]{6}")
)

rawDescription: Perform a WebDriverWait() or similar check on a Regular Expression in Python


rawDescription: Definition of ImageChops.difference

description: Definition of ImageChops.difference


code: fall_events = Event.fall_semester.all()

rawDescription: How to define range of months for any year on Django model?

description: Define range of months for any year on Django model


code: d = dict((row[0], row[1:]) for row in zip(a['columns'], *a['data']))

rawDescription: How to get max value for a specific key from a python dictionary

description: Get max value for a specific key from a python dictionary


code: [u'string1', u'string2', u'string3', u'string4', u'string5', u'string6']

rawDescription: HTML parsing with Beautiful soup

description: HTML parsing with Beautiful soup


code:
from decimal import Decimal

def get_name(s):
    return s.split(',')[0]

def get_price(s):
    return Decimal(s.split('$')[-1])

def get_menu(fname):
    with open(fname) as inf:
        budget = get_price(inf.next())
        items = [(get_name(line), get_price(line)) for line in inf]
    return budget, items

def integer_linear_solver(coefficients, total, index=None):
    """
    Given coefficients [c0, c1, ... cN] and total,
    generate all integer solutions to the equation
        s0*c0 + s1*c1 + ... + sN*cN == total
    and return as [s0, s1, ... sN]
    """
    if index is None:
        # Start at the end and work back
        # (this avoids having to repeatedly slice coefficients)
        index = len(coefficients) - 1

    c = coefficients[index]
    max_s = total // c

    if index:  # more coefficients available - recurse
        for s in range(max_s + 1):    # [0 .. max_s]
            for sol in integer_linear_solver(coefficients, total - s*c, index-1):
                yield sol + [s]
    else: # last coefficient
        if not(total % c):
            # no remainder -> exact solution found
            yield [max_s]

def print_sol(coeffs, labels):
    items = ('{0} {1}'.format(c, l) for c,l in zip(coeffs, labels) if c > 0)
    print(', '.join(items))

def main():
    budget,items = get_menu('menu.txt')
    names,prices = zip(*items)

    solutions = 0
    for sol in integer_linear_solver(prices, budget):
        print_sol(sol, names)
        solutions += 1

    if solutions:
        print('{} solutions found'.format(solutions))
    else:
        print("There is no combination of dishes that will equal your budget.")

if __name__=="__main__":
    main()

rawDescription: Can't understand why my implementation of Itertools.combinations_with_replacement is not working correctly


rawDescription: What if Chinese strings shown in the pandas DataFrame in Python


code:
def makeNonStringIterable(x):
  if isinstance(x, basestring):
    return (x,)
  try: return iter(x)
  except: return (x,)

rawDescription: What is the pythonic way of checking if an object is a list?


code:
class Foo:
    def __eq__(self, other):
        return hasattr(other, '_equals_foo') and other._equals_foo(self)
    def _equals_foo(self, other):
        return self.number == other.number
    def _equals_bar(self, other):
        return False # Foo never equals Bar
class Bar:
    def __eq__(self, other):
        return hasattr(other, '_equals_bar') and other._equals_bar(self)
    def _equals_foo(self, other):
        return False # Foo never equals Bar
    def _equals_bar(self, other):
        return True # Bar always equals Bar

rawDescription: Python set intersection and __eq__

description: Python set intersection and __eq__


code: [[1 if i*10+j in values else 0 for j in range(10)] for i in range(10)]

rawDescription: Python fill matrix with specific values

description: Python fill matrix with specific values


code:
df.pivot_table(index='User', columns='Resource',
               aggfunc=lambda _ : '+', fill_value='-')

rawDescription: Build access matrix from raw data with python pandas


code:
from subprocess import Popen, PIPE

with Popen(["unbuffer", "-p","scala"], stdout=PIPE, stdin=PIPE, bufsize=0, universal_newlines=True) as scala:
    for line in scala.stdout:
        print(line)
        if not line.strip():
            break
    while True:
        command = input("Enter scala command >>> ")
        scala.stdin.write(command+"\n")
        scala.stdout.flush()
        for line in scala.stdout:
            if not line.strip():
                break
            print(line)

rawDescription: input command doesn't seem to work when used with popen python

description: Input command doesn't seem to work when used with popen python


code:
if __name__ == "__main__":
    L = generateSequences(15)
    print (L)
    S, D = generatePrefixes(4, L)
    print (S)
    print (D)

rawDescription: Pick x (f.e. first) characters from a List entry then pick random entries from the new list


rawDescription: How can the symmetric difference between two lists of two-element sublists be obtained?


code:
def hello():
    XSCRIPTCONTEXT.getDocument().getText().setString("Hello!")

# Functions that can be called from Tools -> Macros -> Run Macro.
g_exportedScripts = hello,

rawDescription: Python macro for LibreOffice - replace string in text


code:
class Controller(object):
    def __init__(self):
        self._output = {}

    def output(self, s, caller):
        method_that_called_me = caller.__name__
        self._output[method_that_called_me] = s

class Public(Controller):
    def about_us(self):
        self.output('Damn good coffee!',self.about_us)

    def contact(self):
        self.output('contact me',self.contact)

rawDescription: Python: Find out what method on derived class called base class method


code:
def __init__(self, param1, dict_param):
    self.param1 = param1
    self.key1 = 10.0  # set default value
    # more defaults...

    for key, value in dict_param.iteritems():
        if hasattr(self, key):
           setattr(self, key, value)

rawDescription: Class instantiation with a dictionary parameter and class variables with default values


code:
import numpy as np
import datetime as DT
np.random.seed(2016)
base = DT.date.today()
date_list = [base - DT.timedelta(days=x) for x in range(0, 10)]
df = pd.DataFrame(data=np.random.randint(1, 100, (10, 8)),
                  index=date_list,
                  columns=['a1', 'a2', 'b1', 'a3', 'b2', 'c1' , 'c2', 'b3'])

group = df.columns.str.extract(r'(\D+)', expand=False)
means = df.groupby(group, axis=1).transform('mean')
result = df - means
print(result)

rawDescription: DataFrame subtract group-wise means

description: DataFrame subtract group-wise means


code:
date += timedelta(days=10)
date -= timedelta(days=5)

rawDescription: How to convert integer into date object python?

description: Convert integer into date object python


code: obj = RSA

rawDescription: python calling methods of class using different ways

description: Python calling methods of class using different ways


code:
# MyPlugin.py
from myapp.plugin import Plugin # a base class you define

def create():
    return MyPlugin()

class MyPlugin(Plugin):
    ...

rawDescription: does anybody know a simple base for a plug in python application?

description: Does anybody know a simple base for a plug in python application


code: self.zip = self.postal_code_format(self.zip, self.country_id)

rawDescription: How to return a value from a method back to the input value

description: Return a value from a method back to the input value


code:
def memoize(function):
    memo = {}
    def wrapper(*args):
      if args in memo:
        return memo[args]
      else:
        rv = function(*args)
        memo[args] = rv
        return rv
    return wrapper

@memoize
def getmaxofsub(x, y):
    if y  == len(triangle) or x>y: return 0
    #print x, y
    return triangle[y][x] + max(getmaxofsub(x, y+1), getmaxofsub(x+1, y+1))

getmaxofsub(0,0)

rawDescription: Max path triangle (Python)

description: Max path triangle (Python)


code: [2 * x for x in some_list if x > 2]

rawDescription: How can I add nothing to the list in list comprehension?

description: Add nothing to the list in list comprehension


code:
thisFrame = 34
nextFrame = thisFrame + 1
if thisFrame in item_dict and nextFrame in item_dict:
    foo = item_dict[thisFrame] # e.g. [list1, list2]
    bar = item_dict[nextFrame] # e.g. [list1, list2, list3]
    DoStuff()

rawDescription: Managing big point lists, best approach?

description: Managing big point lists, best approach


code:
def find_by_size(size, path):
    result = []
    for root, dirs, files in os.walk(path):
        if os.stat(path+name).st_size == size:
            result.append((os.path.join(name), stats.st_size))
        else:
            print ("Nothing of size %d was found" % size)
        return result

rawDescription: How to search file by its size using Python

description: Search file by its size using Python


code: db.whatever.map_reduce(map, reduce, "collection_name", scope = {"number" : the_value_your_function_needs})

rawDescription: MongoDB MapReduce, Date and % operator

description: MongoDB MapReduce, Date and % operator


code:
import numpy as np

A = np.arange(27).reshape([3,3,3])
B = np.zeros(A.size)
i, j, k = np.ogrid[0:3, 0:3, 0:3]
B[i+j+k] = A
print(B)

rawDescription: Efficient way of getting a subarray of an array that the indices are mapped


code:
fig, ax = plt.subplots()
ax.plot([3,1,2,4,0,5,3,2,0,2,4])
plt.close(fig)

vline = ax.axvline(1)
hline = ax.axhline(0.5)

def set_cursor(x, y):
    vline.set_xdata((x, x))
    hline.set_ydata((y, y))
    display(fig)

interact(set_cursor, x=(1, 9, 0.01), y=(0, 5, 0.01))

rawDescription: IPython Notebook widgets for Matplotlib interactivity


code:
for line in filename:
    fields = line.split(',')  # For comma-delimited files
    # - or -
    fields = line.split('\t') # For tab-delimited files

rawDescription: Parsing CSV to list of tuples without using CSV module


code:
import lxml.etree
import pprint

s = '''
<data>
    data text
    <foo>foo - <bar>bar</bar> text</foo>
    data text
    <bar>
        bar text
        <baz>baz text</baz>
        <baz>baz text</baz>
        bar text
    </bar>
    data text
</data>
'''

etree = lxml.etree.fromstring(s)
text = etree.xpath("//text()[normalize-space()]")
pprint.pprint([(s.getparent().tag, s.is_tail, s.strip()) for s in text])

rawDescription: Why getparent() don't work as expected?

description: Why getparent() don't work as expected


code:
class Wrap:

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

    def unlink(self):
        val = self.val
        self.val = None
        return val

rawDescription: Python: yield-and-delete

description: Python: yield-and-delete


code:
store = pd.HDFStore('test.h5')
store.select_column('df_mi','foo')
store.select_column('df_mi','bar')
store.close()

rawDescription: how to access index in a pandas HDStore (pyTables)

description: Access index in a pandas HDStore (pyTables)


code:
df['m'] = pd.Categorical(df['m'], ["March", "April", "Dec"])
df  # looks the same!

rawDescription: Custom sorting in pandas dataframe

description: Custom sorting in pandas dataframe


code:
from account.models import UserProfile
from django.db.models import Q

class AuthBackend(object):
    supports_object_permissions = True
    supports_anonymous_user = False
    supports_inactive_user = False

    def get_user(self, user_id):
       try:
          return UserProfile.objects.get(pk=user_id)
       except UserProfile.DoesNotExist:
          return None

    def authenticate(self, username, password):
        try:
            user = UserProfile.objects.get(
                Q(username=username) | Q(email=username) | Q(phone=username)
            )
        except UserProfile.DoesNotExist:
            return None

        return user if user.check_password(password) else None

rawDescription: Multiple login fields in django user

description: Multiple login fields in django user


rawDescription: how to "add" things together python

description: "add" things together python


code: def classIterator(clazz: Class[_]): Iterator[Class[_]] = classStream(clazz).iterator

rawDescription: Scala equivalent to python generators?

description: Scala equivalent to python generators


code: dic = {j:float(val) for j, val in enumerate(astr.split(' '))}

rawDescription: Solving a task in cosmology using Python 2.7.5


code:
cssdict = { 'xxxxx':'font-weight: bold; font-size: 8.0pt; font-style: oblique',
            'yyyyy':'font-weight: normal; font-size: 9.0pt; font-style: italic',
            'aaaa': 'font-weight: bold; font-size: 9.0pt; font-style: italic',
            'bbbbbb': 'font-weight: normal; font-size: 9.0pt; font-style: normal',
            'Title': 'font-style: oblique; text-align: center; font-weight: bold',
            'norm': 'font-style: normal; text-align: center; font-weight: normal'
          }

RELEVANT = ['font-weight', 'font-style']

def parse_css_spec(s):
    """
    Decompose CSS style spec into a dictionary of its components.
    """
    parts = [ p.strip() for p in s.split(';') ]
    attpairs = [ p.split(':') for p in parts ]
    attpairs = [ (k.strip(), v.strip()) for k,v in attpairs ]
    return dict(attpairs)

cssparts = { k: parse_css_spec(v) for k,v in cssdict.items() }
# pprint(cssparts)

def redundant_span(span_css_name, parent_css_name, consider=RELEVANT):
    """
    Determine if a given span is redundant with respect to its parent,
    considering sepecific attribute names. If the span's attributes
    values are the same as the parent's, consider it redundant.
    """
    span_spec = cssparts[span_css_name]
    parent_spec = cssparts[parent_css_name]
    for k in consider:
        # Any differences => not redundant
        if span_spec[k] != parent_spec[k]:
            return False
    # Everything matches => is redundant
    return True

rawDescription: lxml strip_tags results in AttributeError

description: Lxml strip_tags results in AttributeError


rawDescription: Getting the Index of a multi-line pattern in Python


code:
rowlist = [0, 5, 99]

with open('output.txt', w) as out:
    for rowindex in rowlist:
        out.write(data[rowindex])

rawDescription: Extracting certain rows from a csv file using python


code:
def find_pairs(list_, sum_):
    s = set(list_)
    pairs = 0

    for i in list_:
        diff = sum_ - i
        s.remove(i)

        if diff in s:
            pairs += 1

    return pairs

rawDescription: Count number of complementary pairs in array


code:
for _ in range(times_to_advance):
    next(file_object)

rawDescription: Advance a file object more than one line as a way of skipping blank lines and lines containing strings


code:
text = """This is the first line.
           This is the second line.
           The line below is true.
           The line above is false.
           A short line.
           A very very very very very very very very very long line.
           A self-referential line.
           The last line.
        """

lines = (i.strip() for i in text.splitlines())

for line in lines:
    for chunk in chunkstring(line, 16):
        print(chunk)

rawDescription: What's the best way to split a string into fixed length chunks and work with them in Python?


code:
class ProductList(generics.ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_class = ProductFilter

    def get_queryset(self):
        data = self.request.DATA
        mixed_query = data.get('mixed',None)

        if not mixed_query:
            return self.queryset
        and_params = {}
        for key in data:
           if 'and_' in key:
              and_params[key] = data[key]

        queryset = Products.objects.filter(**and_params)
        for key in self.request.DATA:
            if 'or_' in key:
              queryset = queryset | Products.objects.filter(key=data[key])

        return queryset

rawDescription: How can i make OR operator in query params in django rest framework

description: Make OR operator in query params in django rest framework


code:
from math import ceil

def F(n):
    m = 1000000007
    a = 2
    for i in range(2, n+1):
        a = (a + pow(2, int(ceil((i - 1.0) / 2)), m)) % m
    return a

rawDescription: Any better algorithm possible here?

description: Any better algorithm possible here


rawDescription: Float value is equal -1.#IND

description: Float value is equal -1.#IND


code: obs = pm.Bernoulli('obs', p_true, observed=occurrences)

rawDescription: Porting pyMC2 Bayesian A/B testing example to pyMC3


rawDescription: Calculating pixel in array

description: Calculating pixel in array