code:
from random import choice

def edward_peters(string):
    sequences = [[]]
    for end in range(1, len(string) + 1):
        def candidate_sequences():
            for previous_end in range(max(0, end - 10), end):
                substring = string[previous_end:end]
                if len(substring) == len(set(substring)):
                    yield sequences[previous_end] + [substring]

        sequences.append(min(candidate_sequences(), key=len))
    return sequences[-1]

def brendan_abel(long_string):
    if not long_string:
        return []
    cur_i = None
    cur_s = None
    max_i = None
    max_s = None
    for i, s in enumerate(long_string):
        if cur_s is None or s in cur_s:
            if cur_s and (max_s is None or len(cur_s) > len(max_s)):
                max_i = cur_i
                max_s = cur_s
            cur_i = i
            cur_s = [s]
        else:
            cur_s.append(s)
    else:
        if cur_s and (max_s is None or len(cur_s) > len(max_s)):
            max_i = cur_i
            max_s = cur_s
    before = long_string[:max_i]
    after = long_string[max_i + len(max_s):]
    return brendan_abel(before) + [''.join(max_s)] + brendan_abel(after)

def ruud(string):
    result = []
    current = ''
    for c in string:
        if c in current:
            result.append(current)
            current = c
        else:
            current += c
    result.append(current)
    return result

def main():
    while True:
        string = ''.join(choice('1234567890') for _ in range(10000))
        results = [func(string) for func in [edward_peters, brendan_abel, ruud]]
        assert all(''.join(result) == string for result in results)
        assert len(set(map(len, results))) == 1

main()

rawDescription: Split string by unique patterns

description: Split string by unique patterns


code:
target1 = 'mjzzmjzzmjzz'
key1 = 'zz'
target1.find(key1, 0)
target1.find(key1, 3)
target1.find(key1, 7)
target1.find(key1, 11)

rawDescription: If-else inside a while statement

description: If-else inside a while statement


code:
df = DataFrame(rand(3,2), columns=['A', 'B'])
ax = df.plot(table=True, kind='bar', title='Random')
for i, each in enumerate(df.index):
    for col in df.columns:
        y = df.ix[each][col]
        ax.text(i, y, y)

rawDescription: Adding datalabels - matplotlib barchart

description: Adding datalabels - matplotlib barchart


code:
def main(**kwargs):
    kwargs = functionA(textNew="text added in new", **kwargs)
    # ... etc ...

def functionA(**kwargs):
    # ...
    return kwargs

rawDescription: How to access kwargs created in an other function using python?

description: Access kwargs created in an other function using python


code:
from itertools import islice
for prime in islice(gen_primes(), 10):
    print(prime)

rawDescription: Python prime numbers generators in terminal


code: bitext = [[sentence.strip().split() for sentence in pair if len(sentence) < 100] for pair in zip(open(c_data), open(e_data)) [:opts.num_sents]]

rawDescription: Python if-statement within list comprehension


code:
def argconv(**convs):
    def parse_argument(arg):
        if arg in convs:
            return convs[arg]
        else:
            msg = "invalid choice: {!r} (choose from {})"
            choices = ", ".join(sorted(repr(choice) for choice in convs.keys()))
            raise argparse.ArgumentTypeError(msg.format(arg,choices))
    return parse_argument

rawDescription: argparse: map user input to defined constant

description: Argparse: map user input to defined constant


rawDescription: how to check mousemotion in an undefined direction in pygame?

description: Check mousemotion in an undefined direction in pygame


code:
class MyRouter(object):

    def db_for_read(self, model, **hints):
        if model._meta.app_label == 'yourappname':
            return 'local_mysql'
        return None

    def db_for_write(self, model, **hints):
        return self.db_for_read(model, **hints)

    def allow_relation(self, obj1, obj2, **hints):
        if obj1._meta.app_label == 'yourappname' or \
           obj2._meta.app_label == 'yourappname':
           return True
        return None

    def allow_migrate(self, db, model):
        if db == 'local_mysql':
            return model._meta.app_label == 'yourappname'
        elif model._meta.app_label == 'yourappname':
            return False
        return None

rawDescription: How do I stop Django "python manage.py syndb" from adding tables to multiple DB's in Settings?

description: Stop Django "python manage.py syndb" from adding tables to multiple DB's in Settings


code:
centers = np.rollaxis(centers, 0, centers.ndim)
centers.shape
centers

rawDescription: Dividing a square into N smaller squares and finding center coordinates of the N smaller squares


code:
import json
testfile = '/home/vivek/Desktop/input12.txt'

with open(testfile ) as fp:
    content = fp.read()

value = json.loads(content)

list3 = [9,10,11,12]
value.append(list3)

with open(testfile, "wb" ) as fp:
    json.dump(value, fp)

rawDescription: Add item to list in txt file using json (python)


code:
while True:
    username = input('please enter your username or exit to quit the program')

    if username == 'exit':
        break
    else:

        with open('myfile.txt', 'r') as f:
            for line in f:
                print(line)
                if username == line:
                    print('you belong here')
                    break
            else:
                with open('myfile.txt', 'a') as f:
                    f.write(username)
                    print('You dont belong but your name has been saved')
                    break

rawDescription: How can I save input to a file and then check the input from the file?

description: Save input to a file and then check the input from the file


code:
# testutils.py
def check_logs(testcase, logs, **kw):
    testcase.assertWhatever(something)

# myserver/tests.py
import unittest
from testutils import check_logs

class MyServerTest(unittest.TestCase):
    def test_log1(self):
        logs = extract_the_logs()
        check_logs(self, logs, log_1=1, log2='foo')

rawDescription: Python unittest: having an external function for repetitive code in different modules


code:
colors = dict(low='DarkBlue', high='red', part='yellow', medium='DarkGreen')

fig, ax = plt.subplots()

for grp, vals in df.groupby('col4'):
    color = colors[grp]
    vals[['col2','col3']].plot.scatter(x='col2', y='col3', ax=ax,
                                       s=120, label=grp, color=color)

rawDescription: Multiple inputs multivariate data visualisation


code:
x = ['dogs', 'cats']
", ".join(map(repr,x))

rawDescription: String of strings for arbitrary amount, python


code:
import re
print (re.IGNORECASE)
print (re.LOCALE)
print (re.MULTILINE)
print (re.DOTALL)
print (re.UNICODE)
print (re.VERBOSE)
print (re.DEBUG)
print (re.A)

rawDescription: Changes in re module between Python 2 and Python 3


code:
def rolling_prod2(xs, n):
    cxs = np.cumprod(xs)
    nans = np.empty(n)
    nans[:] = np.nan
    nans[n-1] = 1.
    a = np.concatenate((nans, cxs[:len(cxs)-n]))
    return cxs / a

rawDescription: Fast numpy rolling_product

description: Fast numpy rolling_product


code: IOLoop.add_timeout(deadline, callback)

rawDescription: How to run functions outside websocket loop in python (tornado)

description: Run functions outside websocket loop in python (tornado)


rawDescription: Deduplicate and reorder dictionary

description: Deduplicate and reorder dictionary


code:
target = Model()
target.password = 'b'
# '$5$rounds=80000$H.............'
target.password == 'b'
# True

rawDescription: SQLAlchemy & PassLib

description: SQLAlchemy & PassLib


rawDescription: Python: Check an index against multiple other indexes


rawDescription: grouping lines from a file with regular expression

description: Grouping lines from a file with regular expression


code: all(a==b for a,b in zip(A,B))

rawDescription: Compare List with different number of items


code:
def filter_out_common_queries(querylist):
    basequery = ' '.join(querylist)
    querylist = []
    for n in range(2,len(basequery)+1):
        querylist.append(basequery[:n])
    return querylist

rawDescription: comparing two text file and find out the related word in python

description: Comparing two text file and find out the related word in python


code:
fivepm = datetime.datetime.combine(
    datetime.date.today(),
    datetime.time(17, 0))

rawDescription: How do I get the datetime object of today's 5pm in Python?

description: Get the datetime object of today's 5pm in Python


rawDescription: datetime to float not include milliseconds

description: Datetime to float not include milliseconds


code:
...
settings.py
settings_dev.py
_settings_test.py
_settings_prod.py
...

rawDescription: How do I make Django use a different database besides the 'default'?

description: Make Django use a different database besides the 'default'


code:
from mod1 import A

class B(object):
    pass

rawDescription: Limit which classes in a .py file are importable from elsewhere


code: ('done', 'PoolWorker-4')

rawDescription: In multiprocess module of python , how to find which worker process has executed the job


code: set.intersection(*(set(x) for x in [a, b, v] if x))

rawDescription: Python - finding same elements in three lists (ignoring empty list)


code: d[key] = [(x, y[0]) for x,y in d[key]]

rawDescription: How to change a tuple within a value of a dictionary?

description: Change a tuple within a value of a dictionary


code:
fields = {'title': 'My Title',
          'description': 'My Description',
          'name': 'My Name'}

foo = Foo(**fields)
foo.save()

rawDescription: Using variables when referring to an objects datamember


code:
def splitText(text):
    """Split text on any non-alphabetic character, return list of words."""
    final_list = []
    word = ''

    for ch in text:
        if word:   # Empty string is false!
            if ch.isalpha():
                word += ch
            else:
                final_list.append(word)
                word = ''
        else:
            if ch.isalpha():
                word += ch
            else:
                # still not alpha.
                pass

    # Handle end-of-text with word still going
    if word:
        final_list.append(word)

    return final_list

sampleText = "As Python's creator, I'd like to say a few words about its origins."
print(splitText(sampleText))

rawDescription: Trouble splitting text without using split()


code:
class Media:
    js = ['/path/to/project_change.js',]

rawDescription: How to set dynamic mapping between two models in django

description: Set dynamic mapping between two models in django


rawDescription: Python: hex conversion always two digits


code:
def main():
    import doctest
    print(doctest.testmod())

    pubkey, privkey = keygen(2 ** 64)
    msg = u'the quick brown fox jumped over the lazy dog ® ⌀'
    h = encode(msg, pubkey, True)
    p = decode(h, privkey, True)
    print('-' * 20)
    print('message:', msg)
    print('encoded:', b64encode(h).decode())
    print('decoded:', p)
    print('private key:', key_to_str(privkey))
    print('public key:', key_to_str(pubkey))

rawDescription: Using user input in RSA code in Python

description: Using user input in RSA code in Python


rawDescription: filtering elements of matrix by row in python scipy/numpy

description: Filtering elements of matrix by row in python scipy/numpy


code:
['develop',
 'feature-dm',
 'feature/breedtest',
 'feature/fedortest',
 'feature/frontend-autumn14',
 'feature/socket-testing',
 'feature/youtracktest',
 'master',
 'master-old']

rawDescription: What is the most pythonic way to extract branch names from a remote-ls list?


code:
myHat='green'
def fooBar():
    return myHat

rawDescription: What happens to imports when a new process is spawned?


code:
from itertools import takewhile, izip_longest
from operator import itemgetter
somezip = lambda *p: list(takewhile(itemgetter(0),izip_longest(*p)))

rawDescription: Is there a middle ground between `zip` and `zip_longest`


rawDescription: Equivalent of transform in R/ddply in Python/pandas?


code:
from django.views.generic import ListView

# Import your models here.

class HomepageView(ListView):
    model = Post
    ordering = '-date'
    template_name = 'blog1.html'
    context_object_name = 'posts'

    def get_context_data(self, **kwargs):
        context = super(HomepageView, self).get_context_data(**kwargs)
        context['members'] = Member.objects.all()
        return context

    def get_queryset(self):
        return super(HomepageView, self).get_queryset()[:10]

rawDescription: Django dynamic homepage

description: Django dynamic homepage


