code:
import numpy as N
XGridPoints = N.empty((nx, ny, nz), dtype='object')

rawDescription: Python netCDF4 append an array array

description: Python netCDF4 append an array array


rawDescription: Control screen brightness on Windows 10 with Python3.X


code:
name = input('What is your name? ')
location = input('Hello %s, where are you from? ' % name)
print("Your name is %s and you are from %s." % (name, location))

rawDescription: Using variables in input parameters

description: Using variables in input parameters


code: contour(im, levels=[245], colors='black', origin='image')

rawDescription: Extract external contour or silhouette of image in Python


code:
def addData( self, col, val):

    if col not in self._data.keys():
        self.beginInsertColumns(QModelIndex(), self.columnCount(),self.columnCount())
        # Catch this column up with the others by adding blank rows
        self._data[col] = [""] * self.rowCount()
        self.endInsertColumns()

    self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount())
    # Add data to each column, either the value specified or a blank
    for i in range(self.columnCount()):
        if i == col:
            self._data[i].append(val)
        else:
            self._data[i].append( "" )
    self.endInsertRows()

rawDescription: PyQt5: phantom columns when using QTableView.setSortingEnabled and QSortFilterProxyModel


code:
def foo_reference_default(context):
    now = datetime.now()
    month, year = now.month, now.year
    ref = context.connection.execute(db.select([Foo.__table__]).where(
        db.and_(db.extract('month', Foo.date)==month,
                db.extract('year', Foo.date)==year)
    ).count()).scalar() + 1
    return u'FOO{year}{month}-{ref:03}'.format(year=year, month=month, ref=ref)

class Foo(Model):
    __tablename__ = 'foo'
    id = Column(Integer, primary_key=True)
    date = Column(Date, default=datetime.now)
    reference = Column(Unicode, default=foo_reference_default)

rawDescription: Column with default checking same table

description: Column with default checking same table


code: filter(lambda f:isinstance(f, generic.GenericRelation), Service._meta.many_to_many)

rawDescription: django-contenttypes - List All Generic Relations for Model

description: Django-contenttypes - List All Generic Relations for Model


code:
d = dict()
d['myattr'] = 42

rawDescription: Is there a "standard" basic class in python?


rawDescription: Why can't I apply value to entire pandas column after subsetting my data frame by two conditions?


code:
#Your html body
mail_html_body = '
Hello!
'

# read data from request
mail_to = str(self.request.POST.get('to'))
mail_from = str(self.request.POST.get('from'))
mail_subject = str(self.request.POST.get('subject'))
mail_body = str(self.request.POST.get('body'))

mail.send_mail(mail_from,
               mail_to,
               mail_subject,
               mail_body,
               html = mail_html_body ) #your html body

rawDescription: Google App Engine: how to send html using send_mail


rawDescription: How do I add space between the ticklabels and the axes in matplotlib?

description: Add space between the ticklabels and the axes in matplotlib


code:
from collections import namedtuple
Norm = namedtuple('Norm', 'mu variance')
def pickle_norm(n):
    return pickle.dumps(Norm(*n.args))

def unpickle_norm(s):
    return scipy.stats.norm(*pickle.loads(s))

s = pickle_norm(scipy.stats.norm(5, 10))
d = unpickle_norm(s)