code:
import tkFileDialog
import os               # so we can call getcwd()
...
types = (("Text file", ".txt"), ("All Files", "*.*"))
file = tkFileDialog.askopenfilename(filetypes=types, initialdir=os.getcwd())

rawDescription: Python. File open procedure

description: Python. File open procedure


code:
from pymongo import Connection
from bson import ObjectId, Code

con = Connection(port=30000)  # add host/port here if different from default
db = con['test']    # or the database name you are using

# insert documents
db.master.insert({'_id': ObjectId(), 'Name': 'Jim', 'Age': 24})
db.master.insert({'_id': ObjectId(), 'Name': 'Bill', 'Age': 38})
db.master.insert({'_id': ObjectId(), 'Name': 'Mary', 'Age': 55})

db.subset.insert({'_id': ObjectId(), 'Name': 'Jim'})
db.subset.insert({'_id': ObjectId(), 'Name': 'Mary'})

# map function for master collection
mapf_master = Code(""" function () {
    emit(this.Name, {'age': this.Age, 'inSubset': false});
} """)

# map function for subset collection
mapf_subset = Code(""" function() {
    emit(this.Name, {'age': 0, 'inSubset': true});
} """)

# reduce function for both master and subset
reducef = Code(""" function(key, values) {
    var result = {'age': 0, 'inSubset': false};

    values.forEach( function(value) {
        result.age += value.age;
        result.inSubset = result.inSubset || value.inSubset;
    });

    return result;
} """)

# call map-reduce on master and subset (simulates a join)
db.master.map_reduce(mapf_master, reducef, out={'reduce': 'join'})
db.subset.map_reduce(mapf_subset, reducef, out={'reduce': 'join'})

# final map function for third map-reduce call
mapf_final = Code(""" function() {
    if (this.value.inSubset) {
        emit('total', {'age': this.value.age, 'count': 1});
    }
} """)

# final reduce function for third map-reduce call
reducef_final = Code(""" function(key, values) {
    var result = {'age': 0, 'count': 0};

    values.forEach( function(value) {
        result.age += value.age;
        result.count += value.count;
    });

    return result;
} """)

# final finalize function, calculates the average
finalizef_final = Code(""" function(key, value) {
    if (value.count > 0) {
        value.averageAge = value.age / value.count;
    }
    return value;
} """)

# call final map-reduce
db.join.map_reduce(mapf_final, reducef_final, finalize=finalizef_final, out={'merge': 'result'})

rawDescription: Filter map reduce to records that match a different collection


code:
def dist(item):
    item = map(int, item)
    return sum(abs(item[i] - myCmpItem[i]) for i in xrange(len(item)))

rawDescription: Order a list by all item's digits in Python


code:
- removed.append(n)
+ removed.append(node)

rawDescription: python ete2 delete node from tree

description: Python ete2 delete node from tree


code: serializer = MySerializer(account, context={'request': request})

rawDescription: Django REST Framework and FileField absolute url


rawDescription: Porting from Python to Java: looking for a fast implementation of an array search operation


code:
file_output = open("file_output.txt","w")
file_output.write(text_output)
file_output.close()

rawDescription: Merge 3 Textfiles with python

description: Merge 3 Textfiles with python


code:
with open('input.ass') as infile, open('output.xml', 'w') as outfile:
    for start, end, text in extract(infile):
        outfile.write(to_xml(start, end, text) + '\n')

rawDescription: Replacing and ading text in text files in Python


code:
def nearest_50(n):
    return round(n*2, -2)/2

rawDescription: Rounding separate values in a list at the same time


rawDescription: Python set Union and set Intersection operate differently?


code:
def create_grid(grid):
    y = 0
    size = LENGTH * WIDTH
    table = ''
    while y < LENGTH:
        x = 0
        while x < size:
            if x:
                table += '|'
            table += grid[y + x]
            x += LENGTH
        table += '\n'
        y += 1

    return table

rawDescription: Python: Using two while loops to create grid. No for loops


rawDescription: read and display raw image using python

description: Read and display raw image using python


code:
from copy import copy, deepcopy

class MyClass(object):
    def __init__(self):
        self.a = [1,2,3,4]

mc = MyClass()
mc2 = mc
mc3 = copy(mc)
mc4 = deepcopy(mc)

rawDescription: Interesting list behaviour in python

description: Interesting list behaviour in python


code:
import ctypes  # An included library with Python install.
def Mbox(title, text, style):
    ctypes.windll.user32.MessageBoxA(0, text, title, style)
Mbox('Your title', 'Your text', 1)

rawDescription: How can I create a simple message box in Python?

description: Create a simple message box in Python


code: ['a', 'b', 'hello\nworld']

rawDescription: Python csv new line character in field

description: Python csv new line character in field


code:
from collections import Counter
list1 = ['a', 'a', 'b', 'c']
list2 = ['a', 'a', 'a', 'b']
cn1, cn2 = Counter(list1), Counter(list2)
print(all(cn2[k] <= v for k, v in cn1.items()))

rawDescription: Python: check if list is contained in another list


rawDescription: sort text file by first element

description: Sort text file by first element


code: [list(t) for t in zip(x, y, z)]

rawDescription: combining lists: three lists into one new list

description: Combining lists: three lists into one new list


rawDescription: String Comparison with a Format - Python


code: d2 = dict((k, d[k]) for k in set(d) & s)

rawDescription: Remove entries of a dictionary that are not in a set


rawDescription: Python counterpart to partial for ignoring an argument


rawDescription: Python: compare an array element-wise with a float


rawDescription: Parent changing child's attribute

description: Parent changing child's attribute


code:
import tkinter
import importlib
import main

class Executor:
    def __init__(self):
        self.root = tkinter.Tk()
        self.app = main.Application(master=self.root, on_reload=self.on_reload)
        self.app.mainloop()

    def on_reload(self):
        self.root.destroy()

        importlib.reload(main)

        self.root = tkinter.Tk()
        self.app = main.Application(master=self.root, on_reload=self.on_reload)
        self.app.mainloop()

if __name__ == '__main__':
    Executor()

rawDescription: how can I re-execute my Python program by clicking a button

description: Re-execute my Python program by clicking a button


code:
from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'sampledjango.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^add/location/', 'add_location.views.add_location'),
    url(r'^thanks/', 'add_location.views.thanks'),
)

rawDescription: Django: Creating a forgeinkey in a form on the spot.


code: raise RuntimeError("The variable does not exist in the expression.")

rawDescription: Python returns list but to variable, but variable is null


code:
sp_mat
zero_mat
sp_mat - sp_mat.multiply(zero_mat)

rawDescription: Bulk zeroing of elements in a scipy.sparse_matrix


code:
def change_it(some_list):
    some_list.append("world")

foo = ["hello"]
change_it(foo)
print(foo)  # prints ['hello', 'world']

rawDescription: Send by ref/by ptr in python?

description: Send by ref/by ptr in python


code:
new_values = np.empty_like(df)
for i, row in enumerate(df.values):
    # sort in descending order
    new_values[i] = row[inds[i]][::-1]

sorted_df = DataFrame(new_values, index=df.index)

rawDescription: `pandas.DataFrame.apply` in a row by row operation


code: new_array = m * 2

rawDescription: Calculation on 2D array rejecting special values (knowing the indices)


code:
import arcpy
curObj = arcpy.SearchCursor(r"C:/shape.shp")
row = curObj.next()
while row:
    columnValue = row.getValue("columnName")
    row = curObj.next()

rawDescription: iterating through attribute tables (ArcGIS 10.1, Python)

description: Iterating through attribute tables (ArcGIS 10.1, Python)


code: occupations = np.array([0, 2, 1, 2])

rawDescription: Fast Numpy calculation of a slight variation of the repeat and choose functions


code:
# This class performs the iterative computation that needs to update the GUI
# the signals it send would *ideally* be special_obect objects so any of the parameters can be shown
class Worker(QtCore.QObject):
    update_signal = QtCore.pyqtSignal(QtCore.QObject)
    done_signal = QtCore.pyqtSignal()
    def __init__(self, special_object):
        QtCore.QObject.__init__(self)
        self.special_object = special_object

    @QtCore.pyqtSlot()
    def process_on_special_object(self):
        # do a long fitting process involving the properties of the special_object
        for i in range(0,99999999999999999):
            self.special_object.Y += .1
            self.signal.emit(self.special_object)
        self.done.emit()
        return

rawDescription: Tabs with long processes in GUI all calling the same instance? [EDITED-QThread and QObject for passing objects to GUI]


code:
fields_that_reference = [[m._meta.object_name.lower()+'__'+f.name for f in m._meta.fields if not isinstance(f,related.ForeignKey) ] for m in models_that_reference]

for i in fields_that_reference:
    fields +=i

rawDescription: How do you join all models that reference a model into one table in Django?

description: Join all models that reference a model into one table in Django


code:
import subprocess
def check_output(*popenargs, **kwargs):
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')
    process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
    output, unused_err = process.communicate()
    retcode = process.poll()
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        raise subprocess.CalledProcessError(retcode, cmd, output=output)
    return output

class CalledProcessError(Exception):
    def __init__(self, returncode, cmd, output=None):
        self.returncode = returncode
        self.cmd = cmd
        self.output = output
    def __str__(self):
        return "Command '%s' returned non-zero exit status %d" % (
            self.cmd, self.returncode)
# overwrite CalledProcessError due to `output` keyword might be not available
subprocess.CalledProcessError = CalledProcessError

rawDescription: What's a good equivalent to python's subprocess.check_call that returns the contents of stdout?


code:
def fixedpoint(f, start, stop):
    while start != stop:
        yield start
        start = f(start)

rawDescription: How to walk up a linked-list using a list comprehension?

description: Walk up a linked-list using a list comprehension


code:
url('^address/edit/(?P<pk>\d+)$', 'edit_address', name="edit"),
url('^address/save/$', 'save_address', name="save"),

rawDescription: Editing django forms using django bootstrap forms


code:
if all(_ is None for _ in (arg_one, arg_two)):
    pass
elif all(_ is not None for _ in (arg_one, arg_two)):
    pass

rawDescription: Best way to require exactly one of a set of keyword arguments in Python?

description: Require exactly one of a set of keyword arguments in Python


code:
import pandas as pd
import pandas.io.data as web

stocks = {'xom': '2014-01-01', 'dvn': '2013-01-01', 'aapl': '2013-01-01'}
L = dict()
for stock, date in stocks.items():
    price = web.get_data_yahoo(stock, date)['Adj Close']
    change = price.diff().cumsum()
    perChange = change / price.iloc[0]
    L[stock] = perChange
df = pd.DataFrame(L)
print(df.head())

rawDescription: Iterating a dictionary to create a DataFrame with the column names being the dictionary keys


rawDescription: Changing ASCII values in a list

description: Changing ASCII values in a list


code:
def __init__(self, *args):
    args = [argument or None for argument in args]

rawDescription: How to check function argument values in python?

description: Check function argument values in python


rawDescription: Tkinter indexing words issue

description: Tkinter indexing words issue


code: pd.to_datetime(ts, format='%d/%m/%y %H h %M min %S s +02:00')

rawDescription: Convert dataframe with odd timestamp to timeseries with pandas


rawDescription: Creating an XML document with BeautifulSoup


code:
class SomeClass:
    def __init__(self,value):
        self.some_variable = value

    def setVariable(self,value):
        self.some_variable = value

    def getVariable(self):
        return self.some_variable

rawDescription: How to avoid variable to be persistent across many requests?

description: Avoid variable to be persistent across many requests


code:
all = Other.objects.all()
all[0].content_object
all[0].content_object.foo
all[1].content_object
all[1].content_object.foop

rawDescription: Django Releationship between multiple fields


rawDescription: How do I remove identical items from a list and sort it in Python?

description: Remove identical items from a list and sort it in Python


code:
mod = None
if 'file1.txt' in files:
    mod = files['file1.txt']['fileMod']

rawDescription: checkin python if a list of dictonaries does NOT contain a specific value

description: Checkin python if a list of dictonaries does NOT contain a specific value


code:
import pymongo

class MongoDB: # Classes generally are camel-case, starting with uppercase
    def __init__(self, dbname):
        # the __init__ method is the class constructor, where you define
        # instance members.  We'll make conn an instance member rather
        # than a class level member
        self._conn = pymongo.Connection("localhost", 27017)
        self._db   = self._conn[dbname]

    # methods usually start with lowercase, and are either camel case (less desirable
    # by Python standards) or underscored (more desirable)
    # All instance methods require the 1st argument to be self (pointer to the
    # instance being affected)
    def createCollection(self, name=""):
        return self._db[name]

if __name__ == '__main__':
    # you want to initialize the class
    database   = MongoDB("Hello")
    collection = database.createCollection("MyTable")

rawDescription: Writing a simple MongoDB module in python


rawDescription: Is there a simpler way to change 0xff01 into \\uff01?


rawDescription: Extract a list from itertools.cycle

description: Extract a list from itertools.cycle


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

us = [np.array(([0,1,0],[1,1,1],[0,1,0])), np.array(([0,1,0],[1,1,1],[0,1,0]))]
centers = [[10,20],[40,40]]

plt.figure()
for cm,u in zip(centers,us):
    n,m = u.shape
    X = np.arange(n+1)
    Y = np.arange(m+1)
    # center and shift coordinates
    X = X - n/2.0 + cm[0]
    Y = Y - m/2.0 + cm[1]
    plt.pcolormesh(X,Y,u)

rawDescription: Superimpose heat maps in one plot in python


code: df.loc[:,  [col for col in df.columns.levels[0] if col != 'bar']] = 0

rawDescription: use column name as condition for where on pandas DataFrame

description: Use column name as condition for where on pandas DataFrame


code:
from itertools import count

iter_count = count()

animations = {
    action : {
        direction : (
            (duration, (count, x)) for c in (next(iter_count),) for x in frames
        ) for direction in directions
    } for action in actions
}

rawDescription: How to find the iteration index in this loop

description: Find the iteration index in this loop


code:
if len(doca_dic) < len(docb_dict):
    short_dict, long_dict = doca_dic, docb_dic
else:
    short_dict, long_dict = docb_dic, doca_dic
similarity = 0
for x in short_dict:
    if x in long_dict:
        #calculate the similarity by summing the products of the tf-idf_norm
        similarity += short_dict[x] * long_dict[x]

rawDescription: Document Similarity: Comparing two documents efficiently


code:
def reverseList(listXS):
    return [] if not listXS else listXS[-1:] + reverseList(listXS[:-1])

rawDescription: Using recursion to reverse a list in python?


code:
per_user = {}

for perm in inputlist:
    key = perm['id'], perm['name']
    per_user.setdefault(key, {})[perm['perm']] = True

[{'perms': value, 'id': key[0], 'user': key[1]} for key, value in per_user.iteritems()]

rawDescription: Group by a list of dicts by two values in python


code: [Test(foo=1, bar=3), Test(foo=10, bar=20)]

rawDescription: Default constructor parameters in pyyaml


rawDescription: Calculate mean of sub arrays within a larger 3D array in Python


code: np.all(np.diff(l, 2) == 0)

rawDescription: Verifying arithmetic sequence python

description: Verifying arithmetic sequence python


code:
def smartcopy(filestocopy, dest_path, show_progress = False):
    """Determines what buffer size to use with copy()
       Setting show_progress to True calls back display_progress()"""
    #filestocopy is a list of dictionaries for the files needed to be copied
    #dictionaries are used as the fullpath, st_mtime, and size are needed
    if len(filestocopy.keys()) == 0:
        return None
    #Determines average file size for which buffer to use
    average_size = 0
    for key in filestocopy.keys():
        average_size += int(filestocopy[key]['size'])
    average_size = average_size/len(filestocopy.keys())
    #Smaller buffer for smaller files

    kwargs = {}
    if show_progress:
        kwargs['callback'] = lambda pos, total: display_progress(pos, total, key)

    #Bigger buffer for bigger files
    if average_size >= 1024*10000: #Buffer sizes determined by informal tests on my laptop
        kwargs['buffer'] = 1024 * 2600

    for key, value in filestocopy.iteritems():
        #dest_path+key is the destination path, as the key is the relative path
        #and the dest_path is the top level folder
        copy(value['fullpath'], dest_path+key, **kwargs)

rawDescription: Is there a better way to feed different parameters into a function with if-statements?


code:
im = Image.open(file_path)
exif_data = im.info['exif']

rawDescription: Write EXIF-data from TIF (read with exifread) to JPEG-file using PIL (Pillow)


code:
def setSignal(self,type):
    self.signal = pyqtSignal(type)

rawDescription: PyQt5 signal-slot decorator example

description: PyQt5 signal-slot decorator example


code:
import difflib
Org = ['AMEND', 'ASTRT', 'ETIME', 'OBJ', 'ast', 'bias', 'chip', 'cold']
mod = ['AMEND', 'ASTRT', 'OBJ', 'ast', 'bias', 'chip', 'cold', 'flat', 'deb']
list(difflib.ndiff(Org, mod))

rawDescription: python, detecting elements have been removed/added/changed positions in a list

description: Python, detecting elements have been removed/added/changed positions in a list


code:
import pickle
a = Foo(foo=1)
b = pickle.loads(pickle.dumps(a, pickle.HIGHEST_PROTOCOL))
a is b

rawDescription: Python pickling keep object identity

description: Python pickling keep object identity


rawDescription: Replace non-ASCII characters with a single space


rawDescription: Running Django test with setup.py test and tox


code:
x = np.unique(data['x'])
y = np.unique(data['y'])
r = data['value'].reshape((x.size,y.size))

rawDescription: Nx3 column data to 2d matrix for image processing


code:
groups = itertools.groupby(initial, operator.itemgetter('query'))
def filterkeys(d):
    return {k: v for k, v in d.items() if k in ('rank', 'url')}
filtered = ((key, map(filterkeys, group)) for key, group in groups)
print([{"query": key, "results": list(group)} for key, group in filtered])

rawDescription: Correct use of a fold or reduce function to long-to-wide data in python or javascript?


code:
my_car = create_car(type_of_car)
my_car.start_engine()

rawDescription: Why the syntax for open() and .read() is different?


rawDescription: How to get a function name as a string in Python?

description: Get a function name as a string in Python


code:
import pyodbc
db = pyodbc.connect('Driver={SQL Server Native Client 10.0};Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;')

rawDescription: How to connect to a SQL Server database in Anaconda

description: Connect to a SQL Server database in Anaconda


code:
import seaborn as sns
tips = sns.load_dataset("tips")
sns.regplot(x="total_bill", y="tip", data=tips,
            marker='o', color='red', scatter_kws={'s':2})

rawDescription: How to change the point size for regplot(), seaborn's scatter plot function (python)

description: Change the point size for regplot(), seaborn's scatter plot function (python)


code:
import _sha
_sha.__file__

rawDescription: _sha import in python hashlib

description: _sha import in python hashlib


code:
class Signal:
    def __init__(self):
        self.subs = []

    def subscribe(self, s):
        self.subs.append(s)

    def signal(self, *args, **kwargs):
        for s in self.subs:
            s(*args, **kwargs)

rawDescription: Handle communication in multi layer application


rawDescription: numpy structured array from arbitrary-level nested dictionary

description: Numpy structured array from arbitrary-level nested dictionary


code:
def do_stuff(val):
    print("Started execution of do_stuff()")

    yield val + 3
    print("Line after 'yield val + 3'")
    yield val + 4
    print("Line after 'yield val + 4'")

    print("Finished executing do_stuff()")

my_gen = do_stuff(10)

val = next(my_gen)
print("--received {} from generator".format(val))

rawDescription: Python yield vs Ruby yield

description: Python yield vs Ruby yield


code:
d = { 'token': 10,'custid':100,cycle:"yes" }
select_stmt = "SELECT * FROM kart_user WHERE {key} = '{value}'"
allowed_col = ['token', 'custid'] # Predefined column names to allow from coming dictionary.
for key, value in d.iteritems():
    if  key in allowed_col:
        select_stmt = select_stmt.format(key=key, value=value)
        cursor.execute(select_stmt, dist)
        # Further fetching code you can execute. Here you will get select statement for particular key and value.

rawDescription: Python string substitution for dynamic column name and values


code:
s = next(l['href'] for link in soup.find_all('div', class_='pagination')
         for l in link.find_all('a') if not re.search('pageSub', l['href']))

rawDescription: Improving a python snippet

description: Improving a python snippet


code: df.pivot_table(values='finish', index=['player', 'id'], columns=['year', 'tournament'])

rawDescription: Pandas - Convert Unbalanced Panel Data to Cross Section


rawDescription: if == True, make True for one moment while in loop

description: If == True, make True for one moment while in loop


code:
pre = ('MemTotal', 'MemFree', 'Cached', 'SwapTotal', 'SwapFree', 'AnonPages', 'Dirty', 'Writeback', 'PageTables', 'HugePages_')
with open("/proc/meminfo") as f:
    out = [line.rsplit(None, 2)[1] for line in f if r.search(line)]
print("   ".join(out))

rawDescription: converting bash/shell line into python 2.6

description: Converting bash/shell line into python 2.6


code:
#! /usr/bin/env python

''' Text output buffer

    Write fixed width lines to a text file

    Written by PM 2Ring 2015.03.23
'''

class LineBuffer(object):
    ''' Text output buffer

        Write fixed width lines to file fname
    '''
    def __init__(self, fname, width):
        self.fh = open(fname, 'wt')
        self.width = width
        self.buff = []
        self.bufflen = 0

    def write(self, data):
        ''' Write a string to the buffer '''
        self.buff.append(data)
        self.bufflen += len(data)
        if self.bufflen >= self.width:
            self._save()

    def _save(self):
        ''' Write the buffer to the file '''
        buff = ''.join(self.buff)

        #Split buff into lines
        lines = []
        while len(buff) >= self.width:
            lines.append(buff[:self.width])
            buff = buff[self.width:]

        #Add an empty line so we get a trailing newline
        lines.append('')
        self.fh.write('\n'.join(lines))

        self.buff = [buff]
        self.bufflen = len(buff)

    def close(self):
        ''' Flush the buffer & close the file '''
        if self.bufflen > 0:
            self.fh.write(''.join(self.buff) + '\n')
        self.fh.close()

def testLB():
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    fname = 'linebuffer_test.txt'
    lb = LineBuffer(fname, 27)
    for _ in xrange(30):
        lb.write(alpha)
    lb.write(' bye.')
    lb.close()

if __name__ == '__main__':
    testLB()

rawDescription: Python splitting with string as delimiter


code: url = ParameterisedHyperlinkedIdentityField(view_name="user-device-detail", lookup_fields=(('<model_field_1>', 'user_pk'), ('<model_field_2>', 'uid')), read_only=True)

rawDescription: django-rest-framework HyperlinkedIdentityField with multiple lookup args

description: Django-rest-framework HyperlinkedIdentityField with multiple lookup args


code:
def voice(char):
    return unicodedata.normalize('NFC', char + '\u3099')

rawDescription: Is there any way to do "logical" transformations between Japanese kana characters with different diacritical marks?


code:
from cStringIO import StringIO
from pandas import *