rawDescription: How to pickle a scipy.stats distribution (can't pickle instancemethod objects)

description: Pickle a scipy.stats distribution (can't pickle instancemethod objects)


code: [x + [y] for x, y in zip(list1, list2)]

rawDescription: loop through two list and extend one list by a value in the other list

description: Loop through two list and extend one list by a value in the other list


code:
from __future__ import division
import numpy as np
from scipy.spatial import Delaunay
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
from itertools import combinations

def plot_tetra(tetra, pts, color="green", alpha=0.1, lc="k", lw=1):
    combs = combinations(tetra, 3)
    for comb in combs:
        X = pts[comb, 0]
        Y = pts[comb, 1]
        Z = pts[comb, 2]
        verts = [zip(X, Y, Z)]
        triangle = Poly3DCollection(verts, facecolors=color, alpha=0.1)
        lines = Line3DCollection(verts, colors=lc, linewidths=lw)
        ax.add_collection3d(triangle)
        ax.add_collection3d(lines)

pts = np.array([
            [0,0,0],
            [1,0,0],
            [1,1,0],
            [1,0,1],
            [1,1,1],
            [0,1,0],
            [0,1,1],
            [0,0,1]])
tess = Delaunay(pts)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for k, tetra in enumerate(tess.simplices):
    color = plt.cm.Accent(k/(tess.nsimplex - 1))
    plot_tetra(tetra, pts, color=color, alpha=0.1, lw=0.5, lc="k")
ax.scatter(pts[:, 0], pts[:, 1], pts[:, 2], c='k')
plt.savefig("Delaunay.png", dpi=600)
plt.show()

rawDescription: Delaunay triangularization of Polyhedron (Python)


code:
import geopy
import pickle
import sqlite3

class Cache(object):
    def __init__(self, fn='cache.db'):
       self.conn = conn = sqlite3.connect(fn)
       cur = conn.cursor()
       cur.execute('CREATE TABLE IF NOT EXISTS '
                   'Geo ( '
                   'address STRING PRIMARY KEY, '
                   'location BLOB '
                   ')')
       conn.commit()

    def address_cached(self, address):
        cur = self.conn.cursor()
        cur.execute('SELECT location FROM Geo WHERE address=?', (address,))
        res = cur.fetchone()
        if res is None: return False
        return pickle.loads(res[0])

    def save_to_cache(self, address, location):
        cur = self.conn.cursor()
        cur.execute('INSERT INTO Geo(address, location) VALUES(?, ?)',
                    (address, sqlite3.Binary(pickle.dumps(location, -1))))
        self.conn.commit()

if __name__ == '__main__':
    # run a small test in this case
    import pprint

    cache = Cache('test.db')
    address = '1 Murphy St, Sunnyvale, CA'
    location = cache.address_cached(address)
    if location:
        print('was cached: {}\n{}'.format(location, pprint.pformat(location.raw)))
    else:
        print('was not cached, looking up and caching now')
        g = geopy.geocoders.GoogleV3()
        location = g.geocode(address)
        print('found as: {}\n{}'.format(location, pprint.pformat(location.raw)))
        cache.save_to_cache(address, location)
        print('... and now cached.')

rawDescription: Most straightforward way to cache geocoding data


code:
import pylab as pl
import numpy as np

x, y = np.mgrid[-2:1:100j, -1:1:100j]
z = np.sqrt(x*x+y*y)

cs = pl.contour(x, y, z, linewidths=2)

def path_length(path):
    v = path.vertices
    dv = np.diff(v, axis=0)
    return np.sum(np.sqrt(np.sum(dv**2, axis=-1)))

# remain the longest path and remove all others
deleted_path = []
for c in cs.collections:
    paths = c.get_paths()
    if len(paths) > 1:
        paths.sort(key=path_length, reverse=True)
        for p in paths[1:]:
            deleted_path.append((c, p))
        del paths[1:]

# create labels
r = pl.clabel(cs, cs.levels, inline=True, fontsize=10)

# restore all removed paths
for c, p in deleted_path:
    c.get_paths().append(p)

pl.show()

rawDescription: Remove duplicate matplotlib contour labels when contour goes partially outside visible area


rawDescription: PySide Dialog return values on accept

description: PySide Dialog return values on accept


code:
response = "y"
while response == "y":
    stock_name,num_share,purchase,selling_price,commission = load()
    paid_stock,commission_purchase,stock_sold,commission_sale,profit = calc(num_share, purchase, selling_price, commission)
    Print(stock_name, paid_stock,commission_purchase, stock_sold, commission_sale, profit)
    response = input("Continue input? (y/n):")

rawDescription: While Loop in function ( Python )

description: While Loop in function ( Python )


code:
names = ['John', 'Bob']
message = "{name} had a wonderful day at the park, but then {name} came and ruined it"
i = 0;
while '{name}' in message:
    message = message.replace('{name}', names[i], 1)
    i += 1

message

rawDescription: Python 3: Formatting a string with multiple same keywords but unique strings to replace them


code:
stra = 'abc'
strb = 'abd'
''.join(hex( int(a,16) ^ int(b,16) )[2:] for a,b in zip(stra, strb))

rawDescription: xor function in python

description: Xor function in python


code:
from bidi import algorithm as bidialg
import matplotlib.pyplot as plt
text = bidialg.get_display(u'שלום כיתה א')
plt.text(0.5, 0.5, text , name = 'Arial')
plt.show()

rawDescription: Matplotlib: Writing right-to-left text (Hebrew, Arabic, etc.)


rawDescription: How to split a sorted list into sub lists when two neighboring value difference is larger than a threshold

description: Split a sorted list into sub lists when two neighboring value difference is larger than a threshold


code:
class Courses(models.Model):
   name  = models.TextField()
   schools = ManyToManyField(School, related_name='courses_set')

School.objects.filter(courses_set__name__in=('biology', 'chemistry'))

rawDescription: Querying over many to many field

description: Querying over many to many field


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

x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()

rawDescription: plot with custom text for x axis points

description: Plot with custom text for x axis points


code:
from lxml.html import soupparser
from scrapy import Selector
sel = Selector(_root=soupparser.fromstring(response.body))
sel.xpath('//h4[@class="name"]/a').extract()

rawDescription: why the results of response.xpath('//html') differs than response.body?

description: Why the results of response.xpath('//html') differs than response.body


code:
[] == False
bool([]) == False
{} == False
bool({}) == False

rawDescription: Boolean testing a list in Python

description: Boolean testing a list in Python


rawDescription: How to find the corresponding class in clf.predict_proba()

description: Find the corresponding class in clf.predict_proba()


code:
fig = figure()
but = Button(fig.canvas, label="button")
original_draw = fig.canvas.draw
def draw(gc=None):
    original_draw(gc)
    but.SetLabel(but.GetLabel())
fig.canvas.draw = draw
plot([1],[1])

rawDescription: Keeping a child window visually above its parent


rawDescription: Converting a string to dictionary easily


code:
def extract_number(s,notfound='NOT_FOUND'):
    regex=r'[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?'
    return re.findall(regex,s)

rawDescription: Modify python regexp to match all floating point numbers instead of only the first one


code: {k: 1 for k in arr}

rawDescription: Convert array to dictionary (counter)

description: Convert array to dictionary (counter)


rawDescription: Python - matplotlib - How to plot a space even when .bar() takes a zero value


code:
with open('somefile.txt', 'w+') as f:
    # Note that f has now been truncated to 0 bytes, so you'll only
    # be able to read data that you wrote earlier...
    f.write('somedata\n')
    f.seek(0)  # Important: return to the top of the file before reading, otherwise you'll just read an empty string
    data = f.read() # Returns 'somedata\n'

rawDescription: Confused by python file mode "w+"

description: Confused by python file mode "w+"


code:
import requests

r = requests.get(
    'http://api.stackexchange.com/2.2/tags/python/related?pagesize=3&site=stackoverflow')

for item in r.json()['items']:
   print("{name} shares {count} tags with Python".format(**item))

rawDescription: How to scrape tag information from questions on Stack Exchange

description: Scrape tag information from questions on Stack Exchange


rawDescription: reading library method definitions

description: Reading library method definitions


code:
import requests
import json
solditems = requests.get('https://github.com/timeline.json') # (your url)
data = solditems.json()
with open('data.json', 'w') as f:
    json.dump(data, f)

rawDescription: Saving a json file to computer python

description: Saving a json file to computer python


code:
#!/usr/bin/env python
# coding: utf-8

from __future__ import print_function

try:
    import ConfigParser as configparser
except ImportError:
    import configparser

try:
    import StringIO
except ImportError:
    import io.StringIO as StringIO

test_ini = """
[some_section]
messages.welcome=Hello\
 World
messages.bye=bye
"""
config = configparser.ConfigParser()
config.readfp(StringIO.StringIO(test_ini))
print(config.items('some_section'))

rawDescription: How to read multiline .properties file in python

description: Read multiline .properties file in python


code:
previous_managers = dict()
for line in csv:
    name = line.name
    project = line.project
    manager = line .manager

    if project == 'SICK':
        manager = previous_managers[person] or 'NULL'
    else:
        previous_managers[person] = manager

    write(name, project, manager)

rawDescription: Editing a lines in a csv file based on previous lines


code:
import csv
import sqlite3
from collections import namedtuple

conn = sqlite3.connect('statictest.db')
c = conn.cursor()

c.execute('''CREATE TABLE if not exists movies (ID INTEGER PRIMARY KEY AUTOINCREMENT, 'watched_on','title','score_rating')''')

record = namedtuple('record',['watched_on','title','score_rating'])

SQL ='''
INSERT INTO movies ("watched_on","title","score_rating") VALUES (?,?,?)
'''

with open('statictest.csv', 'r') as file:

    read_data = csv.reader(file)
    for row in read_data:
        watched_on, title, score_rating = row
        data = (record(watched_on, title, score_rating))
        c.execute(SQL, data)
        conn.commit()

rawDescription: Trying to load records from CSV to mysql


code:
def show_polls_with_choices(self):
    return Poll.objects.exlude(choice_set__isnull=True)

def get_queryset(self):
    """Return the last five published NOT EMPTY polls."""
    #Returns polls published at a date the same as now or before
    return self.show_polls_with_choices().filter(pub_date__lte=timezone.now()).order_by('pub_date')[:5]

rawDescription: Preventing polls without choices from being published


code:
def app(environ, start_response):
    path    = environ['PATH_INFO']
    method  = environ['REQUEST_METHOD']
    if method == 'POST':
        if path.startswith('/test'):
            try:
                request_body_size = int(environ['CONTENT_LENGTH'])
                request_body = environ['wsgi.input'].read(request_body_size)
            except (TypeError, ValueError):
                request_body = "0"
            try:
                response_body = str(request_body)
            except:
                response_body = "error"
            status = '200 OK'
            headers = [('Content-type', 'text/plain')]
            start_response(status, headers)
            return [response_body]
    else:
        response_body = open('test.html').read()
        status = '200 OK'
        headers = [('Content-type', 'text/html'),
                    ('Content-Length', str(len(response_body)))]
        start_response(status, headers)
        return [response_body]

rawDescription: How to catch POST using WSGIREF

description: Catch POST using WSGIREF


code:
import ast
s = "[u'foo']"
ast.literal_eval(s)

rawDescription: Python convert formatted string to list

description: Python convert formatted string to list


code:
from collections import defaultdict
statistics={}
for (customer_type, habits) in groupedList:
    statistics[customer_type]=defaultdict(int)
    for times in habits:
        statistics[customer_type][times]+=1

rawDescription: PySpark statistics on values

description: PySpark statistics on values


code:
class Ball:
    def spawn(self):
        self.sinceSpawn = 0

    def update(self, dt):
        if not gamePaused:
            self.sinceSpawn += dt
        if self.sinceSpawn >= BALL_WAIT_TIME:
            pass #Do something here

rawDescription: Stop time without freezing the program

description: Stop time without freezing the program


code:
import pandas as pd
import matplotlib.pyplot as plt
from numpy.random import randn
from pandas.tools.plotting import scatter_matrix

df = pd.DataFrame(randn(1000, 4), columns=['a', 'b', 'c', 'd'])

Axes = scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal='kde')

#y ticklabels
[plt.setp(item.yaxis.get_majorticklabels(), 'size', 15) for item in Axes.ravel()]
#x ticklabels
[plt.setp(item.xaxis.get_majorticklabels(), 'size', 5) for item in Axes.ravel()]
#y labels
[plt.setp(item.yaxis.get_label(), 'size', 20) for item in Axes.ravel()]
#x labels
[plt.setp(item.xaxis.get_label(), 'size', 3) for item in Axes.ravel()]

rawDescription: label size in panda plot (scatter_matrix)

description: Label size in panda plot (scatter_matrix)


code:
class Game(wx.App):
    def OnInit(self):  # upon game opening
        # I would like the options window to be the first window's parent
        # so I will first set up our options window:
        window = Frame(None, -1, "Good Luck!", GAME_POSITION, GAME_SIZE)
        first_panel = window.panel

        #This lines of code add the grid to the frame
        grid = gridlib.Grid(first_panel) #the grid must created with a panel as argument
        grid.CreateGrid(10,3) #create grid with 10 rows and 3 columns
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(grid, 0, wx.ALIGN_CENTER|wx.ALL, 50) #Border in all directions with 50 pixels width
        first_panel.SetSizer(sizer)
        #grid has been added to the frame... continuing with your code

        window.write(first_panel, "BULLS AND COWS!", (20, 20), size=(35))
        countX = 500
        countY = 100
...

rawDescription: How to add a grid to my programm without that all of the rest of the programm will be deleted?

description: Add a grid to my programm without that all of the rest of the programm will be deleted


code:
df.ix[df.index.is_month_end==True, 'SD.prevmo'] = df['SD']
df['SD.prevmo'].fillna(method='ffill')

rawDescription: python pandas: trying to reference data from another column's previous month end

description: Python pandas: trying to reference data from another column's previous month end


code:
import json

with open('data.json') as json_data:
    data = json.load(json_data)
    for element in data:
        del element['imageData']

rawDescription: Removing JSON property in array of objects with Python


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

y = np.sin(np.linspace(0, 2*np.pi, 32, endpoint=False))

f = np.fft.fft(y)
n = len(f)
f_ = np.concatenate((f[0:(n+1)//2],
                     np.zeros(n//2),
                     [] if n%2 != 0 else f[(n+1)//2:(n+3)//2],
                     np.zeros(n//2),
                     f[(n+3)//2:]))
y_ = np.fft.ifft(f_)
plt.plot(y, 'ro')
plt.plot(y_, 'bo')
plt.show()

rawDescription: getting output ifft at a different resolution

description: Getting output ifft at a different resolution


code:
from gi.repository import Gtk, GLib
import os, signal

class MySpawned(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        self.set_default_size(600,600)

        vb = Gtk.VBox(False, 5)

        self.tw_out = Gtk.TextView()

        sw = Gtk.ScrolledWindow()
        vb.pack_start(sw, True, True, 0)
        sw.add(self.tw_out)

        self.tw_err = Gtk.TextView()

        sw = Gtk.ScrolledWindow()
        vb.pack_start(sw, True, True, 0)
        sw.add(self.tw_err)

        self.progress = Gtk.ProgressBar()
        vb.pack_start(self.progress, False, True, 0)

        bt = Gtk.Button('Run')
        bt.connect('clicked', self.process)
        vb.pack_start(bt, False, False, 0)

        bt = Gtk.Button('Stop')
        bt.connect('clicked', self.kill)
        vb.pack_start(bt, False, False, 0)

        self.add(vb)
        self.set_size_request(200, 300)
        self.connect('delete-event', Gtk.main_quit)
        self.show_all()

    def run(self):
        Gtk.main()

    def update_progress(self, data=None):
        self.progress.pulse()
        return True

    def kill(self, widget, data=None):
        os.kill(self.pid, signal.SIGTERM)

    def process(self, widget, data=None):
        params = ['du', '--si', '/']

        def scroll_to_end(textview):
            i = textview.props.buffer.get_end_iter()
            mark = textview.props.buffer.get_insert()
            textview.props.buffer.place_cursor(i)
            textview.scroll_to_mark(mark, 0.0, True, 0.0, 1.0)

        def write_to_textview(io, condition, tw):
            if condition is GLib.IO_HUP:
                GLib.source_remove(self.source_id_out)
                GLib.source_remove(self.source_id_err)
                return False

            line = io.readline()
            tw.props.buffer.insert_at_cursor(line)
            scroll_to_end(tw)

            while Gtk.events_pending():
                Gtk.main_iteration_do(False)

            return True

        self.pid, stdin, stdout, stderr = GLib.spawn_async(params,
            flags=GLib.SpawnFlags.SEARCH_PATH|GLib.SpawnFlags.DO_NOT_REAP_CHILD,
            standard_output=True,
            standard_error=True)

        self.progress.set_text('Runnig du --si')

        io = GLib.IOChannel(stdout)
        err = GLib.IOChannel(stderr)

        self.source_id_out = io.add_watch(GLib.IO_IN|GLib.IO_HUP,
                                 write_to_textview,
                                 self.tw_out,
                                 priority=GLib.PRIORITY_HIGH)

        self.source_id_err = err.add_watch(GLib.IO_IN|GLib.IO_HUP,
                                 write_to_textview,
                                 self.tw_err,
                                 priority=GLib.PRIORITY_HIGH)

        timeout_id = GLib.timeout_add(100, self.update_progress)

        def closure_func(pid, status, data):
            GLib.spawn_close_pid(pid)
            GLib.source_remove(timeout_id)
            self.progress.set_fraction(0.0)

        GLib.child_watch_add(self.pid, closure_func, None)

if __name__ == '__main__':
    s = MySpawned()
    s.run()

rawDescription: button Stop/Cancel progressBar from subprocess PYGTK

description: Button Stop/Cancel progressBar from subprocess PYGTK


rawDescription: Changing type of python keys

description: Changing type of python keys


code:
def info(request):
    data = render(request, 'info.html')
    response = HttpResponse(data)
    response['X-Frame-Options'] = "ALLOWALL"
    return response

rawDescription: header data render_to_response to include X-Frame-Options ALLOWALL

description: Header data render_to_response to include X-Frame-Options ALLOWALL


code:
class MyApp(App):
    ...
    def on_stop(self):
        # do what you need to here
        value_to_save = self.root.subwidget.value
        # self.root is your root widget - either the
        # widget you return from App.build() or
        # the root widget in your app kv file

rawDescription: How to hide/disable close button or at least catch/override built-in quit() function? (Kivy)

description: Hide/disable close button or at least catch/override built-in quit() function? (Kivy)


code:
import inspect

local_vars = {}

def main():
    global local_vars
    a = 2
    b = 4
    c = a+b
    local_vars = inspect.currentframe().f_locals
    return c

main()

rawDescription: Using Variable Explorer in Spyder (Python) to View Other Namespaces


code:
def parse(self, response):
    """ This function parses a sample response. Some contracts are mingled
    with this docstring.

    @url http://www.amazon.com/s?field-keywords=selfish+gene
    @returns items 1 16
    @returns requests 0 0
    @scrapes Title Author Year Price
    """

rawDescription: Create unit-test for method of scrapy CrawlSpider


code:
from string import ascii_lowercase
ascii_lowercase
list(ascii_lowercase)

rawDescription: Is there a built in list in python or some package that has a list of the alphabet?


code:
""" Setup script for PyPI """
from distutils.core import setup

setup(name='dynamic-dynamodb',
    version='0.3.0-SNAPSHOT',
    license='Apache License, Version 2.0',
    description='Automatic provisioning for AWS DynamoDB tables',
    author='Sebastian Dahlgren',
    author_email='sebastian.dahlgren@gmail.com',
    url='http://sebdah.github.com/dynamic-dynamodb/',
    keywords="dynamodb aws provisioning amazon web services",
    platforms=['Any'],
    packages=['dynamic_dynamodb'],
    scripts=['dynamic-dynamodb'],
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'boto >= 2.6.0'
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: OS Independent',
        'Programming Language :: Python'
    ]
)

rawDescription: setuptools: file dynamic_dynamodb.py (for module dynamic_dynamodb) not found

description: Setuptools: file dynamic_dynamodb.py (for module dynamic_dynamodb) not found


code:
import numpy as np
import matplotlib.pyplot as plt
import random as rd
import math

a=np.zeros((1000,2), dtype=np.float)

def randwalk(x,y):
    theta=2*math.pi*rd.random()
    x+=math.cos(theta);
    y+=math.sin(theta);
    return (x,y)

x, y = 0., 0.
for i in range(1000):
    x, y = randwalk(x,y)
    a[i,:] = x, y

plt.figure()
plt.plot(a[:,0], a[:,1])
plt.show()

rawDescription: Storing intermediate values in a numpy array


code:
import string
keys = string.digits+string.ascii_lowercase
values = range(len(keys))
d = dict(zip(keys,values))

rawDescription: What is the most elegant way to initialize a dictionary consists of chars and digits


code:
from itertools import chain

def rle(seq):
    ret = []
    sentinel = object()
    enum = enumerate(chain(seq,[sentinel]))
    start,last = next(enum)
    for i,c in enum:
        if c != last:
            ret.append((last,i-start))
            start,last = i,c
    return ret

rawDescription: Remove code duplication from RLE pattern, without resorting to Haskell?


rawDescription: Removing redundant symbols from string

description: Removing redundant symbols from string


rawDescription: python get time stamp on file in mm/dd/yyyy format

description: Python get time stamp on file in mm/dd/yyyy format


code:
x = np.concatenate((line1_x, line2_x))
y = np.concatenate((line1_y, line2_y))
order = np.argsort(y)

spline_fit = interp.UnivariateSpline(y[order], x[order])
y_points = np.linspace(515, 1000, 20)

plt.plot(spline_fit(y_points), y_points, 'k--', label='Fit')

rawDescription: Python gradient matching spline

description: Python gradient matching spline


code:
bucket_sizes
N
p = bucket_sizes / float(bucket_sizes.sum())
p
np.random.multinomial(N, p)
np.random.multinomial(N, p)

rawDescription: Divide N elements among M buckets of different sizes proportionally to bucket sizes


code:
# data source
l0 = [{"num": 60, "name": "A"}, {"num": 50, "name": "B"}, {"num": 49, "name": "C"}]

# initialization, length of data source, void data destination,
# start from beginning of data source
ll0, l1, nl = len(l0), [], 0

# the loop is downwards, because we want to match the numbers
# in data source from high to low
for n in range(l0[0]['num'], 0, -1):
    # first test avoids IndexError, second test is your condition
    if nl < ll0 and l0[nl]['num'] == n:
        l1.append([n, l0[nl]])
        # if we had a match, we switch our attention to the next item
        # in data source, hence increment the index in data source
        nl += 1
    else:
        l1.append([n, {}])

# we built the data destination list from top to bottom,
# you want from bottom to top, hence
l1.reverse()

rawDescription: how to search efficiently items in the list?

description: Search efficiently items in the list


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

with open('filetest', 'w') as f1:
    f1.write("This is a line")

with open('filetest', 'r') as f2:
    for line in f2.readlines():
        print(line, end='')

rawDescription: python print statement printing a newline despite a comma

description: Python print statement printing a newline despite a comma


code:
import os, zipfile
from os.path import join
def zipfolder(foldername, filename, includeEmptyDIr=True):
    empty_dirs = []
    zip = zipfile.ZipFile(filename, 'w', zipfile.ZIP_DEFLATED)
    for root, dirs, files in os.walk(foldername):
        empty_dirs.extend([dir for dir in dirs if os.listdir(join(root, dir)) == []])
        for name in files:
            zip.write(join(root ,name))
        if includeEmptyDIr:
            for dir in empty_dirs:
                zif = zipfile.ZipInfo(join(root, dir) + "/")
                zip.writestr(zif, "")
        empty_dirs = []
    zip.close()

if __name__ == "__main__":
    zipfolder('test1/noname/', 'zip.zip')

rawDescription: How do I create a zip file of a file path using Python, including empty directories?

description: Create a zip file of a file path using Python, including empty directories


code:
import itertools
for item in itertools.chain(list1, list2, list3):
    function(item)

rawDescription: How do I make the same iteration for several different lists at the same time in Python

description: Make the same iteration for several different lists at the same time in Python


code:
def button_total(self, cr, uid, ids, context=None):
    tea_worker_line_ids = self.browse(cr, uid, ids[0], context=context).selected_tea_workers_line_ids or []
    total_tea_worker = len(tea_worker_line_ids)
    self.write(cr, uid, ids, {'total_workers': total_tea_worker}, context=context)
    return True

rawDescription: How to get total workers by button?

description: Get total workers by button


code: fn(*args)

rawDescription: Programmatically pass unknown number of parameters in Python


code:
import win32api
VK_MEDIA_PLAY_PAUSE = 0xB3
hwcode = win32api.MapVirtualKey(VK_MEDIA_PLAY_PAUSE, 0)
hwcode
win32api.keybd_event(VK_MEDIA_PLAY_PAUSE, hwcode)

rawDescription: Media Play/Pause Simulation

description: Media Play/Pause Simulation


code:
ghost = Ghost()
ghost.frame('<your frame name>')

g.content  # Your frame content

g.frame()  # ascent back to root frame

rawDescription: How can I get data from iframe with ghost.py?

description: Get data from iframe with ghost.py


code:
async def new_sleep():
    await asyncio.sleep(2)

class Waiting:
    def __await__(self):
        return new_sleep().__await__()

rawDescription: How can I await inside future-like object's __await__?

description: Await inside future-like object's __await__


code:
def is_idle(lat1, lat2):

    if lat1 - lat2 < 0.1:
        return 'idle'
    elif lat1 - lat2 > 0.1:
        return 'active'
    else:
        return 'error'

lats = [1,2,3,4,5,6,7,8,9]

for i in range(len(lats)-1):
    lat1= lats[i]
    lat2 = lats[i+1]
    is_idle(lat1,lat2)

rawDescription: how to apply a function to rows of a table in a loop

description: Apply a function to rows of a table in a loop


code:
def while_version(items):
    i = len(items) - 1
    result = []
    while i >= 0:
        result.append(items[i])
        i -= 1
    return result

rawDescription: Translate Python for loop into a while loop


code:
import wx, time, thread

class MainFrame ( wx.Frame ):

    def __init__( self, parent ):
        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u"Progress Bar Example", pos = wx.DefaultPosition, size = wx.Size( 460,135 ), style = wx.CAPTION|wx.CLOSE_BOX|wx.TAB_TRAVERSAL )

        self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )

        bSizer2 = wx.BoxSizer( wx.VERTICAL )

        self.progress = wx.Gauge( self, wx.ID_ANY, 100, wx.Point( 10,10 ), wx.Size( 400,-1 ), wx.GA_HORIZONTAL|wx.GA_SMOOTH )
        self.progress.SetValue( 0 )
        self.progress.SetForegroundColour( wx.Colour( 255, 255, 255 ) )

        bSizer2.Add( self.progress, 0, wx.ALL, 5 )

        self.start_again = wx.Button( self, wx.ID_ANY, u"START", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer2.Add( self.start_again, 0, wx.ALL, 5 )

        self.SetSizer( bSizer2 )
        self.Layout()

        self.Centre( wx.BOTH )

        # Connect Events
        self.start_again.Bind( wx.EVT_BUTTON, self.run_progreee_bar)

    def __del__( self ):
        pass

    # Virtual event handlers, overide them in your derived class
    def run_progreee_bar( self, event ):
        thread.start_new_thread(self.update_progress_bar, ())

    def update_progress_bar(self):
        self.start_again.Disable()
        self.progress.SetValue( 0 )
        for i in range(101):
            self.progress.SetValue( i )
            self.delay()
        self.start_again.Enable()

    def delay(self):
        time.sleep(0.5)

app  = wx.App()
frame = MainFrame(None)
frame.Show()
app.MainLoop()

rawDescription: wxPython Progress bar crashes and not works as expected

description: WxPython Progress bar crashes and not works as expected


code:
import mock

def mymethod(para1, para2, para3):
    return para1 + para2 + para3

m = mock.Mock(side_effect=lambda *args: args[0])
with mock.patch('__main__.mymethod', m):
    assert mymethod(1, 2, 3) == 1

rawDescription: Get parameters of a mocked method in python


rawDescription: Round pandas datetime index?

description: Round pandas datetime index


code:
def transpose(self, print_matrix=True):
    '''
    Transpose a matrix.
    '''
    C = Z ## creating a new zero matrix
    for i in range(0, self.rows):
        for j in range(0, self.cols):
            C.matrix[i][j] = self.matrix[j][i]

    ## printing the resultant matrix
    if print_matrix:
        C.show()
    return C

rawDescription: Python: How to execute only parts of a function?


code:
sequence = [('item 1',150),('item 2',340),('item 3',794),('item 4',1205,),('item 5',1869),('item 2',3412)]
d = {}

for i,tup in enumerate(sequence):
    item,val = tup
    if d.get(item):
        print("I've seen {} before, it was {} at index {}".format(item,*d.get(item)))
    d[item] = (val, i)

#I've seen item 2 before, it was 340 at index 1

rawDescription: How can I retrieve the previous item of an ordered key/pair collection?

description: Retrieve the previous item of an ordered key/pair collection


rawDescription: convert float value to str without rounding in python3

description: Convert float value to str without rounding in python3


code: consonants = 'bcdfghjklmnpqrstvwxyz'

rawDescription: Python - the fastest, most efficient, simplest way to get consonants


rawDescription: Python - Sorting a dictionary {String Key: List of Strings} by len(value)?


rawDescription: Python - Find non mutual items in two dicts


code:
import os
"walk" in dir(os)

rawDescription: Python check if function exists without try


code: df.apply(lambda x: combine(x['MEETING DATE'], x['MEETING TIME']), axis=1)

rawDescription: Combine date column and time column into datetime column


code:
import tkinter as tk

r = tk.Tk()
r.withdraw()

r.clipboard_clear()
r.clipboard_append('1234')
r.after(10000, lambda: r.destroy())
r.mainloop()

rawDescription: Accessing text copied to clipboard by python


code:
from dateutil.parser import parse
parse("Wed, 18 May 2016 11:21:35 GMT")

rawDescription: Python convert date string to timestamp

description: Python convert date string to timestamp


code:
import subprocess
import time

class foo_class(object):
    def __init__(self):
        pass

    def start(self):
        self.foo = subprocess.Popen(['a daemon service'])

    def stop(self):
        self.foo.kill()
        self.foo.wait() #don't know if this is necessary?

    def restart(self):
        self.start()

foo = foo_class()
foo.start()
time.sleep(5)
foo.stop()

rawDescription: How to kill a subprocess initiated by a different function in the same class

description: Kill a subprocess initiated by a different function in the same class


code:
def rec_walk(dir):
    contents = os.listdir(dir) # read the contents of dir
    for item in contents:      # loop over those contents
        if os.path.isdir(item):
            rec_walk(item)     # recurse on subdirectories
        else:
            print(item)        # do something else with non-directory items

rawDescription: Scanning for files and directories recursively in Python


rawDescription: Python - Validate currency

description: Python - Validate currency


rawDescription: Python: Nested for loops giving undesired output


code: img = cv2.imdecode(numpy.fromstring(request.files['file'].read(), numpy.uint8), cv2.CV_LOAD_IMAGE_UNCHANGED)

rawDescription: Can an uploaded image be loaded directly by cv2?


code:
n = 16
c = c.replace('\n', '').replace('\r', '')
m = [hex(pow(int(c[i:i+n], 16), d, N)).rstrip("L") for i in range(0, len(c), n)]

f = open('new.try', 'w')
f.write(''.join(m))
f.close()

rawDescription: Python code that decrypts encrypted file


code: np.repeat(s.index.values, s.values)

rawDescription: Pandas: inverse of value_counts function


code:
...
# subtract the two datetimes (which gives me a timedelta)
dt = rightNow.date() - lastTweetAt.date()
...

rawDescription: Determining "days" in python when the timedelta.days is less than one


code:
urlpatterns = patterns('',
    (r'^$',index),
    )

rawDescription: How to get Djangos urls.py to look into database and take urls from it? Is that even a good idea?

description: Get Djangos urls.py to look into database and take urls from it? Is that even a good idea


code:
from sympy import *
from sympy.solvers import solve
ca, ra = symbols("ca ra")
eq = -ra + (1.5 * (ca - (ra/2))/(1 + 0.8 * (ca - (ra/2))))
print(eq)
solutions = solve(eq, ra)  #solve equation for ra
print(solutions)
values = [s.replace(ca, 5) for s in solutions]  #get solutions for ca=5

rawDescription: Solving an equation with python

description: Solving an equation with python


code:
@app.route("/uploads", methods=["GET", "POST"])
def upload_handler():
    # Handle the upload here
    pass

rawDescription: How to setup for jQuery-File-Upload? How to implement the upload handler?

description: Setup for jQuery-File-Upload? How to implement the upload handler


rawDescription: '(match_start1)...(match_start2)...(match_end)' find the shortest string match


code: from shared import pkg

rawDescription: importing a package from a subdir or relative path

description: Importing a package from a subdir or relative path


code:
@contextlib.contextmanager
def tempdir(prefix='tmp'):
    """A context manager for creating and then deleting a temporary directory."""
    tmpdir = tempfile.mkdtemp(prefix=prefix)
    try:
        yield tmpdir
    finally:
        shutil.rmtree(tmpdir)

rawDescription: How do you manage a temporary directory such that it is guaranteed to be deleted on program close?

description: Manage a temporary directory such that it is guaranteed to be deleted on program close


code:
parser = etree.XMLParser(strip_cdata=False)
with open(source_filename, "rb") as source:
    tree = etree.parse(source, parser=parser)

rawDescription: LXML kills my CDATA sections

description: LXML kills my CDATA sections


code:
import Tkinter as tk

class FullScreenApp(object):
    def __init__(self, master, **kwargs):
        self.master=master
        pad=3
        self._geom='200x200+0+0'
        master.geometry("{0}x{1}+0+0".format(
            master.winfo_screenwidth()-pad, master.winfo_screenheight()-pad))
        master.bind('<Escape>',self.toggle_geom)
    def toggle_geom(self,event):
        geom=self.master.winfo_geometry()
        print(geom,self._geom)
        self.master.geometry(self._geom)
        self._geom=geom

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

rawDescription: Display fullscreen mode on Tkinter

description: Display fullscreen mode on Tkinter


code:
import numpy as np
minval = np.min(a[np.nonzero(a)])
maxval = np.max(a[np.nonzero(a)])

rawDescription: Find the min/max excluding zeros in a numpy array (or a tuple) in python


code:
for row in cursor:
    print(row)

rawDescription: How to do while() the "pythonic way"

description: Do while() the "pythonic way"


code:
from numpy.random import rand
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

cdict = {'red':   ((0.0, 0.0, 0.0),
                   (0.5, 0.0, 0.0),
                   (1.0, 1.0, 1.0)),
         'blue':  ((0.0, 0.0, 0.0),
                   (1.0, 0.0, 0.0)),
         'green': ((0.0, 0.0, 1.0),
                   (0.5, 0.0, 0.0),
                   (1.0, 0.0, 0.0))}

cmap = mcolors.LinearSegmentedColormap(
'my_colormap', cdict, 100)

ax = plt.subplot(111)
im = ax.imshow(2*rand(20, 20) + 1.5, cmap=cmap)
plt.colorbar(im)
plt.show()

rawDescription: Green to red colormap in matplotlib, centered on the median of the data


code:
import Image, ImageDraw, ImageStat

def gcr(im, percentage):
    '''basic "Gray Component Replacement" function. Returns a CMYK image with
       percentage gray component removed from the CMY channels and put in the
       K channel, ie. for percentage=100, (41, 100, 255, 0) >> (0, 59, 214, 41)'''
    cmyk_im = im.convert('CMYK')
    if not percentage:
        return cmyk_im
    cmyk_im = cmyk_im.split()
    cmyk = []
    for i in xrange(4):
        cmyk.append(cmyk_im[i].load())
    for x in xrange(im.size[0]):
        for y in xrange(im.size[1]):
            gray = min(cmyk[0][x,y], cmyk[1][x,y], cmyk[2][x,y]) * percentage / 100
            for i in xrange(3):
                cmyk[i][x,y] = cmyk[i][x,y] - gray
            cmyk[3][x,y] = gray
    return Image.merge('CMYK', cmyk_im)

def halftone(im, cmyk, sample, scale):
    '''Returns list of half-tone images for cmyk image. sample (pixels),
       determines the sample box size from the original image. The maximum
       output dot diameter is given by sample * scale (which is also the number
       of possible dot sizes). So sample=1 will presevere the original image
       resolution, but scale must be >1 to allow variation in dot size.'''
    cmyk = cmyk.split()
    dots = []
    angle = 0
    for channel in cmyk:
        channel = channel.rotate(angle, expand=1)
        size = channel.size[0]*scale, channel.size[1]*scale
        half_tone = Image.new('L', size)
        draw = ImageDraw.Draw(half_tone)
        for x in xrange(0, channel.size[0], sample):
            for y in xrange(0, channel.size[1], sample):
                box = channel.crop((x, y, x + sample, y + sample))
                stat = ImageStat.Stat(box)
                diameter = (stat.mean[0] / 255)**0.5
                edge = 0.5*(1-diameter)
                x_pos, y_pos = (x+edge)*scale, (y+edge)*scale
                box_edge = sample*diameter*scale
                draw.ellipse((x_pos, y_pos, x_pos + box_edge, y_pos + box_edge), fill=255)
        half_tone = half_tone.rotate(-angle, expand=1)
        width_half, height_half = half_tone.size
        xx=(width_half-im.size[0]*scale) / 2
        yy=(height_half-im.size[1]*scale) / 2
        half_tone = half_tone.crop((xx, yy, xx + im.size[0]*scale, yy + im.size[1]*scale))
        dots.append(half_tone)
        angle += 15
    return dots

im = Image.open("1_tree.jpg")

cmyk = gcr(im, 0)
dots = halftone(im, cmyk, 10, 1)
im.show()
new = Image.merge('CMYK', dots)
new.show()

rawDescription: Halftone Images In Python

description: Halftone Images In Python


code:
#!/usr/bin/env python2

import sqlite3
import csv

def quotify(s):
    return '"' + s.strip().replace('"', '""') + '"'

con = sqlite3.connect("pets.db")

# Examle contents of pets.csv:
# person_name, person_age, pet_name
# Lisa, 8, Snowball I
# Lisa, 8, Snowball II
# Bart, 10, Santa's Little Helper
with open("pets.csv") as pets:
    pets = csv.reader(pets)
    with con:
        names = next(pets)
        names = [name.decode('utf-8') for name in names]
        for name in names:
            con.execute('drop table if exists %s;' % quotify(name))
            con.execute('create table %s (value unique on conflict ignore);'
                        % quotify(name))
        con.execute("drop table if exists master")
        st = "create table master(%s);" % (
            ','.join("%s" % quotify(name) for name in names))
        con.execute(st)
        for row in pets:
            row = [item.decode('utf-8') for item in row]
            rowids = []
            for name, value in zip(names, row):
                rowids.append(
                    con.execute("insert into %s (value) values(?)"
                                % quotify(name),
                                (value.strip(),)).lastrowid)
            st = 'insert into master values(%s)' % (
                ','.join('?' for rowid in rowids))
            con.execute(st, rowids)

# Demonstration, using Simpon's example from question:
from pprint import pprint
st = '''select person_name.value, person_age.value, pet_name.value
          from person_name, person_age, pet_name, master
         where master.person_name = person_name.rowid
           and master.person_age = person_age.rowid
           and master.pet_name = pet_name.rowid;'''

pprint(con.execute(st).fetchall())

rawDescription: Create SQL INSERT Script with python

description: Create SQL INSERT Script with python


code:
# swap a with b
'obama'.replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b')

rawDescription: Python string replace two things at once?


code:
import unittest
import test.test_prog
suite = unittest.TestLoader().loadTestsFromModule(test.test_prog)
unittest.TextTestRunner().run(suite)

rawDescription: Run unittest from Python program via command line option


code:
from datetime import datetime

class MyViewSet(viewsets.ModelViewSet):

    ...

    def retrieve(self, request, timestamp=None):
        queryset = self.get_queryset()
        try:
             parsedtime = datetime.strptime(timestamp, '%Y%m%d%H%M%S')
        except ValueError:
             # incorrect timestamp
             ...
        record = get_object_or_404(queryset, timestamp=parsedtime)
        serializer = self.get_serializer(record)
        return Response(serializer.data)

rawDescription: Django Rest Framework: Custom url pattern for Detail model-viewset with datetime lookup field


code:
test_content = '
param_value1param_value2
'

sel = HtmlXPathSelector(text=test_content)
sel.select('//div/strong[@class="param"]/text()').extract()[0]
sel.select('//div/strong[@class="param"]/text()').extract()[1]

rawDescription: Construct Xpath

description: Construct Xpath


code:
d = {'banana': 3, 'orange': 5, 'apple': 5}
sorted(d.items(), key=lambda x: (-x[1], x[0]))

rawDescription: Python Sorted: Sorting a dictionary by value (DESC) then by key (ASC)


code:
titles=hxs.select('//table[@id="searchresults"]/tbody/tr')
items = []
for titles in titles:
    item['title']=titles.select('.//span[@class="jobTitle"]/a/text()').extract()
    item['link']=titles.select('.//span[@class="jobTitle"]/a/@href').extract()
    item['shifttype']=titles.select('.//span[@class="jobShiftType"]/text()').extract()
    item['location']=titles.select('.//span[@class="jobLocation"]/text()').extract()
    items.append(item)
return items

rawDescription: Scrapy output issue

description: Scrapy output issue


code: print('\n', even_count, ' even numbers total to ', even_sum, sep='')

rawDescription: Python 3.4.1 Print new line

description: Python 3.4.1 Print new line


code:
d={k:c[k] if k in c and c[k]>b[k] else v for k,v in b.items()}
d

rawDescription: Compare the key/values of two dictionaries and put into new dictionary


code:
prog = re.compile('\[([^\]]*)\]\s*\[([^\]]*)\]\s*(.*)')

for mystr in string_list:
    result = prog.match(mystr)
    groups = result.groups()

rawDescription: Split a string of a specific pattern into three parts


code:
out = open("outputfile.txt", "w")

with open("inputfle2.txt", "r") as map:
    map_lines = map.readlines()

with open("inputfile1.txt", "r") as f:
    for line in f:
        for mline in map_lines:
            if line[0:6] in mline:
                out.write(line)

rawDescription: Python: Why won't my loop iterate?

description: Python: Why won't my loop iterate


code:
import struct
fh = open('my_file.dat', 'rb')
s = fh.read(40256)
vals = struct.unpack('iidddddd5025d', s)
dpoints, dloops, dtime, bT, sT, hI, LI, tm = vals[:8]
data = vals[8:]

rawDescription: Reading a Delphi binary file in Python

description: Reading a Delphi binary file in Python


code: ax.plot_date(d, nv, ls='solid', fmt='')

rawDescription: Setting colors using color cycle on date plots using `plot_date()`


code:
for i in list:
    print('bla1')
    print('bla2')

rawDescription: multiple actions in list comprehension python

description: Multiple actions in list comprehension python


code:
from sklearn.decomposition import IncrementalPCA
import csv
import sys
import numpy as np
import pandas as pd

dataset = sys.argv[1]
chunksize_ = 5 * 25000
dimensions = 300

reader = pd.read_csv(dataset, sep = ',', chunksize = chunksize_)
sklearn_pca = IncrementalPCA(n_components=dimensions)
for chunk in reader:
    y = chunk.pop("Y")
    sklearn_pca.partial_fit(chunk)

# Computed mean per feature
mean = sklearn_pca.mean_
# and stddev
stddev = np.sqrt(sklearn_pca.var_)

Xtransformed = None
for chunk in pd.read_csv(dataset, sep = ',', chunksize = chunksize_):
    y = chunk.pop("Y")
    Xchunk = sklearn_pca.transform(chunk)
    if Xtransformed == None:
        Xtransformed = Xchunk
    else:
        Xtransformed = np.vstack((Xtransformed, Xchunk))

rawDescription: Python PCA on Matrix too large to fit into memory


code:
from tkinter import *

root = Tk()

display = Label(root,text="Starting")
displayState = 1
display.pack()

def change():
    global displayState, display

    if displayState == 1:
        display.config(text="I just changed")

    elif displayState == 2:
        display.config(text="I changed again")

    elif displayState == 3:
        display.config(text="I changed once more")

    displayState += 1

button = Button(root,text="Press me",command=change)
button.pack()

root.mainloop()

rawDescription: Tkinter: change text in a label multiple times in a series using a single button


code:
import re
try:
    from htmlentitydefs import name2codepoint
except ImportError:
    # Must be Python 3.x
    from html.entities import name2codepoint
    unichr = chr

name2codepoint = name2codepoint.copy()
name2codepoint['apos']=ord("'")

EntityPattern = re.compile('&(?:#(\d+)|(?:#x([\da-fA-F]+))|([a-zA-Z]+));')

def decodeEntities(s, encoding='utf-8'):
    def unescape(match):
        code = match.group(1)
        if code:
            return unichr(int(code, 10))
        else:
            code = match.group(2)
            if code:
                return unichr(int(code, 16))
            else:
                code = match.group(3)
                if code in name2codepoint:
                    return unichr(name2codepoint[code])
        return match.group(0)

    return EntityPattern.sub(unescape, s.decode(encoding))

someText = decodeEntities(b"Ström")
print(someText)

rawDescription: Replacement of ampersands that are part of a numeric character reference by Python's elementtree


code:
import networkx as nx
from networkx import bipartite
G = nx.path_graph(5) # two parts, [0,2,4],[1,3]
bipartite.projected_graph(G,[0,2,4]).nodes()
bipartite.projected_graph(G,[0,2,3]).nodes()

rawDescription: More number of nodes in bipartite projection than node set


code:
import pyglet, sys, os, time

def animgif_to_ASCII_animation(animated_gif_path):
    # map greyscale to characters
    chars = ('#', '#', '@', '%', '=', '+', '*', ':', '-', '.', ' ')
    clear_console = 'clear' if os.name == 'posix' else 'CLS'

    # load image
    anim = pyglet.image.load_animation(animated_gif_path)

    # Step through forever, frame by frame
    while True:
        for frame in anim.frames:

            # Gets a list of luminance ('L') values of the current frame
            data = frame.image.get_data('L', frame.image.width)

            # Built up the string, by translating luminance values to characters
            outstr = ''
            for (i, pixel) in enumerate(data):
                outstr += chars[(ord(pixel) * (len(chars) - 1)) / 255] + \
                          ('\n' if (i + 1) % frame.image.width == 0 else '')

            # Clear the console
            os.system(clear_console)

            # Write the current frame on stdout and sleep
            sys.stdout.write(outstr)
            sys.stdout.flush()
            time.sleep(0.1)

# run the animation based on some animated gif
animgif_to_ASCII_animation(u'C:\\some_animated_gif.gif')

rawDescription: How to create ASCII animation in a console application using Python 3.x?

description: Create ASCII animation in a console application using Python 3.x


code:
while edges:
    current_edge = edges.pop(0)
    body = {current_edge[0], current_edge[1]}
    i = 0
    while i < len(edges):
        if edges[i][0] in body or edges[i][1] in body:
            body.add(edges[i][0])
            body.add(edges[i][1])
            edges.pop(i) # Edge added, no need to check it again
            i = 0 # Restart the loop
        else:
            i += 1
    bodylist.append(body)

rawDescription: Different result upon shuffling a list

description: Different result upon shuffling a list


code:
def DoRotation(xspan, yspan, RotRad=0):
    """Generate a meshgrid and rotate it by RotRad radians."""

    # Clockwise, 2D rotation matrix
    RotMatrix = np.array([[np.cos(RotRad),  np.sin(RotRad)],
                          [-np.sin(RotRad), np.cos(RotRad)]])

    x, y = np.meshgrid(xspan, yspan)
    return np.einsum('ji, mni -> jmn', RotMatrix, np.dstack([x, y]))

rawDescription: Rotate meshgrid with numpy

description: Rotate meshgrid with numpy


code:
class AbstractBase(object):
    def __repr__(self, indent=2):
        result = self.__class__.__name__ + '\n'
        for k,v in self.__dict__.iteritems():
            if k.startswith('__'):
                continue
            if isinstance(v, AbstractBase):
                vStr = v.__repr__(indent + 2)
            else:
                vStr = str(v)
            result += ' '*indent + k + ': ' + vStr
        result += '\n'
        return result

rawDescription: Useful default __repr__ for nested class instances


code:
import os
import os.path

for (dirpath, dirnames, filenames) in os.walk('C:/My Music/'):
    for idx in range(len(dirnames)):
        newname = dirnames[idx].replace('_', ' ')
        os.rename(os.path.join(dirpath, dirnames[idx]), os.path.join(dirpath, newname))
        dirnames[idx] = newname

rawDescription: Changing folder name in Python

description: Changing folder name in Python


code: input("Press Enter to continue...")

rawDescription: My comand prompt exits right after I test my code


code:
class ConstantFunction(object):
    def __init__(self, constant):
        self.constant = constant
    def __call__(self, t):
        return self.constant

def constant_function(constant):
    return ConstantFunction(constant)

rawDescription: Generate functions without closures in python


code:
import sys, itertools

count = int(next(sys.stdin))
x = 0
for line in itertools.islice(sys.stdin, count):
    x += 1 if '++' in line else -1
print(x)

rawDescription: SyntaxError: unexpected EOF while parsing in Python 3


rawDescription: Python Selenium extract a href based on id value


rawDescription: matplotlib y-axis label on right side

description: Matplotlib y-axis label on right side


code:
def lists():
    list1 = [150, 250, 190, 230]
    list2 = [110, 200, 125, 130]
    return list1,list2

def sumOfLists(list1,list2):
    return sum(list1) + sum(list2)

print(sumOfLists(*lists()))

rawDescription: How to call lists from a function in the main program?

description: Call lists from a function in the main program


code:
answer = 0
while answer < 5:
    answer = int(raw_input("coded by: Narralol\n\n"
    "Pick a task:\n"
    "1) Start Minecraft.exe\n"
    "2) Start Minecraft_Server.jar\n"
    "3) Backup your server\n"
    "4) Copy the backup to your desktop\n"
    "5) Exit\n").strip())
    if answer == 1:
        os.system('D:\Games\Minecraft\Minecraft.exe')
    elif answer == 2:
        os.system('D:\Games\Minecraft\Minecraft_server.jar')
    elif answer == 5:
        break

rawDescription: How to Run a Program in Python.

description: Run a Program in Python.


rawDescription: Interpreting Django .update()

description: Interpreting Django .update()


code:
def _get_content(editor, initial=""):
    from subprocess import call
    from tempfile import NamedTemporaryFile

    # Create the initial temporary file.
    with NamedTemporaryFile(delete=False) as tf:
        tfName = tf.name
        tf.write(initial)

    # Fire up the editor.
    if call([editor, tfName]) != 0:
        return None # Editor died or was killed.

    # Get the modified content.
    with open(tfName).readlines() as result:
        os.remove(tfName)
        return result

rawDescription: Getting data from external program

description: Getting data from external program


code:
sandbox = {}

with open("functions.pickle", "rb") as funcfile:
    while True:
        try:
            code = marshal.load(funcfile)
        except EOFError:
             break
        sandbox[code.co_name] = types.FunctionType(code, sandbox, code.co_name)

rawDescription: How to pickle a python function with its dependencies?

description: Pickle a python function with its dependencies


code:
import glob
import re

#path = 'C:\Doc\version 1\Output*.txt'   # read all source files with this name format
#files=glob.glob(path)

criteria = ['AB', 'CD', 'EF']   # select lines that start with criteria

list_of_files = glob.glob('./Output*.txt')

with open("P_out.txt", "a") as f_out: #use "a" so you can keep the data from the last Output.txt
    for fileName in list_of_files:
        data_list = open( fileName, "r" ).readlines()
        #indenting the below will allow you to search through all files.
        for line in data_list: #Search data_list, not fileName
            for letter in criteria:
                if re.search(letter,line):
                    f_out.writelines('{}\n'.format(line))
                    #I recommend the \n so that the text does not get concatenated when moving from file to file.

#Really? I promise with will not lie to you.
#f_out.close()  # 'with' construction should close files, yet I make sure they close

rawDescription: Python: read multiple source txt files, copy by criteria into 1 output file


code:
text = ["this is a sentence", "so is this one"]
bigrams = [b for l in text for b in zip(l.split(" ")[:-1], l.split(" ")[1:])]
print(bigrams)

rawDescription: Forming Bigrams of words in list of sentences with Python


code:
dist_lines = [{'cost_center': ccdl.analytic_id.code,
               'destination': ccdl.destination_id.code}
              for ccdl in ccdl_rows]

rawDescription: How can a list comprehension do this

description: How can a list comprehension do this


code:
class with_called_attribute:
    def __init__(self, func):
        self.func = func
        self.called = False

    def __call__(self, *args, **kwargs):
        self.called = True
        self.func(*args, **kwargs)

@with_called_attribute
def run_some_thing(*args, **kwargs):
    print("You called with:", *args, **kwargs)

run_some_thing.called
#>>> False

run_some_thing(10)
#>>> You called with: 10

run_some_thing.called
#>>> True

rawDescription: How do I tell whether a function has been called in Python?

description: Tell whether a function has been called in Python


code:
import urllib2

class HTTPNxBasicAuthHandler(urllib2.HTTPBasicAuthHandler):

    def http_error_auth_reqed(self, authreq, host, req, headers):
        # host may be an authority (without userinfo) or a URL with an
        # authority
        # XXX could be multiple headers
        authreq = headers.get(authreq, None)
        if authreq:
            mo = AbstractBasicAuthHandler.rx.search(authreq)
            if mo:
                scheme, realm = mo.groups()
                if scheme.lower() == 'nxbasic':
                    return self.retry_http_basic_auth(host, req, realm)

    def retry_http_basic_auth(self, host, req, realm):
        user, pw = self.passwd.find_user_password(realm, host)
        if pw is not None:
            raw = "%s:%s" % (user, pw)
            auth = 'NxBasic %s' % base64.b64encode(raw).strip()
            if req.headers.get(self.auth_header, None) == auth:
                return None
            req.add_header(self.auth_header, auth)
            return self.parent.open(req)
        else:
            return None

rawDescription: Implementing a custom Python authentication handler


code:
import xlsxwriter
import itertools

data = [{"Master" : [
        {
           "month" : "Jan",
           "Expense" : "50",
           "Income" : "100",
           "Emp" : "1"
        },
        {
           "month" : "Jan",
           "Expense" : "500",
           "Income" : "1000",
           "Emp" : "2"
        },
        {
           "month" : "Feb",
           "Expense" : "50",
           "Income" : "100",
           "Emp" : "1"
        },
        {
           "month" : "Feb",
           "Expense" : "500",
           "Income" : "1000",
           "Emp" : "2"
        },
        {
           "month" : "Mar",
           "Expense" : "50",
           "Income" : "100",
           "Emp" : "2"
        },
        {
           "month" : "Apr",
           "Expense" : "50",
           "Income" : "100",
           "Emp" : "1"
        }
     ]
}]

workbook = xlsxwriter.Workbook('output.xlsx')

# List of required months
months = [ "Jan", "Feb", "Apr" ]

# List of required columns and required order
columns = ['month', 'Expense', 'Income', 'Emp']

for workbook_month in months:
    for data_month, g in itertools.groupby(data[0]['Master'], key=lambda x: x['month']):
        if workbook_month == data_month:
            worksheet = workbook.add_worksheet(workbook_month)
            worksheet.write_row(0, 0, columns)

            for row, entry in enumerate(g, start=1):
                worksheet.write_row(row, 0, [entry[col] for col in columns])

workbook.close()

rawDescription: Create dynamic worksheet variable

description: Create dynamic worksheet variable


code:
RNA = {'G':'C', 'C':'G', 'A':'U', 'T':'A'}
DNA = 'ATGTACATGGGCATAGCCATATA'
translated = ''.join(RNA[i] for i in DNA)
translated

rawDescription: String converter program not working

description: String converter program not working


code:
l = [[1, 'A'], [2, 'B'], [3, 'B'], [4, 'A'], [5, 'C']]
from operator import itemgetter
sorted(l, key=itemgetter(1))

rawDescription: Reorder a Python list of lists according to the second element of embedded lists


rawDescription: PyQt Enable/Disable elements in a QComboBox


code:
from scrapy.exceptions import DropItem

class YourPersonalPipeline(object):
    def process_item(self, item, spider):
        required_fields = [] # your list of required fields
        if all(field in item for field in required_fields):
            return item
        else:
            raise DropItem("your reason")

rawDescription: Scrapy how to ignore items with blank fields using Loader


rawDescription: Is there a "bounding box" function (slice with non-zero values) for a ndarray in NumPy?


code:
import time

def myFunction(limit):
    for i in range(0,limit):
        time.sleep(2)
        yield i*i

for x in myFunction(100):
    print( x )

rawDescription: Return multiple values over time

description: Return multiple values over time


code:
files = glob.glob("\*.jpg")
img_a = cv2.imread(files[0])

for file in files[1:]:

    img_b = cv2.imread(file);

    # do what you need to do with img_a and img_b

    # and then prepare img_a for the next loop
    img_a = img_b

rawDescription: Loading two images at a time in a loop using Python-glob


code:
from tastypie.fields import ForeignKey
from tastypie.resources import ALL_WITH_RELATIONS

class CityResource(ModelResource):
    country = ForeignKey("path.to.api.CountryResource", "country")

    class Meta:
        queryset = City.objects.all()
        resource_name = 'city'
        fields = ['name','id']

        filtering = {
           "country": ALL_WITH_RELATIONS
        }

class CountryResource(ModelResource):
    class Meta:
        queryset = Country.objects.all()
        resource_name = 'country'
        fields = ['name','code2','id']
        filtering = { "id": ALL }

rawDescription: Tastypie - Filtering by related pk

description: Tastypie - Filtering by related pk


code:
import tkinter as tk
languages = ['Mandarin', 'English', 'French']
global counter
counter = 1
class LanguageFamilies(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        global canv, canv_id # IN ORDER TO MAKE THEM ACCESSIBLE TO OnDouble EVENT HANDLER
        canv = tk.Canvas(self, width=675, height=530, bg="white", relief="sunken")
        canv.config(scrollregion=(0,0,300,650), highlightthickness=0)
        canv.pack(side="right", expand=True, fill="both")

        # Create scroll bar
        sbar = tk.Scrollbar(self)
        canv.config(yscrollcommand=sbar.set)
        sbar.config(command=canv.yview)
        sbar.pack(side="right", fill="both")

        # Create Scroll List
        lstbox = tk.Listbox(self, width=240, height=530, relief="sunken", font="Courier")
        lst_scrollbar = tk.Scrollbar(self)
        lstbox.config(yscrollcommand=lst_scrollbar.set)
        lst_scrollbar.config(command=lstbox.yview)
        lstbox.pack(side="left", expand=True, fill="both")
        lst_scrollbar.pack(side="right", fill="both")
        lstbox.bind("<Double-Button-1>", self.OnDouble)

        # Add items to the lstbox
        i = 0
        while i < len(languages):
            lstbox.insert(i, languages[i])
            i += 1

        # Create a text inside canvas
        global textmatter
        textmatter = tk.Text(canv) # THE TEXT SHOULD BE PRINTED ON THE CANVAS
        textmatter.insert("end", "Double-click on a language on the left to view information.")
        textmatter.pack()

    #Binding Handler, ONE INDENTATION LEVEL IS REMOVED AS PER BRYAN'S SUGGESTION
    def OnDouble(self, event):
        global counter
        self.widget = event.widget
        selection = self.widget.curselection()
        content = self.widget.get(selection[0])
        if counter == 1:
            textmatter.delete(1.0, "end") # CLEAR THE TEXT WHICH IS DISPLAYED AT FIRST RUNNING
            textmatter.insert("end", content)
            counter += 1 #ONE ITEM HAS BEEN SELECTED AND PRINTED SUCCESSFULLY
        elif counter > 1:
            textmatter.delete(1.0, "end")
            textmatter.insert("end", content)
            counter = 1 # RESET THE COUNTER SO THAT NEXT SELECTED ITEM DISPLAYS PROPERLY

if __name__ == "__main__":
    root = tk.Tk()
    root.geometry("930x530")
    root.title("Language Families")
    LanguageFamilies(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: How to display text of listbox items in the canvas with Python3x tkiner?

description: Display text of listbox items in the canvas with Python3x tkiner


code:
file = open("file.txt", "w")
while True:
    file.write( DATA )
    flle.flush()

rawDescription: Save to Text File from Infinite While Loop


code:
sys.path.append('/path/to')
import lib

rawDescription: Include Python library at path?

description: Include Python library at path


code:
s = StringIO.StringIO()
window.save(s, "jpg")
encodedWindow = base64.b64encode(s.getvalue())

rawDescription: Get Binary Representation of PIL Image Without Saving


code:
class projet(object):
    def __init__(self):
        self.valCouche = ''

    def nameCouche(self):
        valLissage = float(ui.valLissage.displayText())
        return (valLissage)

    def choixTraitement(self):
        ui.okLissage.clicked.connect(p.goLissage)

    def goLissage(self, valCouche):
        if ui.chkboxLissage.isChecked():
            self.valCouche = self.nameCouche()
            print(self.valCouche) # result is False
            os.system(r'"C:\Program Files\FME\fme.exe" D:\Stelios\..... --MAX_NUM_POINTS {0}'.format(self.valCouche))

rawDescription: Difficulties with re-using a variable

description: Difficulties with re-using a variable


rawDescription: Matplotlib: plotting transparent histogram with non transparent edge


code:
class Tree():
  def __init__(self):
    self.root = None
    self.nodes = {}
    self.end_arcs = {}

class Arc():
  def __init__(self,start,end,data={}):
    self.start = start
    self.end = end
    self.data = data

  def __str__(self):
    return "%s-%s" % (self.start.token, self.end.token)

class Node():
  def __init__(self,token,data={}):
    self.token = str(token)
    #self.state = self.OPEN
    self.data = data

n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n5 = Node(5)

t = Tree()
t.root = n1
t.nodes = [n1,n2,n3,n4,n5]

a1 = Arc(n1,n2)
a2 = Arc(n2,n3)
a3 = Arc(n2,n4)
a4 = Arc(n1,n5)

print(a1)  # 1-2
# "Rename" Nodes
n1.token = 101
n2.token = 102
print(a1)  # 101-102

rawDescription: Python: building a tree with data in nodes and arcs


code:
for line in sys.stdin:
    myfloats = [float(x) for x in line.split()]

rawDescription: Put integers from stdin in list

description: Put integers from stdin in list


code:
def xml():
    with open('config\\' + productLine + '.xml','r') as f:
        return f.read()

def table():
     xmlfile = xml()
     parsexml(xmlfile)

rawDescription: global variable usage

description: Global variable usage


code:
class MySerializer(serializers.Serializer):
    id = serializers.ReadOnlyField()
    field1 = serializers.ReadOnlyField()
    field2 = serializers.ReadOnlyField()

    def to_representation(self, data):
        res = super(MySerializer, self).to_representation(data)
        return {res['id']: res}
        # or you can fetch the id by data directly
        # return {str(data.id): res}

rawDescription: Return list of objects as dictionary with keys as the objects id with django rest framerwork


code:
def reshape(thelist, rows,cols):
    parent_list = []
    count = 0
    for j in range(rows):
        new_list = []
        for i in range(cols):
            new_list.append(thelist[count])
            count+=1
        parent_list.append(new_list)
    return parent_list

rawDescription: reshape 2d list

description: Reshape 2d list


code:
import threading
import tkinter
import time

class RepeatExecute(object):
    def __init__(self,master,t=2000):
        self.master=master
        self.time=t

    def go(self):
        self.GO = True
        self.call_self()

    def call_self(self):
        if self.GO is True:
            t = self.time
            print(time.time())
            thrd = threading.Thread(target=self.slow_execute)
            thrd.start()
            self.master.after(t,self.call_self)

    def set_time(self,t):
        self.time=t

    def stop(self):
        self.GO = False

    def slow_execute(self):
        time.sleep(1.0)
        if self.GO is True:
            print('Halfway')

    def active(self):
        print('Active')

if __name__=='__main__':
    root =tkinter.Tk()
    RE = RepeatExecute(root,t=2000)
    btn1 = tkinter.Button(root,text='Start',command=RE.go)
    btn1.grid()
    btn2 = tkinter.Button(root,text='Stop',command=RE.stop)
    btn2.grid()
    btn3 = tkinter.Button(root,text='ACTIVE!',command=RE.active)
    btn3.grid()
    root.mainloop()

rawDescription: Run task repeatedly every x minutes

description: Run task repeatedly every x minutes


first_name: John

last_name: Lennon

first_name: Paul

last_name: McCartney

rawDescription: Good ways to import data into Django

description: Good ways to import data into Django


code:
def getProperty(self,x, *key):
    key = (x,)+key
    return {k:self.__properties[k] for k in key if k in self.__properties}

rawDescription: Combine single and multi argument variables in a function call for Python


code:
import json

s = '''{ "account_balance": 0, "cards": { "count": 1, "data": [ { "address_city": null, "address_country": null, "address_line1": null, "address_line1_check": null, "address_line2": null, "address_state": null, "address_zip": null, "address_zip_check": null, "country": "US", "customer": "cus_2kZQDsySSBFBb3", "cvc_check": null, "exp_month": 5, "exp_year": 2015, "fingerprint": "Nf1jHB21DkK6brg6", "id": "card_102kZQ2wq4yXwSPaT66QP0ho", "last4": "4242", "name": null, "object": "card", "type": "Visa" } ], "object": "list", "url": "/v1/customers/cus_2kZQDsySSBFBb3/cards" }, "created": 1381729976, "default_card": "card_102kZQ2wq4yXwSPaT66QP0ho", "delinquent": false, "description": "rohit.fantasy@yahoo.com", "discount": null, "email": null, "id": "cus_2kZQDsySSBFBb3", "livemode": false, "metadata": {}, "object": "customer", "subscription": null }'''

parsedJson = json.loads(s)

country = parsedJson['cards']['data'][0]['country']

rawDescription: Retrive fields from json Python?

description: Retrive fields from json Python


code: subdict = dict((k, v) for k, v in myDict.iteritems() if v.field2 >= 2)

rawDescription: Python: Get values (objects) from a dictionary of objects in which one of the object's field matches a value (or condition)


code: print(', '.join(datetime.datetime.strftime(item, '%Y%m%d') if type(item) == datetime.datetime else item for item in row))

rawDescription: How to format the datetime object in list with strftime while leaving following numbers unaffected

description: Format the datetime object in list with strftime while leaving following numbers unaffected


code:
import matplotlib.pyplot as plt

ax = plt.subplot(1, 1, 1)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.set_xticks(range(-5, 6))
ax.set_yticks(range(-5, 6))
ax.set_xlim((-5.5, 5.5))
ax.set_ylim((-5.5, 5.5))
ax.grid()

plt.show()

rawDescription: Drawing rectangular grid using matplotlib


code:
HEIGHT_FILE = "/Users/battledrum/Desktop/review2.txt"
TIME_FILE   = "/Users/battledrum/Desktop/review3.txt"
OUTPUT_FILE = "/Users/battledrum/Desktop/HeightVStime.txt"

def main():
    # load data pairs
    with open(HEIGHT_FILE) as hf, open(TIME_FILE) as tf:
        hts = [(height.strip(), time.strip()) for height,time in zip(hf, tf)]
    # write output
    with open(OUTPUT_FILE, "w") as outf:
        lines = ("{}\t{}".format(h, t) for h,t in hts)
        outf.write("\n".join(lines))
    print("{} lines written".format(len(hts)))

if __name__=="__main__":
    main()

rawDescription: Spacing Two Things On The Same Line Then Writing To File


code:
pattern = re.compile(".*stop\s+(\w+\s+){0,10}mail(?!(\s+stop|(.*mail stop))).*")
print(pattern.search("please stop the mail, I want the mail to stop"))
print(pattern.search("please stop the mail stop"))
print(pattern.search("please stop the mail, and I want the mail stop"))

rawDescription: python regex negative lookahead assertion

description: Python regex negative lookahead assertion


rawDescription: Python: Formatting text to specific column


code:
a = np.array(list_a)
b = np.array(list_b)
list_c = np.setdiff1d(b, a).tolist()

rawDescription: Pythonic way to find elementa of a python list that are not contained in another python list


code:
myKey = db.Key.from_path('MyModel', 'mykeyvalue')
rec = db.get(myKey)

rec.MyProperty = 'this is a new value'
rec.put()

rawDescription: update an entity in datastore app engine

description: Update an entity in datastore app engine


code:
newrows = list()
for fl in infiles:
    with open(fl, 'rb') as csvin:
        reader = csv.reader(csvin, delimiter=',')
        reader.next() # skip header
        for row in reader:
            sld = gettld(row[urlcolumn])
            tld = psl.get_public_suffix(row[urlcolumn])
            newrows.append([sld, tld] + row[1:]) # row[1:] is everything but the first

with open(outfile, 'wb') as csvout:
    wtr = csv.writer(csvout, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    wtr.writerow(["TLD", "SLD", "Registrar", "Host", "ASN"]) # write header
    wtr.writerows(newrows)

rawDescription: Using writerow from csv module to write columns starting after the first?


code:
outlist=[]
added_keys = set()

for row in parsed_in:
    # We use tuples because they are hashable
    lookup = tuple(row[:3])
    if lookup not in added_keys:
        outlist.append(row)
        added_keys.add(lookup)

rawDescription: Remove duplicate entries in list using python


code:
my_list = ['Hello. World', 'Big.Big.World']
[x.lower().replace('.', '') for x in my_list]

rawDescription: Multiple list comprehension actions in a single line


code:
def foo():
    """
    extending one list by another end then remove duplicates by making set
    """
    l1 = range(200)
    l2 = range(150, 250)
    l1.extend(l2)
    set(l1)

def bar():
    """
    checking if element is on one list end adding it only if not
    """
    l1 = range(200)
    l2 = range(150, 250)
    for elem in l2:
            if elem not in l1:
                    l1.append(elem)

def baz():
    """
    making sets from both lists and then union from them
    """
    l1 = range(200)
    l2 = range(150, 250)
    set(l1) | set(l2)

from timeit import Timer
Timer(foo).timeit(10000)
Timer(bar).timeit(10000)
Timer(baz).timeit(10000)

rawDescription: Is it faster to union sets or check the whole list for a duplicate?


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

fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111)
ax.set_title("X vs Y AVG",fontsize=14)
ax.set_xlabel("XAVG",fontsize=12)
ax.set_ylabel("YAVG",fontsize=12)
ax.grid(True,linestyle='-',color='0.75')
x = np.random.random(30)
y = np.random.random(30)
z = np.random.random(30)

# scatter with colormap mapping to z value
ax.scatter(x,y,s=20,c=z, marker = 'o', cmap = cm.jet );

plt.show()

rawDescription: How to modify 2d Scatterplot to display color based off third array in csv file?

description: Modify 2d Scatterplot to display color based off third array in csv file


code: rowList = [column for column in [row for row in yourListStore]]

rawDescription: How can I convert a gtk.ListStore to list?

description: Convert a gtk.ListStore to list


code:
import json

with open('some_text_file.txt') as txtfile:
    data = {'filedata': txtfile.read()}

json_data = json.dumps(data)

rawDescription: Include text file in JSON

description: Include text file in JSON


code:
f = open('boo.txt')
lines = [line for line in f]
f.close()
import random
selectedline = random.choice(lines)
print (selectedline)

rawDescription: I/O Reading from a file

description: I/O Reading from a file


code:
import matplotlib.pyplot as plt

def main():
    fig = plt.figure()
    plt.axis([0, 10, 0, 10])

    t = "This is a really long string that I'd rather have wrapped so that it"\
    " doesn't go outside of the figure, but if it's long enough it will go"\
    " off the top or bottom!"
    plt.text(4, 1, t, ha='left', rotation=15)
    plt.text(5, 3.5, t, ha='right', rotation=-15)
    plt.text(5, 10, t, fontsize=18, ha='center', va='top')
    plt.text(3, 0, t, family='serif', style='italic', ha='right')
    plt.title("This is a really long title that I want to have wrapped so it"\
             " does not go outside the figure boundaries", ha='center')

    # Now make the text auto-wrap...
    fig.canvas.mpl_connect('draw_event', on_draw)
    plt.show()

def on_draw(event):
    """Auto-wraps all text objects in a figure at draw-time"""
    import matplotlib as mpl
    fig = event.canvas.figure

    # Cycle through all artists in all the axes in the figure
    for ax in fig.axes:
        for artist in ax.get_children():
            # If it's a text artist, wrap it...
            if isinstance(artist, mpl.text.Text):
                autowrap_text(artist, event.renderer)

    # Temporarily disconnect any callbacks to the draw event...
    # (To avoid recursion)
    func_handles = fig.canvas.callbacks.callbacks[event.name]
    fig.canvas.callbacks.callbacks[event.name] = {}
    # Re-draw the figure..
    fig.canvas.draw()
    # Reset the draw event callbacks
    fig.canvas.callbacks.callbacks[event.name] = func_handles

def autowrap_text(textobj, renderer):
    """Wraps the given matplotlib text object so that it exceed the boundaries
    of the axis it is plotted in."""
    import textwrap
    # Get the starting position of the text in pixels...
    x0, y0 = textobj.get_transform().transform(textobj.get_position())
    # Get the extents of the current axis in pixels...
    clip = textobj.get_axes().get_window_extent()
    # Set the text to rotate about the left edge (doesn't make sense otherwise)
    textobj.set_rotation_mode('anchor')

    # Get the amount of space in the direction of rotation to the left and
    # right of x0, y0 (left and right are relative to the rotation, as well)
    rotation = textobj.get_rotation()
    right_space = min_dist_inside((x0, y0), rotation, clip)
    left_space = min_dist_inside((x0, y0), rotation - 180, clip)

    # Use either the left or right distance depending on the horiz alignment.
    alignment = textobj.get_horizontalalignment()
    if alignment is 'left':
        new_width = right_space
    elif alignment is 'right':
        new_width = left_space
    else:
        new_width = 2 * min(left_space, right_space)

    # Estimate the width of the new size in characters...
    aspect_ratio = 0.5 # This varies with the font!!
    fontsize = textobj.get_size()
    pixels_per_char = aspect_ratio * renderer.points_to_pixels(fontsize)

    # If wrap_width is < 1, just make it 1 character
    wrap_width = max(1, new_width // pixels_per_char)
    try:
        wrapped_text = textwrap.fill(textobj.get_text(), wrap_width)
    except TypeError:
        # This appears to be a single word
        wrapped_text = textobj.get_text()
    textobj.set_text(wrapped_text)

def min_dist_inside(point, rotation, box):
    """Gets the space in a given direction from "point" to the boundaries of
    "box" (where box is an object with x0, y0, x1, & y1 attributes, point is a
    tuple of x,y, and rotation is the angle in degrees)"""
    from math import sin, cos, radians
    x0, y0 = point
    rotation = radians(rotation)
    distances = []
    threshold = 0.0001
    if cos(rotation) > threshold:
        # Intersects the right axis
        distances.append((box.x1 - x0) / cos(rotation))
    if cos(rotation) < -threshold:
        # Intersects the left axis
        distances.append((box.x0 - x0) / cos(rotation))
    if sin(rotation) > threshold:
        # Intersects the top axis
        distances.append((box.y1 - y0) / sin(rotation))
    if sin(rotation) < -threshold:
        # Intersects the bottom axis
        distances.append((box.y0 - y0) / sin(rotation))
    return min(distances)

if __name__ == '__main__':
    main()

rawDescription: Text box with line wrapping in matplotlib?


code:
def bigger(x, y):
    if x > y:
        # when x>y, x will be returned and 'return y' in the last line will not be executed.
        return x
    # only if x<y, this line will be executed.
    return y

rawDescription: Why does this Python function only have one output?


code:
class CarSerializer(serializers.ModelSerializer):

    speed = serializers.SerializerMethodField()

    def get_speed(self, obj):
        if obj.speed == 0:
            return "slow"
        else:
            return "fast"

    class Meta:
        model = Car
        fields = ('name', 'speed')

rawDescription: Django REST -- How to "modify" value before returning the REST response?


code:
xsd = lxml.etree.parse('http://xmlgw.companieshouse.gov.uk/v2-1/schema/Egov_ch-v2-0.xsd')
newimport = lxml.etree.Element('{http://www.w3.org/2001/XMLSchema}import',
    namespace="http://xmlgw.companieshouse.gov.uk",
    schemaLocation="http://xmlgw.companieshouse.gov.uk/v1-1/schema/forms/CompanyIncorporation-v1-2.xsd")
xsd.getroot().append(newimport)

validator = lxml.etree.XMLSchema(xsd)

rawDescription: Validate with three xml schemas as one combined schema in lxml?


rawDescription: Python str.format - Get (only) the sign of a number?


rawDescription: Numpy index slice without losing dimension information


code:
from selenium.webdriver import ActionChains

actions = ActionChains(driver)
actions.move_to_element(element_to_click).click_and_hold(element_to_click).perform()

rawDescription: How do I properly click an element in Selenium with Python?

description: Properly click an element in Selenium with Python


code:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Firefox()
example_menu = driver.find_element_by_id('m_example')
example_menu.click()
# Wait for the "Example Choice" choice to appear
choice_present = expected_conditions.presence_of_element_located((By.LINK_TEXT, 'Example Choice'))
WebDriverWait(driver, 5).until(choice_present)
# Use an action chain to move to the "Example Choice" but click on the
# Milonic menu link
example_choice = driver.find_element_by_link_text('Example Choice')
mmlink1 = driver.find_element_by_id('mmlink1')
action_chain = ActionChains(driver)
action_chain.move_to_element(example_choice)
action_chain.click(mmlink1)
action_chain.perform()

rawDescription: Milonic Menu: Element is not clickable at point. Other element would receive the click


code:
with open("/tmp/out.txt", "w") as o:
    for k in range(len(energy)):
        s = "%12.4e %12.4e " %(energy[k], spectra[0][k])
        for j in range(1,spectra.shape[0]):
            s += "%12.4 " % spectra[j][k]
        o.write(s)

rawDescription: String Output in a data file

description: String Output in a data file


code: mydata['var'].plot(kind='barh', linewidth=0, width=.9, edgecolor=None)

rawDescription: Remove frame from plot

description: Remove frame from plot


code:
from time import sleep
for countdown in range(10,0,-1):
  print(countdown)
  sleep(1)

rawDescription: Python timer not working in real time

description: Python timer not working in real time


code:
pyro_ns_object = Pyro.naming.NameServerStarter()
pyro_ns = threading.Thread(name='Pyro Name Server', target=self.__Pyro_NameServer, args=(pyro_ns_object,))
pyro_ns.setDaemon(True)
self.__logger.debug('start thread def self.__Pyro_NameServer')
pyro_ns.start()

while True:
    if pyro_ns_object.waitUntilStarted(timeout=0.1):
        break
    else:
        self.__logger.debug('waiting pyro-ns')

def __Pyro_NameServer(self, pyro_ns_object):

    try:
        self.__logger.debug('def __Pyro_NameServer')

        self.__logger.debug('starting pyro-ns')
        pyro_ns_object.start()

    except Exception as e:
        self.__logger.error('%s' % str(e))
        raise e

rawDescription: subprocess.call('pyro-ns') sync with threading.Lock

description: Subprocess.call('pyro-ns') sync with threading.Lock


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

def figure():
    fig = plt.figure(figsize=(8,6))
    axes = fig.gca(projection='3d')
    x = np.linspace(-1.5, 1.5, 100)
    y = np.linspace(-1.5, 1.5, 100)
    x, y = np.meshgrid(x, y)

    f = lambda x, y: 1/np.log(y - (x-1)**0.5)
    axes.plot_wireframe(x, y, f(x, y))
    axes.set_xlim(1,1.5)
    axes.set_ylim(0,1.5)

figure()

rawDescription: Plotting surface - enhacing the output

description: Plotting surface - enhacing the output


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
import matplotlib

npol, nvrts = 200000, 5
cnts = 100 * (np.random.random((npol,2)) - 0.5)
offs = 10 * (np.random.random((nvrts,npol,2)) - 0.5)
vrts = cnts + offs
vrts = np.swapaxes(vrts, 0, 1)
z = np.random.random(npol) * 500

fig, ax = plt.subplots()
coll = PolyCollection(vrts, array=z, cmap=matplotlib.cm.jet)
ax.add_collection(coll)
ax.autoscale()
plt.show()

rawDescription: matplotlib: efficient way to create large number of Patch objects

description: Matplotlib: efficient way to create large number of Patch objects


code:
for x in range(len('ACT')):
    if "CATTCG".find('ACT'[x:]) > -1 :
            print("CATTCG".find('ACT'[x:]))
            print("Match found for " + 'ACT'[x:])

rawDescription: how can i search for common elements in two integers with while loop

description: Search for common elements in two integers with while loop


code:
def sample_addition(num1=1, num2=2):
    """adding 2 numbers as an example

    this function will add 2 numbers in case of failre it will raise an exception

    @param num1: first number
    @type num1: float
    @param num2: second number
    @type num2: float
    @return: addition result
    @rtype: float
    """

return num1 + num2

rawDescription: Sphinx autofunction generate python docstring without newlines


code:
DETACHED_PROCESS = 0x00000008
pid = subprocess.Popen(["rv", rvFile, '-nc'], creationflags=DETACHED_PROCESS, shell=True).pid
raw_input("= Opened file")

rawDescription: Start another program and leave it running when the script ends


code: from VAWomensHealth.index import app as application

rawDescription: Changes to Flask index.py not loading

description: Changes to Flask index.py not loading


code:
import concurrent.futures
import time
import datetime

max_numbers = [10000000, 10000000, 10000000, 10000000, 10000000]

class Task:
    def __init__(self, max_number):
        self.max_number = max_number
        self.interrupt_requested = False

    def __call__(self):
        print("Started:", datetime.datetime.now(), self.max_number)
        last_number = 0;
        for i in xrange(1, self.max_number + 1):
            if self.interrupt_requested:
                print("Interrupted at", i)
                break
            last_number = i * i
        print("Reached the end")
        return last_number

    def interrupt(self):
        self.interrupt_requested = True

def main():
    with concurrent.futures.ThreadPoolExecutor(max_workers=len(max_numbers)) as executor:
        tasks = [Task(num) for num in max_numbers]
        for task, future in [(i, executor.submit(i)) for i in tasks]:
            try:
                print(future.result(timeout=1))
            except concurrent.futures.TimeoutError:
                print("this took too long...")
                task.interrupt()

if __name__ == '__main__':
    main()

rawDescription: How to use concurrent.futures with timeouts?

description: Use concurrent.futures with timeouts


code:
source
import matplotlib
# see http://matplotlib.org/faq/usage_faq.html#what-is-a-backend
matplotlib.use('Svg')

import os
import matplotlib.pyplot as plt

x=[0,1,2,3,4]
y=[0,1,4,9,16]
plt.plot(x,y)
plt.savefig('plot.svg')
os.system('feh plot.svg')       # or "eog" for Gnome

rawDescription: matplotlib plot creation very slow on a headless server

description: Matplotlib plot creation very slow on a headless server


code:
import csv

import lxml.etree

x = u'''<!-- MoneyMate (tm) XMLPerfs Application version 1.0.1.1 - Copyright 2000 MoneyMate Limited. All Rights Reserved. MoneyMate -->
<!-- Discrete Perfs for 180 periods for Monthly frequency -->
<MONEYMATE_XML_FEED xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://mmia2.moneymate.com/xml/MoneyMateComplete.xsd" version="1.0" calcCurrency="SEK">
    <TYPES>
        <TYPE typeCountry="SE" typeId="85" typeName="string" calcToDate="2013-07-16">
            <COMPANIES>
                <COMPANY companyId="25000068" companyName="string"/>
                <CATEGORIES>
                    <CATEGORY categoryId="1101" categoryName="Aktie -- Asien">
                        <FUNDS>
                            <FUND fundId="6201" fundName="string" fundCurrency="GBP" fundCompanyId="25000068">
                                <PERFORMANCES>
                                    <MONTHLYPERFS>
                                        <PERFORMANCEMONTH perfEndMonth="2006-05-31" perfMonth="-0.087670"/>
                                    </MONTHLYPERFS>
                                </PERFORMANCES>
                            </FUND>
                        </FUNDS>
                    </CATEGORY>
                    <CATEGORY categoryId="13" categoryName="Rntefonder">
                        <FUNDS></FUNDS>
                    </CATEGORY>
                </CATEGORIES>
            </COMPANIES>
        </TYPE>
    </TYPES>
</MONEYMATE_XML_FEED>
'''

with open('output.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow(('fundid', 'fundName', 'fundCurrency', 'fundCompanyId', 'perfEndMonth', 'perfMonth'))
    root = lxml.etree.fromstring(x)
    for fund in root.iter('FUND'):
        perf = fund.find('.//PERFORMANCEMONTH')
        row = fund.get('fundId'), fund.get('fundName'), fund.get('fundCurrency'), fund.get('fundCompanyId'), perf.get('perfEndMonth'), perf.get('perfMonth')
        writer.writerow(row)

rawDescription: Python XML parsing example

description: Python XML parsing example


code:
list1.sort()
list2.sort()

results = []
try:
    iter1 = iter(list1)
    iter2 = iter(list2)
    i = iter1.next()
    j = iter2.next()
    while True:
        if i[0] == j[0]:
            results.append((i[0], i[1], j[1]))
            i = iter1.next()
            j = iter2.next()
        elif i[0] < j[0]:
            i = iter1.next()
        else:
            j = iter2.next()
except StopIteration:
    pass

rawDescription: list of common first element in tuple of list of tuples

description: List of common first element in tuple of list of tuples


code:
def check_exists_by_xpath(xpath):
    try:
        driver.find_element_by_xpath(xpath)
    except NoSuchElementException:
        driver.save_screenshot('screenshots/screenie.png')
        return False
    return True

rawDescription: Python selenium save screenshot in newly created folder


code:
CTemp = str(12.34) #set for testing
text = "The temp is: "+CTemp

msg = MIMEText(text)

rawDescription: Send an email in Python and include a vaiable in the subject line


rawDescription: How to write a pandas Series to CSV as a row, not as a column?

description: Write a pandas Series to CSV as a row, not as a column


rawDescription: Search a list and split

description: Search a list and split


rawDescription: Acces data points scikit KNNR

description: Acces data points scikit KNNR


code:
import numpy as np

def splitPerc(l, perc):
    splits = np.cumsum(perc)/100.
    if splits[-1] != 1:
        raise ValueError("percents don't add up to 100")
    # split doesn't need last percent, it will just take what is left
    return np.split(l, splits[:-1]*len(l))

list = np.arange(100)
percents = np.array([25, 10, 15,  5,  5,  5, 10, 25])
# 100 elements -> lengths of sublists should equal their percents
assert all(percents == map(len, splitPerc(list, percents)))

rawDescription: Partition a python list by percentage

description: Partition a python list by percentage


code:
result = dict(d2)
for k in d1:
    if k in result:
        result[k] = (result[k] + d1[k]) / 2.0
    else:
        result[k] = d1[k]

rawDescription: What's the most pythonic way to merge 2 dictionaries, but make the values the average values?


code:
import tkinter
tkinter.Text.focus is tkinter.Text.focus_set # Same function object
help(tkinter.Text.focus)

rawDescription: What is the difference between focus and focus_set methods?


code:
def normalize(name):
    name_parts = name.replace("-", " ").split()
    return " ".join(sorted(name_parts)).lower()

rawDescription: Programmatically figuring out if translated names are equivalent


code:
app = Flask(__name__)
app.config.from_pyfile('base')
app.config.from_envvar('YOURAPPLICATION_SETTINGS')

rawDescription: How to create test database with Flask-Testing

description: Create test database with Flask-Testing


code:
from twisted.internet import reactor
from twisted.web.client import Agent
from twisted.internet.defer import inlineCallbacks
from twisted.trial import unittest
from twisted.web.http_headers import Headers
from twisted.internet.error import DNSLookupError

class SomeTestCase(unittest.TestCase):
    @inlineCallbacks
    def test_smth(self):
        ag = Agent(reactor)
        response = yield ag.request('GET', 'http://example.com/', Headers({'User-Agent': ['Twisted Web Client Example']}), None)
        self.assertEquals(response.code, 200)

    @inlineCallbacks
    def test_exception(self):
        ag = Agent(reactor)
        try:
            yield ag.request('GET', 'http://exampleeee.com/', Headers({'User-Agent': ['Twisted Web Client Example']}), None)
        except DNSLookupError:
            pass
        else:
            self.fail()

rawDescription: How can I write tests for code using twisted.web.client.Agent and its subclasses?

description: Write tests for code using twisted.web.client.Agent and its subclasses


code:
data = bytearray([0])
i, count = 1, 4
data += bytearray((i,)) * count
data

rawDescription: How can I append multiple copies of a value to a Python bytearray?

description: Append multiple copies of a value to a Python bytearray


code:
import struct
struct.unpack('<I', 'efgh')

rawDescription: pointer typecasting like c in python

description: Pointer typecasting like c in python


code:
class User:
    STATUS_INACTIVE = 'Inactive'
    STATUS_ACTIVE = 'Active'
    STATUS_PENDING = 'Pending'
    STATUS_BANNED = 'Banned'

    def __init__(self):
        self.status = User.STATUS_ACTIVE

rawDescription: Using classes to keep predefined strings


code:
import re

if re.match('[0-9]{4}-[0-9a-z]{7}', '3256-10wyput'):
    return True

rawDescription: If statement for regex in string

description: If statement for regex in string


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

fig = plt.figure()
ax = fig.add_subplot(111)
# a plot
t = np.linspace(0,2*np.pi,1000)
ax.plot(t * np.sin(t), t * np.cos(t), 'w', linewidth=3)
ax.plot(t * np.sin(t), t * np.cos(t), 'k', linewidth=1)

# create a  background image
X = np.linspace(0, np.pi, 100)
img = np.sin(X[:,None] + X[None,:])

# show the background image
x0,x1 = ax.get_xlim()
y0,y1 = ax.get_ylim()
ax.imshow(img, extent=[x0, x1, y0, y1], aspect='auto')

fig.savefig('/tmp/test.png')

rawDescription: matplotlib - Changing background image of the graph and save the results on file

description: Matplotlib - Changing background image of the graph and save the results on file


code:
pool = multiprocessing.Pool(4)
out1, out2, out3 = zip(*pool.map(calc_stuff, range(0, 10 * offset, offset)))

rawDescription: how do I parallelize a simple python loop?

description: Parallelize a simple python loop