reportText = StringIO(reportResult.text)
reportDF = read_csv(reportText, sep=',',parse_dates=False)

rawDescription: fastest way in python to read csv, process each line, and write a new csv

description: Fastest way in python to read csv, process each line, and write a new csv


code:
lines = your_text.splitlines()
lastword = lines[line_to_replace].split()[-1]
lines[line_to_replace] = lines[line_to_replace].replace(lastword, word_to_replace_with)

rawDescription: Python: How to replace the last word of a line from a text file?


rawDescription: Round to a given number in Python

description: Round to a given number in Python


rawDescription: Using python's in-place addition with unpacked tuples


code: list(eachWithPrefix(v))

rawDescription: How to group strings with similar beginnings in a sorted list?

description: Group strings with similar beginnings in a sorted list


code:
import os
os.system('ssh -t -t myname@myserver "nice -11 screen"')

rawDescription: SSH and Screen with a Python script

description: SSH and Screen with a Python script


code:
outputfile = inputfile + '.tmp'
with open(inputfile, 'rb') as inf, open(outputfile, 'wb') as outf:
    reader = csv.reader(inf)
    writer = csv.writer(outf, delimiter='|')
    for row in reader:
        writer.writerow([col.replace('|', ' ') for col in row])
os.remove(inputfile)
os.rename(outputfile, inputfile)

rawDescription: Pipe delimiter file, but no pipe inside data


code:
a = [4, -5, 10, 4, 4, 4, 0, 4, 4]
a1 = np.array(a)
indices = a1.argsort()
indices = indices[a1[indices] != -5]
print(indices[:3])

rawDescription: Get the three minimum values of an array in Python, ignoring a value


code: list3 = filter(lambda e: e[0] in list1, list2)

rawDescription: Find matching values in a list of lists using python


rawDescription: How to accept "open document" events in py2app based Python app when the app is already running?

description: Accept "open document" events in py2app based Python app when the app is already running


code: A, B, C, D = (row for row in m)

rawDescription: How to plot contours from multidimensional data in MatPlotLib (NumPy)?

description: Plot contours from multidimensional data in MatPlotLib (NumPy)


code:
british = get_timezone('Europe/London')
format_datetime(dt, 'H:mm zzzz', tzinfo=british, locale='en_US')

rawDescription: Python timezone full names

description: Python timezone full names


code:
YourModel.objects.using("db_for_write").bulk_create(
    [your_model_instance1, your_model_instance2, etc]
    )

rawDescription: Django -- Multiple Databases -- Data Migration


rawDescription: ARCGIS: open feature into TOC

description: ARCGIS: open feature into TOC


code:
d = {}
d['theSentence'] = re.sub(r'(\w+)=(\S+)',
    lambda m: d.setdefault(m.group(1), m.group(2)) and '',
    s).strip()

rawDescription: Python tokenize sentence with optional key/val pairs


code:
import re
re.sub(r'\b\w{1,3}\b', '', 'The quick brown fox jumps over the lazy dog')
re.sub(r'\b\w{1,3}\b', '', 'I am in a bank.')

rawDescription: Remove words of length less than 4 from string


rawDescription: how to get uploaded file name in django

description: Get uploaded file name in django


code:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import svm
from sklearn.pipeline import Pipeline

vectorizer = TfidfVectorizer()
clf = svm.SVC()
tfidf_svm = Pipeline([('tfidf', vectorizer), ('svc', clf)])

documents, y = load_training_data()
tfidf_svm.fit(documents, y)

rawDescription: How to use save model for prediction in python

description: Use save model for prediction in python


code:
def passVars():
    variable = "bla"
    return variable

rawDescription: Run Python script from another and pass the variables and output


code: soup.find_all('from')[2].string    # get the string in the third `from` tag

rawDescription: Python; BeautifulSoup and inbuilt Functions


code:
import json

raw = sc.textFile("/path/to/file.json")
deserialized = raw.map(lambda x: json.loads(x))
desired_fields = deserialized.map(lambda x: x['key1'])

rawDescription: Spark and Python use custom file format/generator as input for RDD


code:
import string
import json

values = dict(title='titleVar', content='contentVar')

with open('/tmp/values', 'w') as f:
    json.dump(values, f)

with open('/tmp/values', 'r') as f:
    newvals = json.load(f)

s = string.Template('''\
$title
$content''')
result = s.safe_substitute(newvals)
print(result)

rawDescription: storing template replacement values in a separate file

description: Storing template replacement values in a separate file


code:
i = 1
while i<5:
    continue   # Endless loop because we're going to the next iteration
    i = i + 1

rawDescription: Continue and pass: what's the difference?


code:
from itertools import ifilter, ifilterfalse

l1 = list(ifilter(condition, l))
l2 = list(ifilterfalse(condition, l))

rawDescription: python list.iteritems replacement

description: Python list.iteritems replacement


rawDescription: Getting and analyzing the index columns of a dataframe


code:
f = func()
func()

rawDescription: When IDLE does implicit print?

description: When IDLE does implicit print


code:
#!/usr/bin/env python2.7
from argparse import ArgumentParser

def funky(x, a='alpha', b=False):
    pass

if __name__ == '__main__':
    import argparse
    import inspect

    funky_spec = inspect.getargspec(funky)
    defaults = funky_spec.defaults
    defaults = dict(zip(funky_spec.args[-len(defaults):], defaults))
    # effect: ['x', 'a', 'b'] + ('alpha', False) -> {'a': 'alpha', 'b': False}

    parser = argparse.ArgumentParser()
    parser.add_argument('x', help='input number')
    parser.add_argument('-a', default=defaults['a'])
    parser.add_argument('-b', action='store_true', default=defaults['b'])
    args = parser.parse_args()

    funky(x=args.x, a=args.a, b=args.b)

rawDescription: How can I avoid redundancy when I handle default arguments to modules that may also be parsed from the command line?

description: Avoid redundancy when I handle default arguments to modules that may also be parsed from the command line


code:
class EpisodeManager(models.Manager):
    def upcoming(self):
        return self.get_queryset().filter(air_time__lt=now())

    def live(self):
        return self.get_queryset().filter(
            air_time__gte=now(),
            end_time__lt=now()
        )

    def vod(self):
        return self.get_queryset().filter(
            end_time__lte=now()
        )

class Episode(models.Model):
    ...

    objects = EpisodeManager()

rawDescription: Best way to keep data in an object updated based on some logic?

description: Keep data in an object updated based on some logic


code:
x2
x2 > -np.inf

rawDescription: Filter numpy array by comparing elements to elements in prior row without looping


code:
from x import mf_collection, pop

pop()

for mf_group in mf_collection.itervalues():  # this yields lists of MovieFiles
    for mf in mf_group:  # this yields the actual MovieFiles
        ft = mf.fulltitle
        title = mf.title

rawDescription: Passing Custom Class in Python

description: Passing Custom Class in Python


rawDescription: How Python's a, b = b, a works?

description: How Python's a, b = b, a works


code: [x for x in random.choice([p for p in itertools.permutations(s, 3) if len(set(p)) == 3])]

rawDescription: Python Random List Comprehension

description: Python Random List Comprehension


rawDescription: In Python, how to check if a string only contains certain characters?


code:
from django.conf.urls import url
from rest_framework import routers

from . import views

router = routers.SimpleRouter()
router.register(r'users', views.UserViewSet)

urlpatterns = [
    url(r'^users/me/$', views.UserViewSet.as_view(), kwargs={'pk': 'me'}),
    url(r'^', include(router.urls)),
]

rawDescription: DRF - make an resource alias /me for current user


code: (True in a) and ("a" in a)

rawDescription: Python 2.7: Using reduce to verify that elements are in a list


code:
input_dict = {"a":"b", "c":1}
for key, value in input_dict.items():
    try:
            exec( "{} = {}".format(key, value))
    except:
            exec( "{} = {}".format(key, "'" + str(value) + "'"))

a
c

rawDescription: How to convert dict to expressions in python

description: Convert dict to expressions in python


code:
del list_item[4]
del dictionary["alpha"]

rawDescription: When is del useful in python?

description: When is del useful in python


code: df.xs(1, level='A', drop_level=False) # axis=1 if columns

rawDescription: selecting from multi-index pandas

description: Selecting from multi-index pandas


rawDescription: Base convert in python given a string

description: Base convert in python given a string


code:
a = 'abcderui'
len(a.translate(None, 'aeiou'))

rawDescription: Count length of string without vowels

description: Count length of string without vowels


code:
attrs = [1, 'bomb', 'C4', 'red', 'evil', 'yup']
print('{0:<4}{1:<16}{2:<10}{3:<11}{rest}'.format(*attrs[:4], rest=' '.join(attrs[4:])))
# Note in earlier versions of py2 you have to refer to format arguments by index or key, {} won't work

rawDescription: Printing an List without brackets, without quotations, without commas and additional spacing


code:
import calendar
print(calendar.timegm(date.utctimetuple()))
# 1231545600

rawDescription: parse a date to utc unixtime

description: Parse a date to utc unixtime


code:
import regex

words = [ ['a', 'the', 'one'], ['reason', 'reasons'], ['for', 'of'] ]

pattern = r'\m \L<word1> \s+ \L<word2> \s+ \L<word3> \M'
p = regex.compile(pattern, regex.X, word1=words[0], word2=words[1], word3=words[2])

s = 'the reasons for'

print(p.search(s))

rawDescription: Python regex: Alternation for sets of words


rawDescription: Python xml Trying to show a if statement on a tag


code:
from collections import OrderedDict
import json

with open('data.json', 'r') as f:
    data = json.load(f, object_pairs_hook=OrderedDict)

rawDescription: how to Change dictionary values in python file

description: Change dictionary values in python file


code:
factor = pd.factorize(df.Class)
# forward
df.Class = factor[0]
# backward
df.Class = factor[1]

rawDescription: Python replacing column values with 0-x indexes (for xgboost)


code:
import re

foo = ['am','pm']
timex = re.compile('({foo})'.format(foo='|'.join(foo)))

bar = "It's 6:00 pm, do you know where your brain is?"

timex.findall(bar)

rawDescription: Python 2.7 regex with format multiple list items


code: map(len, data)

rawDescription: Scrapy hxs.select() not selecting all results


code:
# only include this when you would have a screen where the country
# is preset and would not change, but you want to use it as a search context
country = forms.ModelChoiceField(queryset=Country.objects.all(),
                                 widget=forms.HiddenInput())
state = StateChoices(widget = AutoHeavySelect2Widget(
    select2_options = {
        'minimumInputLength': 1,
        'ajax': {
            'dataType': 'json',
            'quietMillis': 100,
            'data': JSFunctionInContext('s2_state_param_gen'),
            'results': JSFunctionInContext('django_select2.process_results'),
        }
    }))

rawDescription: Update the Queryset of a Django-Select2 AutoModelSelect2Field


code: C = numpy.sum(A * B, -1)

rawDescription: 3D array multiplication

description: 3D array multiplication


code:
# myproject/myapp/management/commands/fleetworker.py
from mpi4py import MPI

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'Example worker process.'

    def handle(self, *args, **options):
        self.stdout.write("Worker launched.")

        comm = MPI.Comm.Get_parent().Merge()
        rank = comm.Get_rank()
        self.stdout.write('Worker rank {}.'.format(rank))

        data = comm.scatter()
        result = "{!r}, {!r}".format(rank, data)

        comm.gather(result)
        self.stdout.write("Finished worker.")

        comm.Disconnect()

rawDescription: Launch MPI worker processes in a Django app


code:
a = MyClass()
a = prova.DBLogWrapper(a, ['hello'])
a.hello()
a.goodbye()

rawDescription: How to wrap python instance methods at runtime

description: Wrap python instance methods at runtime


rawDescription: Python add object to list inside same object method


code: namedPi = Record._make(tuplePi)

rawDescription: How to cast tuple into namedtuple?

description: Cast tuple into namedtuple


code: ax.scatter(xs, ys, zs, c=cs, marker=m)

rawDescription: Matplotlib 3D Scatter Plot with Colorbar


code:
from itertools import defaultdict
countlist = defaultdict(int)
for word in allwords:
    countlist[word] += 1

rawDescription: Print frequency of words, in a sentence, in a single line


code: fig.suptitle(r'$H_2$ Emission from GJ832')

rawDescription: Force LaTeX font to match default matplotlib font


code: mu

rawDescription: Numpy - Matrix Generation from list comprehension


rawDescription: Does Indexing makes Slice of pandas dataframe faster?


code:
r=Result({1:1,"_foo":2, "bar":3})
for item in r:
    print(item)

rawDescription: Custom iteration behavior in dict subclass


code:
print(const.y)
# foo

rawDescription: python binding of variable to particular expression

description: Python binding of variable to particular expression


code:
def check (x):
    for f in f_array:
        if not f (x):
            return False
    return True

return check

rawDescription: Can you dynamically combine multiple conditional functions into one in Python?

description: Dynamically combine multiple conditional functions into one in Python


code:
class Forgive:
  def __init__(self, value = None):
    self.value = value
  def __getitem__(self, name):
    if self.value is None:
      return Forgive()
    try:
      return Forgive(self.value.__getitem__(name))
    except (KeyError, AttributeError):
      return Forgive()
  def get(self, default = None):
    return default if self.value is None else self.value

data = {'actor':{'username': 'Joe'}}
print(Forgive(data)['actor']['username'].get('default1'))
print(Forgive(data)['actor']['address'].get('default2'))

rawDescription: python .get() and None

description: Python .get() and None


rawDescription: PyQt proper use of emit() and pyqtSignal()


code:
from itertools import permutations
list(permutations([1,2,2]))

rawDescription: manipulating the output of itertools.permutations in python

description: Manipulating the output of itertools.permutations in python


code:
def propagate_fc(board, N, P, Q, row, col, num):
    # no copying any more here

    #row propagate
    for x in range(N):
        if board[x][col][0] == 0:
            if num in board[x][col][1]:
                board[x][col][1].remove(num)
        if len(board[x][col][1]) == 0:
           return False

    #col propagate
    for y in range(N):
        if board[row][y][0] == 0:
            if num in board[row][y][1]:
                board[row][y][1].remove(num)
        if len(board[row][y][1]) == 0:
            return False

    #box propagate
    rDiv = row/P
    cDiv = col/P
    for i in range((rDiv * P), ((rDiv + 1) * P)):
        for j in range((cDiv * Q), ((cDiv + 1) * Q)):
            if board[i][j][0] == 0:
                if num in board[i][j][1]:
                    board[i][j][1].remove(num)
            if len(board[i][j][1]) == 0:
                return False

    return board #success; return new board

rawDescription: Backtracking in sudoku solver failing

description: Backtracking in sudoku solver failing


code:
import itertools

a = 'ABCDE'
b = 'xy'

list(itertools.izip_longest(a, b, fillvalue='-'))
list(itertools.izip(a, itertools.cycle(b)))

rawDescription: izip_longest with looping instead of fillvalue

description: Izip_longest with looping instead of fillvalue


code:
from functools import wraps

def intercept(target,**trigger):
    def decorator(func):
        names = getattr(func,'_names',None)
        if names is None:
            code = func.func_code
            names = code.co_varnames[:code.co_argcount]
        @wraps(func)
        def decorated(*args,**kwargs):
            all_args = kwargs.copy()
            for n,v in zip(names,args):
                all_args[n] = v
            for k,v in trigger.iteritems():
                if k in all_args and all_args[k] != v:
                    break
            else:
                return target(all_args)
            return func(*args,**kwargs)
        decorated._names = names
        return decorated
    return decorator

rawDescription: How can I use named arguments in a decorator?

description: Use named arguments in a decorator


code:
self.response.out.write("""
<form name="search_form" action="/searchhandler" method="GET"><br />
<input type="text" name="search_string" size=40>
<input type="submit" value="search tags">
</form>""")

rawDescription: How do I add search parameters to search page url?

description: Add search parameters to search page url


code:
length, rand = 4, 2
key = "XPMGTDHLYONZBWEARKJUFSCIQV"
key[rand:rand + length]

rawDescription: How do I move a specific part of a string to a new string

description: Move a specific part of a string to a new string


code:
# append new IDs to another table in the database
for j, k in idList.iteritems():
    sql = "INSERT INTO newID values ('%s', '%s')" %(j,k)
    cursor.execute(sql)

rawDescription: is there a way to speed up this python program? (short)

description: Is there a way to speed up this python program? (short)


code:
inputlist = ['A, B, C, D, e, f, g, h, i', '1, 2, 3, 4, 5, 6, 7, 8, 9',]
result = []
for elem in inputlist:
    elems = elem.split(', ')
    elems[4:] = [tuple(elems[4:])]
    result.append(tuple(elems))

result

rawDescription: How can I format a list into a tuple with sub-tuples?

description: Format a list into a tuple with sub-tuples


code:
flabbergast
boggle
bowl_over
dumbfounded
dumfounded
stupefied
thunderstruck
dumbstruck
dumbstricken

rawDescription: Python : Error in comparing strings

description: Python : Error in comparing strings


rawDescription: f2py: Specifying real precision in fortran when interfacing with python?

description: F2py: Specifying real precision in fortran when interfacing with python


code:
import csv
import datetime
from itertools import repeat

header = ['Stock', 'Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']
stocklist=['CCK','MSFT','AA','AAPL']
start = datetime.datetime(2015, 12, 21)
#end = datetime.datetime(2015, 12, 31)
for stock in stocklist:
    q = GoogleQuote(stock, start.strftime('%F'))
    data = zip(repeat(q.symbol), q.date, q.time, q.open_, q.high, q.low, q.close, q.volume)
    with open('{}.csv'.format(stock), 'w') as f:
        w = csv.writer(f)
        w.writerow(header)
        w.writerows(data)

rawDescription: prepend a header to .csv file with python

description: Prepend a header to .csv file with python


rawDescription: What's a variable in a inner function definition in python?


code:
def make_regex(name):
    return re.compile(r'\s*%s\s*\([^;)]*\)\s*\{' % re.escape(name))

rawDescription: Python - Regexp - Find function names but not function calls


rawDescription: How to count elements in a list and return a dict?

description: Count elements in a list and return a dict


code:
from collections import defaultdict

score = '#4=DFF\n#1=DDF\n'
res = defaultdict(int)
for entry in score.splitlines():
    for pos, char in enumerate(entry, 1):
        res[pos] += ord(char)

rawDescription: How to sum value of integers based on position?

description: Sum value of integers based on position


code:
#!/usr/bin/python
import sys
import json
import urllib2

req = urllib2.Request("http://url/feed.json")
opener = urllib2.build_opener()
f = opener.open(req)
json_response = json.loads(f.read())
keywords = ['key', 'key2', 'key3']
for k, v in json_response.iteritems():
    if k in keywords:
        print(v)
        break

rawDescription: Parsing json and searching through the output


code:
with open(path) as f:
    return {left.strip(): right.strip() for left, right, *rest in tabsplit(f)}

rawDescription: Reading from file using dict comprehensions


code:
min(stats, key=lambda k:float(stats[k]['load_1min']))
max(stats, key=lambda k:float(stats[k]['load_1min']))

rawDescription: find max , min of values in multidimensional dict

description: Find max , min of values in multidimensional dict


code:
def repl(x):
    if x:
        return x.group().replace(" ", "_")
    return x

def replace_re(fle, dct):
    with open(fle) as f:
        for line in f:
            spl = set(line.split())
            phrases = chain.from_iterable(dct[word] for word in spl if word in dct)
            line = re.sub("|".join(phrases), repl, line)
            yield line

def replace_re2(fle, dct):
    cached = {}
    with open(fle) as f:
        for line in f:
            phrases = tuple(chain.from_iterable(dct[word] for word in set(line.split()) if word in dct))
            if phrases not in cached:
                r = re.compile("|".join(phrases))
                cached[phrases] = r
                line = r.sub(repl, line)
            else:
                line = cached[phrases].sub(repl, line)
            yield line

rawDescription: Fastest way to replace space for underscore for a list of words in text


code: ((cl != cl.shift()) & cl).cumsum() * cl + (ser * 0)

rawDescription: Pandas Label Sequences of 1 in a 0-1 valued Series


rawDescription: Compare element with previous along axis


code: Import('env')

rawDescription: scons construction environment inheritance

description: Scons construction environment inheritance


code:
url = 'abcdc.com'
if url.endswith('.com'):
    url = url[:-4]

rawDescription: How do I remove a substring from the end of a string in Python?

description: Remove a substring from the end of a string in Python


code:
from matplotlib import markers

def align_marker(marker, halign='center', valign='middle',):
    """
    create markers with specified alignment.

    Parameters
    ----------

    marker : a valid marker specification.
      See mpl.markers

    halign : string, float {'left', 'center', 'right'}
      Specifies the horizontal alignment of the marker. *float* values
      specify the alignment in units of the markersize/2 (0 is 'center',
      -1 is 'right', 1 is 'left').

    valign : string, float {'top', 'middle', 'bottom'}
      Specifies the vertical alignment of the marker. *float* values
      specify the alignment in units of the markersize/2 (0 is 'middle',
      -1 is 'top', 1 is 'bottom').

    Returns
    -------

    marker_array : numpy.ndarray
      A Nx2 array that specifies the marker path relative to the
      plot target point at (0, 0).

    Notes
    -----
    The mark_array can be passed directly to ax.plot and ax.scatter, e.g.::

        ax.plot(1, 1, marker=align_marker('>', 'left'))

    """

    if isinstance(halign, (str, unicode)):
        halign = {'right': -1.,
                  'middle': 0.,
                  'center': 0.,
                  'left': 1.,
                  }[halign]

    if isinstance(valign, (str, unicode)):
        valign = {'top': -1.,
                  'middle': 0.,
                  'center': 0.,
                  'bottom': 1.,
                  }[valign]

    # Define the base marker
    bm = markers.MarkerStyle(marker)

    # Get the marker path and apply the marker transform to get the
    # actual marker vertices (they should all be in a unit-square
    # centered at (0, 0))
    m_arr = bm.get_path().transformed(bm.get_transform()).vertices

    # Shift the marker vertices for the specified alignment.
    m_arr[:, 0] += halign / 2
    m_arr[:, 1] += valign / 2

    return m_arr

rawDescription: Align matplotlib scatter marker left and or right


code: df.columns = [custom_rename(lvl1, lvl2) for lvl1, lvl2 in df.columns]

rawDescription: Multiindex in pandas pivot table

description: Multiindex in pandas pivot table


code:
A = [[] for _ in xrange(2)]
A
A[0].append(1)
A

rawDescription: Python multiply sequence trick

description: Python multiply sequence trick


code:
def removeNumerics(s):
  return ' '.join([term for term in s.split() if not term[0].isdigit()])

rawDescription: Removing numbers from strings

description: Removing numbers from strings


code:
from itertools import combinations
list(combinations(range(4), 1))

rawDescription: Python generate all possible configurations of numbers on a "board"


code:
blacklist = [0]
blacklist = set([float(i) for i in blacklist])
myList = [e for e in myList if int(e) not in blacklist]

rawDescription: Remove all occurrences of an integer from a list of floats


code:
from xml.etree import ElementTree

doc = ElementTree.parse('test.xml')
nsmap = {'ns': 'http://www.digicine.com/PROTO-ASDCP-KDM-20040311#'}
ids = [id.text for id in doc.findall(".//ns:KeyId", namespaces=nsmap)]
print(ids)
...

rawDescription: XML parsing in Python using Python 2 or 3


rawDescription: numpy: broadcasting ndarray of booleans

description: Numpy: broadcasting ndarray of booleans


code:
global valid
valid = True
#not put this at start of your program
def opennewindow():
  global valid
  if valid == True:
      valid = False
      #put code for opening new window here assuming you already have that code as
      #you haven't asked for code for that

def closewindow():
    global valid
    valid = True
    self.master.destroy()

rawDescription: How to make pre initilized text appear in Tkinter Entry widget?/ How to set limit of number of same windows open?

description: Make pre initilized text appear in Tkinter Entry widget?/ How to set limit of number of same windows open


rawDescription: Why only can get the whole sliced reverse list ommiting start and end?


code:
patterns = """
P: {<NN><VBD><JJ>(<CC><JJ>)?}
"""
PChunker = RegexpParser(patterns)
PChunker.parse(pos_tag(sent1))
PChunker.parse(pos_tag(sent2))

rawDescription: How to use nltk regex pattern to extract a specific phrase chunk?

description: Use nltk regex pattern to extract a specific phrase chunk


code:
from __future__ import division
import random
import sys

def dice_roll():
    return random.randint(1, 6)

def number_of_rolls():
    return int(raw_input('Enter the number of rolls: '))

def simulate(number_of_times):
    counter = {n : 0 for n in range(2, 13)}
    doubles = 0

    for i in range(number_of_times):
        first_dice = dice_roll()
        second_dice = dice_roll()
        total = first_dice + second_dice

        doubles += 0 if first_dice != second_dice else 1
        counter[total] += 1

    return counter, doubles

def main():
    rolls = number_of_rolls()
    counter, doubles = simulate(rolls)
    total = sum(counter.values())

    for total, count in counter.items():
        print("{} - {} {:0.4f}%".format(total, count, count / rolls * 100))

    print("Doubles - {} - {:0.6f}%".format(doubles, doubles / rolls * 100))

if __name__ == '__main__':
    sys.exit(main())

rawDescription: Rolling two dice and tabulating outcomes


code:
import os
import sys

def add_to_path():

    partial_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../')
    workspace_path = os.path.abspath(partial_path)
    assert os.path.exists(workspace_path)

    projects = []

    for current, dirs, c in os.walk(str(workspace_path)):
        for dir in dirs:

            project_path = os.path.join(workspace_path, dir, 'src')

            if os.path.exists(project_path):
                projects.append(project_path)

    for project_str in projects:
        sys.path.append(project_str)

add_to_path()

rawDescription: Sphinx does not document all classes

description: Sphinx does not document all classes


code:
import itertools

def Replace():
    count = itertools.count()
    def wrapper(match):
        return '5' if next(count) > 0 else match.group()
    return wrapper

rawDescription: Python RegEx substitution of all but first instance found


code:
import subprocess
command = 'wait.bat 5 & echo hello'
p = subprocess.Popen(command, shell=True)

rawDescription: Delay command in Windows 7

description: Delay command in Windows 7


code:
def old(im):
    rows,cols = im.shape
    s = []
    for x in xrange(1,rows):
        for y in xrange(1,cols):
            s.append(im[x-1:x+2,y-1:y+2])
    return s

rawDescription: Find a 3x3 sliding window over an image

description: Find a 3x3 sliding window over an image


rawDescription: Python Image Uploading with AjaxUpload

description: Python Image Uploading with AjaxUpload


code:
with open('data.txt', 'w') as datafile:
    datafile.write(', '.join(a.dtype.names) + '\n')
    numpy.savetxt(datafile, a, '%i, %s, %s')

rawDescription: Using python dtype as headers for compressed csv


rawDescription: Can't parse YAML correctly

description: Can't parse YAML correctly


code:
def is_allowed(time_rated, duration):
    if not isinstance(time_rated, int):
        return False
    duration = {'day': 86400, 'week': 604800}.get(duration, float('inf'))
    return time.time() - time_rated > duration

rawDescription: comparing unix timestamps in python

description: Comparing unix timestamps in python


code:
for no_of_words in xrange(1, len(words)+1):
    for comb in combinations(words, no_of_words):
        ...

rawDescription: Python: anagram finder

description: Python: anagram finder


code:
df = df.reset_index().set_index(['index', 'Sub-Product'])
df

rawDescription: How to use pandas to group pivot table results by week?

description: Use pandas to group pivot table results by week


code:
import pandas as pd
df = pd.DataFrame({'word':'a the a an the'.split(),
                   'tag': list('SSTTT'),
                   'count': [30, 20, 60, 5, 10]})

print(df.groupby('word').apply(lambda subf: subf['tag'][subf['count'].idxmax()]))

rawDescription: python pandas, DF.groupby().agg(), column reference in agg()

description: Python pandas, DF.groupby().agg(), column reference in agg()


code:
import xattr
x = xattr.xattr('/Users/buzzi/Projects/apimon/apimon/check/tests/resources/brus->lux dec 28.pdf')
x.items()

rawDescription: How to get extended MacOS attributes of a file using python?

description: Get extended MacOS attributes of a file using python


rawDescription: Optimizing the search of a string in a phrases. Don't know which Python structures I need to use


code:
for permutation in orderedpermutations(columns):
    print(permutation)

rawDescription: Moving a column around in python

description: Moving a column around in python


code:
x = raw_input("Enter number: ")
type(x)

rawDescription: Iterative Comparison of raw_input

description: Iterative Comparison of raw_input


code: splitter("foo.,.bar", ".,")

rawDescription: How can I simplify this function?

description: Simplify this function


code:
Original
#Add extensions that requires NumPy to build
if is_Numpy_installed():
   import numpy
   numpy_include_dir = numpy.get_include()
   EXTENSIONS.append(
      Extension('Bio.Cluster.cluster',
              ['Bio/Cluster/clustermodule.c',
               'Bio/Cluster/cluster.c'],
              include_dirs=[numpy_include_dir],
              ))
   EXTENSIONS.append(
      Extension('Bio.KDTree._CKDTree',
              ["Bio/KDTree/KDTree.c",
               "Bio/KDTree/KDTreemodule.c"],
              include_dirs=[numpy_include_dir],
              ))
   EXTENSIONS.append(
      Extension('Bio.Motif._pwm',
              ["Bio/Motif/_pwm.c"],
              include_dirs=[numpy_include_dir],
              ))

rawDescription: Changing Biopython include path for compilation during pip installation


variable_1: something

rawDescription: Dumping multiple variables to disk in Json. One variable per line


code:
a.b.method
foo
xtime.time
q.y
x.m

rawDescription: Regex matching Python function calls

description: Regex matching Python function calls


code:
d = {'Changes': [{'StartColumn': 34, 'StartLine': 8, 'EndLine': 8, 'NewText': '\n        ', 'EndColumn': 34}, {'StartColumn': 13, 'StartLine': 9, 'EndLine': 9, 'NewText': '', 'EndColumn': 17}, {'StartColumn': 13, 'StartLine': 10, 'EndLine': 10, 'NewText': '', 'EndColumn': 17}]}
d["Changes"] = sorted(d["Changes"], key= lambda x: x["EndLine"], reverse=True)
d["Changes"]

rawDescription: Python ordering a dictionary value

description: Python ordering a dictionary value


code:
def on_select1(self, event):
    # Get index of selected option.
    index = self.lista1.curselection()[0]
    # Select corresponding options in other list-boxes.
    self.select_others(index, self.lista2, self.lista3)

def on_select2(self, event):
    # Get index of selected option.
    index = self.lista2.curselection()[0]
    # Select corresponding options in other list-boxes.
    self.select_others(index, self.lista1, self.lista3)

def on_select3(self, event):
    # Get index of selected option.
    index = self.lista3.curselection()[0]
    # Select corresponding options in other list-boxes.
    self.select_others(index, self.lista1, self.lista2)

def select_others(self, index, *others):
    for listbox in others:
        # The list-box's selection must be cleared to prevent the previous selection from remaining.
        listbox.selection_clear(0, listbox.size() - 1)
        listbox.selection_set(index)

rawDescription: Selecting values simultaneously from different Tkinter Listbox widgets in Python 3.5


code:
def norm_spirals(a,k, pi=pi, abs=abs, gamma=gamma):
    se = 0.25 + 0.5*k + 0.5j * a
    b = abs(gamma(se)/gamma(se + 0.5))
    return b * b * pi

rawDescription: Order of operations and fast computation in Python


code:
# Result from Redis
result = ['1000:123', '1050:122', '1100:125']
# Weed out the temperatures
temperatures = [int(x.split(':')[1]) for x in result]
# Get max and min temperatures
max_temp, min_temp = max(temperatures), min(temperatures)

rawDescription: redis.py - sorting hashes by particular fields

description: Redis.py - sorting hashes by particular fields


code:
df['Time'] = df.Day + " " + df.Hour

df = df[[-1]]

rawDescription: Extract specified area from DataFrame

description: Extract specified area from DataFrame


code:
starting_text = "THIS WOULD COME FROM A FILE"
...
textbox = TEXT_WIDGET_SETUP_ALREADY

textbox.insert("1.0",starting_text)
...

ending_text = textbox.get("1.0","end-1c")

rawDescription: Integrating file and text widget python/tkinter


rawDescription: Iterate through rows in pandas dateframe in a cleaner way using .iterrows() and keep track of rows inbetween specific values


code:
Vendor,Name,Model
vfoo,nhi,m1
vZ,nX,m2
v,n3,m3
vbar,nho,m4
v,na,m5
vY,nZ,m6
vbaz,nhe,m7
vX,nY,m8
v,n_,m9

rawDescription: Concatenate large files in sql-like way with limited RAM


code:
a1
b2
c3
d
e

rawDescription: Print two presorted lists into one output file in python


rawDescription: python nltk returning odd result for wordnet similarity measure

description: Python nltk returning odd result for wordnet similarity measure


code:
text = 'user:12345 location:ny search'
dict(pair.split(":") for pair in text.split() if ":" in pair)

rawDescription: python how to parse "user:12345 location:ny search"

description: Python how to parse "user:12345 location:ny search"


code:
import tkinter

class Mbox(object):

    root = None

    def __init__(self, msg, dict_key=None):
        """
        msg = <str> the message to be displayed
        dict_key = <sequence> (dictionary, key) to associate with user input
        (providing a sequence for dict_key creates an entry for user input)
        """
        tki = tkinter
        self.top = tki.Toplevel(Mbox.root)

        frm = tki.Frame(self.top, borderwidth=4, relief='ridge')
        frm.pack(fill='both', expand=True)

        label = tki.Label(frm, text=msg)
        label.pack(padx=4, pady=4)

        caller_wants_an_entry = dict_key is not None

        if caller_wants_an_entry:
            self.entry = tki.Entry(frm)
            self.entry.pack(pady=4)

            b_submit = tki.Button(frm, text='Submit')
            b_submit['command'] = lambda: self.entry_to_dict(dict_key)
            b_submit.pack()

        b_cancel = tki.Button(frm, text='Cancel')
        b_cancel['command'] = self.top.destroy
        b_cancel.pack(padx=4, pady=4)

    def entry_to_dict(self, dict_key):
        data = self.entry.get()
        if data:
            d, key = dict_key
            d[key] = data
            self.top.destroy()

rawDescription: Correct way to implement a custom popup tkinter dialog box


code:
class StoppableRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):

    stopped = False
    allow_reuse_address = True

    def __init__(self, *args, **kw):
        SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, *args, **kw)
        self.register_function(lambda: 'OK', 'ping')

    def serve_forever(self):
        while not self.stopped:
            self.handle_request()

    def force_stop(self):
        self.server_close()
        self.stopped = True
        self.create_dummy_request()

    def create_dummy_request(self):
        server = xmlrpclib.Server('http://%s:%s' % self.server_address)
        server.ping()

rawDescription: How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?

description: Stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass


code:
def mean_diff(device_id):
    return data['datetime'][groups.groups.get(device_id)].diff().mean()
mean_diff(34)

rawDescription: Fastest way to calculate average of datetime rows using pandas


rawDescription: Matching codons

description: Matching codons


code:
# Python 2.x interpreter
'exec' in dir(__builtins__)
callable(exec)  # This would return True if exec was a function

rawDescription: Where is python exec?

description: Where is python exec


rawDescription: Initializing a large list of booleans in Python


rawDescription: How to numerically integrate f(x) between a lower and an upper bound?

description: Numerically integrate f(x) between a lower and an upper bound


code:
for rank, func in functions.items():
    mask = np.all(transform(arr).argsort(-1) == rank, -1)
    out[mask] = func(arr[mask])

rawDescription: Iterating a function over the RGB values of individual pixels


rawDescription: Python, Math, and Latex: Display + Compute?


code:
import matplotlib.pyplot as plt

plt.ion()

figure = plt.figure()

plotAxes = figure.gca()

plotAxes.plot([1, 2, 3], [4, 5, 6], "b-", label = "Testaaaaaaaaaaaaaa 1")
plotAxes.plot([1, 2, 3], [6, 5, 4], "r-", label = "Test 2")

legend = Legend(figure, plotAxes, Location.EastOutside)

rawDescription: Legend outside the plot in Python - matplotlib


code:
lit = rdflib.term.Literal('Literal\nvalue', lang='en')

print(str(lit))
print('---')
print(lit.n3())

rawDescription: Python RDF lib - String value for nodes

description: Python RDF lib - String value for nodes


code:
from collections import Counter

output = {1: 0, 2: Counter()}

names = frozenset(['Teddy', 'Daniel', 'Alex'])

for dataset in data.values():
    if names.issubset(dataset[1]):
        output[1] += 1
        output[2].update(dataset[2])

rawDescription: How to find reoccuring string groups (order does not matter) in a dictionary of lists?

description: Find reoccuring string groups (order does not matter) in a dictionary of lists


code: actor = next(actor for actor in self.actors if actor.name==actorName)

rawDescription: Alternative to list comprehension if there will be only one result


code:
# Existing button processing code here
self.toggleLeds(interrupt=True)

rawDescription: Python Tkinter use to emulate blinking with interaction of multiple buttons


code:
for item in price:
    print(item.decode()) # assume utf-8

rawDescription: How to display proper output when using re.findall() in python?

description: Display proper output when using re.findall() in python


code:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('', 50000))
s.send('ADDRESS2')
s.recv(1024)

rawDescription: python search string from socket

description: Python search string from socket


code:
n = 1
while n <= 3:
    old = 'a_i=' + str(n)
    new = 'a_i=' + str(n+1)

rawDescription: Python Autocomplete Variable Name

description: Python Autocomplete Variable Name


code: im1 = im.filter(ImageFilter.BLUR)

rawDescription: Blur image with python

description: Blur image with python


code:
f = StringIO('<foo><bar></bar></foo>')
tree = etree.parse(f)
r = tree.xpath('/foo/bar')

rawDescription: Is there a function to get an element by its DOM address?


code: {k: v for d in lst for k, v in d.iteritems()}

rawDescription: Python - Convert list of single key dictionaries into a single dictionary


code:
tree = html5lib.parse('<div attr="val" U00022="">', treebuilder='lxml', namespaceHTMLElements=False)
tree.write('yourfilename', method='html')

rawDescription: parse any HTML to XML using html5lib

description: Parse any HTML to XML using html5lib


code:
old_df = sqlContext.createDataFrame(sc.parallelize(
    [(0, 1), (1, 3), (2, 5)]), ('col_1', 'col_2'))

new_df = old_df.withColumn('col_n', old_df.col_1 - old_df.col_2)

rawDescription: Adding a new column in Data Frame derived from other columns (Spark)


code: months

rawDescription: Sorting of one list using specific strings contained in the list


code:
{'canada': {'location': 'North America',
  'name': 'Canada',
  'population': '100M+',
  'president': 'none'},
 'france': {'location': 'Europe',
  'name': 'France',
  'population': '65.7M',
  'president': 'Hollande'}}

rawDescription: python, how to update the dictionaries by mutating its format?

description: Python, how to update the dictionaries by mutating its format


code:
import re
strs = """In my project, I have a bunch of strings that are.
Read in from a file.
Most of them, when printed in the command console, exceed 80.
Characters in length and wrap around, looking ugly."""
print('\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', strs)))
"""
Reading a single line at once:
for x in strs.splitlines():
    print '\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', x))
"""

rawDescription: A good way to make long strings wrap to newline in Python? (3.x)


rawDescription: How do I set the increment in a graph in matplotlib

description: Set the increment in a graph in matplotlib


code:
s='
Ввоскресень
'
import html.parser
h=html.parser.HTMLParser()
h.unescape(s)

rawDescription: Python - Convert unicode hex to string

description: Python - Convert unicode hex to string


code:
def pluralize(f):
    def on_seq(seq):
        return [f(x) for x in seq]
    def on_dict(d):
         return dict((k, f(v)) for k, v in d.iteritems())
    f.on_dict = on_dict
    f.on_seq = on_seq
    return f

rawDescription: How Awful is My Decorator?

description: How Awful is My Decorator


code:
from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import re
import time

def get_choice():
    print('MAIN MENU')
    print('1. Plot Graph A')
    print('2. Plot Graph B')
    print('3. Plot Graph C')
    print('4. History')
    print('5. Exit/Quit')

    choice = raw_input('Please choose an option: ')
    if choice == '1':
        import plotA
    elif choice == '2':
        import plotB
    elif choice == '3':
        import plotC
    elif choice == '4':
        import history
    elif choice == '5':
        exit()
    else:
        print('Try Again')
        return False
    return True

if __name__ == '__main__':
    while True:
        if get_choice() is True:
            break

rawDescription: creating a text menu, user can't enter option again

description: Creating a text menu, user can't enter option again


code:
N = 100
flips = [flip(0.2) for i in xrange(N)]
float(flips.count('H'))/N
N = 10000
flips = [flip(0.2) for i in xrange(N)]
float(flips.count('H'))/N

rawDescription: How do I simulate flip of biased coin in python?

description: Simulate flip of biased coin in python


code:
authors_string = ' & '.join([', '.join(authors[:-1]), authors[-1]]
                                if len(authors) > 2 else authors)

rawDescription: How to format inputted data and output it

description: Format inputted data and output it


code:
@staticmethod
def __neg__():
    return S.Zero    # the negation of Zero is still Zero

rawDescription: Sympy classes Zero, One and NegativeOne, why they exist?


code:
CURRENCIES = (
    (u'USD', u'US Dollars'),
    (u'EUR', u'Euro'),
    # ...
)

currency = models.CharField(max_length=3, choices=CURRENCIES)

rawDescription: Django ternary relationships

description: Django ternary relationships


code:
indptr = np.cumsum([0]+[len(i) for i in vectors])
aa = np.array(vectors,dtype='i,f').flatten()
A = sparse.csr_matrix((aa['f1'], aa['f0'], indptr))

rawDescription: scipy csr_matrix from several vectors represented as list of sets

description: Scipy csr_matrix from several vectors represented as list of sets


code:
animal = ['cat', 'dog', 'fish' , 'monkey']
name = ['george', 'steve', 'john', 'james']
zip(name, animal)

rawDescription: enumerate is iterating of letters of strings in a list instead of elements

description: Enumerate is iterating of letters of strings in a list instead of elements


rawDescription: Taking a hex file and extracting data

description: Taking a hex file and extracting data


code:
class Product(Base):

    __tablename__ = 'products'

    product_id = Column(Integer, primary_key=True)
    product_name = Column(String(100))
    product_pictures = relationship("ProductPicture")

    main_pictures = relationship("ProductPicture",
        primaryjoin="and_(Product.product_id==ProductPicture.product_id, "
                    "ProductPicture.picture_type=='main')")
    option_pictures = relationship("ProductPicture",
        primaryjoin="and_(Product.product_id==ProductPicture.product_id, "
                    "ProductPicture.picture_type=='option')")

rawDescription: SQLAlchemy one to many relationship, how to filter the collection


code:
def sortlh(lst_input):
    lst = list(lst_input) # make a copy of lst_input
    i = 0
    while i < len(lst):
        j = i + 1
        i_lowest = i
        lowest = lst[i_lowest]
        while j < len(lst):
            if lst[j] < lowest:
                i_lowest = j
                lowest = lst[i_lowest]
            j += 1
        lst[i], lst[i_lowest] = lst[i_lowest], lst[i]  # swap
        i += 1
    return lst

test = [9,8,7,6,5,4,3,2,1]
assert sortlh(test) == sorted(test)
test = [1,3,2,4,5,7,6,9,8]
assert sortlh(test) == sorted(test)

rawDescription: Selection Sort (low to high) python

description: Selection Sort (low to high) python


code:
class Item(models.Model):
   user = models.ForeignKey(User)
   # ...

rawDescription: Django query for items that have a unique field


code: T1 = T0 * Affine.translation(0.5, 0.5)

rawDescription: How to I get the coordinates of a cell in a geotif?


code:
import numpy as np

a = np.arange(1,11)
b = np.linspace(1, 0, 4)
a * np.hstack((np.ones(a.size - b.size), b))

rawDescription: Elementwise multiplication of shorter array with longer one at an offset index with numpy?


code:
import re

def work():
  to_find = re.compile("cat|fish|dog")
  search_str = "blah fish cat dog haha"
  match_obj = to_find.search(search_str)
  the_index = match_obj.start()  # produces 5, the index of fish
  which_word_matched = match_obj.group()  # "fish"
  # Note, if no match, match_obj is None

rawDescription: What's the most efficient way to find one of several substrings in Python?


code:
STATIC_ROUTES = {'static': 'MyPkg:static'}
for name, path in STATIC_ROUTES.iteritems():
    cfg.add_static_view(name=name, path=path)

rawDescription: How to get file path of a add_static_view() in Pyramid

description: Get file path of a add_static_view() in Pyramid


code:
t = [("x", "1","11"),("x", "2","22"),("x", "3","33"),
     ("y", "3","00"),("z", "2","222"), ("z", "3","333")]
order = []
mapping = {}
for outer, inner, value in t:
    if outer not in order:
        order.append(outer)
    mapping.setdefault(outer, {})[inner] = value

[(k, mapping[k]) for k in order]
mapping.items()  # ignoring order
from collections import OrderedDict
mapping = OrderedDict()
for outer, inner, value in t:
    mapping.setdefault(outer, {})[inner] = value

mapping.items()
from itertools import groupby
from operator import itemgetter
[(k, {k: v for _, k, v in g}) for k, g in groupby(t, itemgetter(0))]

rawDescription: how can I convert python tuple to dict

description: Convert python tuple to dict


code:
#!/usr/bin/python
import ephem, numpy, scipy, scipy.optimize

# Make a set of observers (observation points)
def observers(lata, lona):
    def makeIter(x):
        if hasattr(x, '__iter__'):
            return x
        return [x]
    lata, lona = makeIter(lata), makeIter(lona)
    arr = []
    for lat in lata:
        for lon in lona:
            o = ephem.Observer()
            o.lat, o.lon, o.elevation, o.temp = str(lat), str(lon), 1400, 0
            arr.append(o)
    return tuple(arr)

# Make a year of data for an observer, equinox-relative
def riseData(observr, year, skip):
    yy = ephem.Date('{} 00:00'.format(year))
    rr = numpy.arange(0.0, 366.0, skip)
    springEquinox = 78
    observr.date = ephem.Date(yy + springEquinox)
    seDelta = observr.previous_rising(ephem.Sun()) - yy - springEquinox + 1
    for i, day in enumerate(range(0, 366, skip)):
        observr.date = ephem.Date(yy + day)
        t = observr.previous_rising(ephem.Sun()) - yy - day + 1 - seDelta
        rr[i] = t
    return numpy.array(rr)

# Make a set of time curves
def makeRarSet(lata, lona, year, daySkip):
    rar=[]
    for o in observers(lata, lona):
        r = riseData(o, year, daySkip)
        rar.append(r)
    x = numpy.arange(0., 366., daySkip)
    return (x, rar)

# data() is an object that stores curves + results
def data(s):
    return data.ss[s]

# Initialize data.ss
def setData(lata, lona, year, daySkip):
    x, rar = makeRarSet(lata, lona, year, daySkip)
    data.ss = rar

# Compute y values from model, given vector x and given params in p
def yModel(x, p):
    t = numpy.zeros(len(x))
    for i in range(len(p)):
        t += p[i] * data(i)
    return t

# Compute residuals, given params in p and data in x, y vectors.
# x = independent var,  y = dependent = observations
def residuals(p, y, x):
    err = y - yModel(x, p)
    return err

# Compute least squares result
def lsr(lat, lon, year, daySkip):
    latStep = 13.
    lata = numpy.arange(0., 66.4, latStep)
    lata = [ 88 * (1 - 1.2**-i) for i in range(8)]
    l, lata, lstep, ldown = 0, [], 20, 3
    l, lata, lstep, ldown = 0, [], 24, 4
    while l < 65:
        lata.append(l); l += lstep; lstep -= ldown
    #print 'lata =', lata
    setData(lata, lon, year, daySkip)
    x, ya = makeRarSet(lat, lon, year, daySkip)
    x, za = makeRarSet(lat, 10+lon, year, daySkip)
    data.ss.append(za[0])
    y = ya[0]
    pini = [(0 if abs(lat-l)>latStep else 0.5) for l in lata]
    pars = scipy.optimize.leastsq(residuals, pini, args=(y, x))
    data.x, data.y, data.pv = x, y, yModel(x, pars[0])
    data.par, data.err = pars, residuals(pars[0], y, x)
    #print 'pars[0] = ', pars[0]
    variance = numpy.inner(data.err, data.err)/len(y)
    #print 'variance:', variance
    sec = 1.0/(24*60*60)
    emin, emax = min(data.err), max(data.err)
    print ('Lat. {:4.1f}:  Error range: {:.6f} to {:.6f} seconds'.format(lat, emin/sec, emax/sec))

def plotData(iopt, emul):
    import matplotlib.pyplot as plt
    plt.clf()
    x = data.x
    if iopt == 0:
        iopt = 15
        emul = 1
    if iopt & 1:
        plt.plot(x, data.y)
        plt.plot(x, data.y + 0.001)
        plt.plot(x, data.y - 0.001)
    if iopt & 2:
        plt.plot(x, data.pv)
    if iopt & 4:
        plt.plot(x, emul*data.err)
    if iopt & 8:
        for ya in data.ss:
            plt.plot(x, ya)
    plt.show()

rawDescription: Best strategy for storing precomputed sunrise/sunset data?


code:
s = os.stat('some_file')
s
s.st_size / 1e6 # size of data fork only, in MB
x.st_blocks * 512e-6 # total size on disk, in MB

rawDescription: How to determine file's extended attributes and resource forks with their size on Mac OSX?

description: Determine file's extended attributes and resource forks with their size on Mac OSX


code:
import lxml.sax
help(lxml.sax)

rawDescription: convert to lxml sax interface from default python xml.sax

description: Convert to lxml sax interface from default python xml.sax


code:
def combined_words(word_list):
  combined_word = ""
  for k, word in enumerate(word_list):
    combined_word += k
    if next_word_can_be_paired:
      pass
    else: # next word can't be paired
      yield combined_word
      combined_word = ""
  if combined_word:
    yield combined_word # just in case anything is left over

rawDescription: Can I skip an indeterminate amount of steps for an enclosing loop? (Python)

description: Skip an indeterminate amount of steps for an enclosing loop? (Python)


code:
from twisted.web import proxy
from twisted.internet import reactor
from twisted.internet import protocol
from twisted.internet.protocol import ReconnectingClientFactory
from twisted.protocols import basic
from twisted.python import log
import sys
log.startLogging(sys.stdout)

rawDescription: Twisted client for a send only protocol that is tolerant of disconnects


code:
class Bar(object):
    @property
    def foo(self):
        return 'foo'

    @with_descriptor_defaults(foo)
    def echo(*args):
        for a in args:
            print(a)
        print('bar')

rawDescription: How to access a class's property using a partialmethod?

description: Access a class's property using a partialmethod


code:
import pygame

# Just a definition of a few colours
class Colour(object):
    WHITE = (255, 255, 255)
    GREY  = (128, 128, 128)
    BLUE  = ( 64, 128, 255)

# GuiObject is just a rectangle with a colour at the moment (for testing purposes).
class GuiObject(object):
    def __init__(self, rect, colour):
        self.rect   = rect
        self.colour = colour
        self.enabled = True

    def render(self, screen):
        if self.enabled:
            pygame.draw.rect(screen, self.colour, self.rect)

class Gui(object):
    def __init__(self):
        self.hpbar_bg = GuiObject(( 0,  0, 150, 600), (Colour.BLUE))
        self.enemy_hpbar = GuiObject((10, 10, 200, 400), (Colour.WHITE))
        self.enabled = True

    def render(self, screen):
        #render my gui in the order i want
        if self.enabled:
            self.hpbar_bg.render(screen)
            self.enemy_hpbar.render(screen)

def main():
    ############################################################################
    # Initialise
    pygame.init()
    screen = pygame.display.set_mode((800, 600))

    gui = Gui()

    #uncomment to get the enabled/disabled behavior
    #gui.hpbar_bg.enabled = False

    #or disable the whole gui
    #gui.enabled = False

    ############################################################################
    # Main loop
    while True:
        ########################################################################
        # Event Handling
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit(0)

        ########################################################################
        # Render
        screen.fill((0, 0, 0))

        # Render GUI
        gui.render(screen)

        pygame.display.flip()

if __name__ == "__main__":
    main()

rawDescription: Pygame: Rect Objects Don't Render Properly in For Loops


code:
data_dict = {} # empty dict
data_list = [] # empty list

for i in range(50):
    data_list.append(np.loadtxt('{0}.txt'.format(i+1)))
    #or
    data_dict[i] = np.loadtxt('{0}.txt'.format(i+1))

rawDescription: Load many text files in a loop in arrays with different names with numpys loadtxt


rawDescription: Multiple format options in Python

description: Multiple format options in Python


code:
name = Entry(root)
name.delete(0, END) # clear the entry field

rawDescription: how to create clear entry text in tkinter and display on to the window

description: Create clear entry text in tkinter and display on to the window


code: "'{0}'".format(''.join(r'\x{:02x}'.format(ord(c)) for c in value))

rawDescription: Python binary conversion to hex

description: Python binary conversion to hex


code:
for x in range(0,len(tuesday)):
 print(" -",tuesday[x])

rawDescription: Use loop to print an array

description: Use loop to print an array


code:
def something_web_facing():
    ...
    queue.enqueue(crawl, 'http://url.com/start_point.html')
    ...

def crawl(start_url):
    fetch_jobs = []
    seen_urls = set()

    seen_urls.add(start_url)
    fetch_jobs.append( queue.enqueue(fetch, start_url) )

    while len(fetch_jobs) > 0:

        # loop over a copy of fetch_jobs
        for job in list(fetch_jobs):

            # has this job completed yet?
            if job.result:

                # a fetch job returns a list of the next urls to crawl
                for url in job.result:

                    # fetch this url if we haven't seen it before
                    if url not in seen_urls:
                        seen_urls.add(url)
                        fetch_jobs.append( queue.enqueue(fetch, url) )

                fetch_jobs.remove(job)

        time.sleep(1)

    return "Job done!"

def fetch(url):
    """Get web page from url, return a list of links to follow next"""

    html_page = download_web_page(url)
    links_to_follow = find_links_to_follow(html_page)
    return links_to_follow

rawDescription: How to get notified when multiple workers complete a job with an unknown size?

description: Get notified when multiple workers complete a job with an unknown size


code:
class ExampleElement(Element):
    loader = XMLFile(FilePath('template.xml'))

    extraContent = XMLString("<b>This content will be in bold</b>")

    @renderer
    def content(self, request, tag):
        return self.extraContent.load()

rawDescription: How to dump html string into a python twisted template

description: Dump html string into a python twisted template


code:
from update import UpdateManager
UpdateManager.send()

rawDescription: Having persistent runtime objects with Tornado


code: X = sm.add_constant(X)

rawDescription: Pandas/Statsmodel OLS predicting future values


rawDescription: Easy way to find what item repeated in list


code:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor

rawDescription: Scrapy: Scraping very select URLs

description: Scrapy: Scraping very select URLs


code:
db.session.begin_nested()
db.session.execute('LOCK TABLE database_version IN ACCESS EXCLUSIVE MODE;')

rawDescription: Sqlalchemy explicit locking of Postgresql table


code:
from collections import defaultdict

myDict = defaultdict(int)

for item in myTupleList:
    myDict[item[1]] += item[2]

rawDescription: Map List of Tuples into a Dictionary, python


code:
import constraint as c

p = c.Problem()
p.addVariable(0, range(1,101))
p.addVariable(1, range(1,51))
p.addConstraint(lambda i: i >= 20, [0])
p.addConstraint(lambda j: j >= 21, [1])
p.addConstraint(c.MaxSumConstraint(50))

indices = ((s[0], s[1]) for s in p.getSolutionIter())  # convert to tuple generator

rawDescription: Is there a Python library for handling complicated mathematical sets (constructed using mathematical set-builder notation)?


code:
import itertools
input = [['a','b'],['c','d'],['e','f']]
combs = []
for i in xrange(1, len(input)+1):
    els = [list(itertools.chain.from_iterable(x)) for x in itertools.combinations(input, i)]
    combs.extend(els)

rawDescription: Python all combinations of a list of lists


code: sorted(my_2d_list,reverse=True)[:4] # 4 biggest numbers ... at least it should be

rawDescription: Convert a column in a list to number, keeping other columns unchanged


code:
np.set_printoptions(threshold=np.inf, linewidth=np.inf)  # turn off summarization, line-wrapping
with open(path, 'w') as f:
    f.write(np.array2string(x, separator=', '))

rawDescription: numpy save 2d array to text file

description: Numpy save 2d array to text file


code:
import numpy as np
x=np.linspace(0,2*np.pi,10)
y=np.sin(x)
import subprocess
gnuplot = subprocess.Popen(["/usr/bin/gnuplot"],
                           stdin=subprocess.PIPE)
gnuplot.stdin.write("set term dumb 79 25\n")
gnuplot.stdin.write("plot '-' using 1:2 title 'Line1' with linespoints \n")
for i,j in zip(x,y):
   gnuplot.stdin.write("%f %f\n" % (i,j))
gnuplot.stdin.write("e\n")
gnuplot.stdin.flush()

rawDescription: Python ASCII plots in terminal

description: Python ASCII plots in terminal