code:
ux, uy = self.GetScrollPixelsPerUnit()
sx, sy = self.GetViewStart()
w, h = self.GetGridWindow().GetClientSize().Get()
sx *= ux ; sy *= uy

x0 = self.XToCol(sx)
y0 = self.YToRow(sy)
x1 = self.XToCol(sx + w, True)
y1 = self.YToRow(sy + h, True)

rawDescription: WxPython: How to get the range of displayed cells in a wx grid?


code:
class TestMyClass(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        db_data_repo = repositories.DBDataRepository()
        db_data = db_data_repo.find(1)
        cls.class_to_test = MyClass(db_data)

    def test_result_should_be_an_float(self):
        result = self.class_to_test.do_something()
        assert isinstance(result, float)

rawDescription: Writing Python test classes using Nose and Sqlalchemy with fixtures


code:
import binascii, doctest

def ascii_to_packed_hex(string_data):
    r"""
    >>> binascii.a2b_hex('01')
    '\x01'
    >>> binascii.a2b_hex('0102030405')
    '\x01\x02\x03\x04\x05'
    >>> binascii.a2b_hex('fafbfcfd')
    '\xfa\xfb\xfc\xfd'
    >>> binascii.a2b_hex('31323334')
    '1234'
    """
    doctest.testmod()

rawDescription: Python: convert string to packed hex ( '01020304' -> '\x01\x02\x03\x04' )


rawDescription: How to add the content of two tuples (or lists)?

description: Add the content of two tuples (or lists)


rawDescription: Inserting a value to a sublist in a list. PYTHON


code:
import requests
username = "SomeUser"
password = "SomePass"
r = requests.get("https://a.b.c:7895/resource/path?param1=foo",auth=(username,password),verify=False)

rawDescription: How do I make a BasicAuth REST query over SSL with python3

description: Make a BasicAuth REST query over SSL with python3


code:
class SuperHero(object):
    @property
    def name(self):
        return self._name
    @name.setter
    def name(self, name):
        self._name = name

sh = SuperHero()
sh.name = "Clark Kent"

rawDescription: Python: How to copy all attibutes from base class to derived one


code:
u = "he is a [good man] and she is a [beautiful woman]"
m = u.split()
m
l = re.findall(r'\[([^\]]*)\]', u)
l
j = [k for k,v in enumerate(m) if v.startswith('[')]
dict(zip(l,j))

rawDescription: Using re.search or re.findall in regular expression to detect words with their index in the sentence


code:
from subprocess import Popen, PIPE, STDOUT

p = Popen(['lzop', '-c'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
result_stdout = p.communicate(input=json.dump(results))[0]

rawDescription: How to compress Twitter streaming using LZO in Linux/Python/Tweepy environment?

description: Compress Twitter streaming using LZO in Linux/Python/Tweepy environment


code:
import sys

cKey = ""
cList = []
lines = sys.stdin.readlines()

for line in lines:
    line = line.rstrip()
    splitLine = line.split("\t")

    if len(splitLine) > 1:
      key = splitLine[0]
      value = splitLine[1]

rawDescription: python: list index out of range in reducer

description: Python: list index out of range in reducer


code:
from bokeh.io import vform
from bokeh.models import CustomJS, ColumnDataSource, MultiSelect
from bokeh.plotting import figure, output_file, show
import pandas as pd

IBM = pd.read_csv(
        "http://ichart.yahoo.com/table.csv?s=IBM&a=0&b=1&c=2011&d=0&e=1&f=2016",
        parse_dates=['Date'])

output_file("datetime.html")
source = ColumnDataSource({'x': IBM['Date'], 'y1': IBM['Close'], \
'y2': IBM['Adj Close'], 'y1p': IBM['Close'], 'y2p': IBM['Adj Close']})

p = figure(width=500, height=250, x_axis_type="datetime")

p.line('x', 'y1', source=source, color='navy', alpha=0.5)
p.line('x', 'y2', source=source, color='red', alpha=0.5)

callback = CustomJS(args=dict(source=source), code="""
        var data = source.get('data');
        var f = cb_obj.get('value')
        y1 = data['y1']
        y2 = data['y2']
        y1p = data['y1p']
        y2p = data['y2p']
        if (f == "line2") {
            for (i = 0; i < y1.length; i++) {
                y1[i] = 'nan'
                y2[i] = y2p[i]
            }
        } else if (f == "line1") {
            for (i = 0; i < y2.length; i++) {
                y1[i] = y1p[i]
                y2[i] = 'nan'
            }
        } else if (f == "none") {
            for (i = 0; i < y2.length; i++) {
                y1[i] = 'nan'
                y2[i] = 'nan'
            }
        } else {
            for (i = 0; i < y2.length; i++) {
                y1[i] = y1p[i]
                y2[i] = y2p[i]
            }
        }
        source.trigger('change');
    """)

multi_select = MultiSelect(title="Lines to plot:", \
value=["line1", "line2", "none"], \
options=["line1", "line2", "none"], callback=callback)
layout = vform(multi_select, p)
show(layout)

rawDescription: Bokeh widget-Working Checkbox Group Example


code: import mymodule.cool.stuff

rawDescription: Importing modules in Python and __init__.py


code:
import Gnuplot
x = [1,2,3,4]
gp = Gnuplot.Gnuplot()
gp.title('My title')
gp('set style data linespoints')
gp.plot(x)

rawDescription: Plotting lines with gnuplot python

description: Plotting lines with gnuplot python


code:
class webviewscroll:
    def __init__(self):
        #webview = ...
        #scrolled_window = ...
        self.vadjustment = scrolled_window.get_vadjustment()
        self.vadjustment.connect('changed', self.on_vadjustment_changed)
        self.scroll_position = {'html_changed': False, 'value': 0}

    def update(self):
        self.scroll_position['html_changed'] = True
        self.scroll_position['value'] = self.vadjustment.get_value()
        self.update_webview() #This method loads the new HTML file

    def on_vadjustment_changed(self, adjustment):
        if self.scroll_position['html_changed'] == True:
            self.vadjustment.set_value(self.scroll_position['value'])
            self.scroll_position['html_changed'] = False

rawDescription: Python Webkit autoscroll

description: Python Webkit autoscroll


code:
if all(c.upper() in 'ATGC' for c in seq_record.seq):
    pass # it's DNA

rawDescription: translate a mixed fasta file using python/biopython

description: Translate a mixed fasta file using python/biopython


code:
Popen("command -flag 'foo foo1'", shell=True)
Popen(["command", "-flag", "foo foo1"])

rawDescription: Python Subprocess: Unable to Escape Quotes


code:
class U32:
    """Emulates 32-bit unsigned int known from C programming language."""

    def __init__(self, num=0, base=None):
        """Creates the U32 object.

        Args:
            num: the integer/string to use as the initial state
            base: the base of the integer use if the num given was a string
        """
        if base is None:
            self.int_ = int(num) % 2**32
        else:
            self.int_ = int(num, base) % 2**32

    def __coerce__(self, ignored):
        return None

    def __str__(self):
        return "<U32 instance at 0x%x, int=%d>" % (id(self), self.int_)

    def __getattr__(self, attribute_name):
        print("getattr called, attribute_name=%s" % attribute_name)
        # you might want to take a look here:
        # http://stackoverflow.com/q/19611001/1091116
        r = getattr(self.int_, attribute_name)
        if callable(r):  # return a wrapper if integer's function was requested
            def f(*args, **kwargs):
                if args and isinstance(args[0], U32):
                    args = (args[0].int_, ) + args[1:]
                ret = r(*args, **kwargs)
                if ret is NotImplemented:
                    return ret
                if attribute_name in ['__str__', '__repr__', '__index__']:
                    return ret
                ret %= 2**32
                return U32(ret)
            return f
        return r

print(U32(4) / 2)
print(4 / U32(2))
print(U32(4) / U32(2))

rawDescription: Emulate uint32_t in Python?

description: Emulate uint32_t in Python


code:
from django.db import models

class Card(object):
    """The ``Card`` class you described."""
    ...

class CardField(models.PositiveIntegerField):
    __metaclass__ = models.SubfieldBase

    def get_db_prep_value(self, value):
        """Return the ``int`` equivalent of ``value``."""
        if value is None: return None
        try:
            int_value = value.as_number()
        except AttributeError:
            int_value = int(value)
        return int_value

    def to_python(self, value):
        """Return the ``Card`` equivalent of ``value``."""
        if value is None or isinstance(value, Card):
            return value
        return Card(int(value))

rawDescription: How do I create trivial customized field types in Django models?

description: Create trivial customized field types in Django models


code:
br.open(url)

# forms = [f for f in br.forms()]
# print forms[1]
# print forms[1].controls[0]

br.select_form(nr = 1)

br.form.set_all_readonly(False)

br.form.set_value(firstname, nr=0)
br.form.set_value(lastname, nr=1)
br.form.set_value(email, nr=2)
br.form.set_value(zip, nr=3)

br.submit()

rawDescription: Python Mechanize Add Value to Form Input without ID or Name


code:
from tastypie.resources import ModelResource
from tastypie.exceptions import BadRequest

class MyResource(ModelResource):
    class Meta:
        ...
        allowed_update_fields = ['field1', 'field2']

    def update_in_place(self, request, original_bundle, new_data):
        if set(new_data.keys()) - set(self._meta.allowed_update_fields):
            raise BadRequest(
                'Only update on %s allowed' % ', '.join(
                    self._meta.allowed_update_fields
                )
            )

        return super(MyResource, self).update_in_place(
            request, original_bundle, new_data
        )

rawDescription: tastypie - where to restrict fields that may be updated by PATCH?

description: Tastypie - where to restrict fields that may be updated by PATCH


code:
from traceback import print_exc
import zmq
from tornado.httputil import HTTPHeaders

class BadRequest(Exception):
    pass

class ConnectionLost(Exception):
    pass

def parse_request(request):
    """Parse a request verp, path, and headers"""
    first_line, header_lines = request.split(b'\r\n', 1)
    verb, path, proto = first_line.decode('utf8').split()
    headers = HTTPHeaders.parse(header_lines.decode('utf8', 'replace'))
    return verb, path, headers

def recv_body(socket, headers, chunks, request_id):
    """Receive the body of a request"""
    if headers.get('expect', '').lower() == '100-continue':
        if 'Content-Length' not in headers:
            # Don't support chunked transfer: http://tools.ietf.org/html/rfc2616#section-3.6.1
            print("Only support specified-length requests")
            socket.send_multipart([
                request_id, b'HTTP/1.1 400 (Bad Request)\r\n\r\n',
                request_id, b'',
            ])
            msg = 1
            while msg != b'':
                # flush until new connection
                _, msg = socket.recv_multipart()
            raise BadRequest("Only support specified-length requests")

        socket.send_multipart([request_id, b'HTTP/1.1 100 (Continue)\r\n\r\n'], zmq.SNDMORE)

        content_length = int(headers['Content-Length'])
        print("Waiting to receive %ikB body" )
        while sum(len(chunk) for chunk in chunks) < content_length:
            id_, msg = socket.recv_multipart()
            if msg == b'':
                raise ConnectionLost("Disconnected")
            if id_ != request_id:
                raise ConnectionLost("Received data from wrong ID: %s != %s" % (id_, request_id))
            chunks.append(msg)
    return b''.join(chunks)

print(zmq.__version__, zmq.zmq_version())

socket = zmq.Context().socket(zmq.STREAM)
socket.bind("tcp://*:5555")

while True:
    # Get HTTP request
    request_id, msg = socket.recv_multipart()
    if msg == b'':
        continue
    chunks = []
    try:
        request, first_chunk = msg.split(b'\r\n\r\n', 1)
        if first_chunk:
            chunks.append(first_chunk)
        verb, path, headers = parse_request(request)
        print(verb, path)
        print("Headers:")
        for key, value in headers.items():
            print('  %s: %s' % (key, value))
        body = recv_body(socket, headers, chunks, request_id)
        print("Body: %r" % body)
    except BadRequest as e:
        print("Bad Request: %s" % e)
    except ConnectionLost as e:
        print("Connection Lost: %s" % e)
    except Exception:
        print("Failed to handle request", msg)
        print_exc()
        socket.send_multipart([
            request_id, b'HTTP/1.1 500 (OK)\r\n\r\n',
            request_id, b''])
    else:
        socket.send_multipart([
            request_id, b'HTTP/1.1 200 (OK)\r\n\r\n',
            request_id, b''])

rawDescription: HTTP server in ZMQ or How to handle a POST request with pyzmq?


rawDescription: Plots made with rpy sent to X11 suddenly close?


code:
keys_a = set(dict_a.keys())
keys_b = set(dict_b.keys())
intersection = keys_a & keys_b # '&' operator is used for set intersection

rawDescription: Intersecting two dictionaries in Python

description: Intersecting two dictionaries in Python


code: "Python or Java use a lot of words".lower().split().count('or')

rawDescription: Finding a word in just a sentence and not in a word (python)


code:
# a list of animals that can "speak"
animals = [Dog(), Cat(), Turkey()]
for a in animals:
  a.speak()

# .. but a string cannot "speak"
animals = [Dog(), "Meow!", Turkey()]

rawDescription: What is "homogenous" in Python list documentation?


code:
with open(FILELOCATION + utcnow.strftime("%Y-%m-%d") + "-" +site+"-prob.txt","w") as f:
    #write to the file below
    f.close()
#open file again as a txt file
f = open(FILELOCATION + utcnow.strftime("%Y-%m-%d") + "-" +site+"-prob.txt","rb")
ftp.storlines("STOR " + utcnow.strftime("%Y-%m-%d-") + site +"-prob.csv",f)
f.close()

rawDescription: new line chars added to csv file after ftp.storbinary()

description: New line chars added to csv file after ftp.storbinary()


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

wait = WebDriverWait(driver, 10)
elm = wait.until(EC.presence_of_element_located((By.XPATH, "//select[@ng-model='yourName']")))

rawDescription: Locating an element using ng-model using Selenium in python


code:
import ast

strArray =  "[[1,2,3],[3,4,5],[6,7,8]]"

# evaluates the array in string format and converts it to a python array object
array = ast.literal_eval(strArray)

rawDescription: Import matrix from text file using python


code:
a = [1,2,3,4,5,6]
matlab_cmd_string = MatlabExePth+ " -nosplash -nodesktop -wait -logfile   FileIoReg_MatlabRemoteRun.log -minimize -r "
mat_file = "tst_script"
tstPth = 'C\\SVN\\Matlabcode\\tst1'
listToBePassed = str(a)
mat_cmd = matlab_cmd_string + '\"' + mat_file + '(' + listToBePassed + ')' + ', exit\"'

rawDescription: passing non string parameter from python to Matlab

description: Passing non string parameter from python to Matlab


code:
from matplotlib.figure import Figure

class FlightData(QtGui.QDialog, Ui_Dialog):
    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.figs = {}
        self.canvas = {}
        self.axs = {}
        plot_names = ['speed', 'height', 'map', 'angle']
        for pn in plot_names:
            fig = Figure()
            self.canvas[pn] = FigureCanvas(fig)
            ax = fig.add_subplot(1, 1, 1)

            self.figs[pn] = fig
            self.axs[pn] = ax

        # -------------------------------------------------------------
        self.speedLayout.addWidget(self.canvas['speed'])
        self.heightLayout.addWidget(self.canvas['height'])
        self.mapLayout.addWidget(self.canvas['map'])
        self.angleLayout.addWidget(self.canvas['angle'])

    def draw_plot(self, target, data):
        self.axs[target].plot(data, '-*')
        self.canvas[target].draw_idle()

rawDescription: How to plot different graphs in different canvas in PyQt4 in a window?

description: Plot different graphs in different canvas in PyQt4 in a window


code:
import csv

records = [line for line in csv.reader(open('test_input.csv', 'rt'), delimiter=',')]
outfile1 = open('test_output1.csv', 'wt')
outfile2 = open('test_output2.csv', 'wt')
outfileWriter1 = csv.writer(outfile1, delimiter=',')
outfileWriter2 = csv.writer(outfile2, delimiter=',')

# headers always the same
outfileWriter1.writerow(records[0])
outfileWriter2.writerow(records[0])

for record in records[1:]:
    cat = record[-1].strip() # get category in form "AB"
    new_record = record
    new_record[-1] = "\t%s" % cat[0] # set category for file 1 with tab as a prefix
    outfileWriter1.writerow(new_record)
    new_record[-1] = "\t%s" % cat[1] # set category for file 2 with tab as a prefix
    outfileWriter2.writerow(new_record)

outfile1.close()
outfile2.close()

rawDescription: How to split up data from a column in a csv file into two separate output csv files?

description: Split up data from a column in a csv file into two separate output csv files


rawDescription: xml.etree.ElementTree getElementByID()?

description: Xml.etree.ElementTree getElementByID()


code:
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
import matplotlib.pyplot as plt

velocity=np.random.rand(3,9)

fig, ax1 = plt.subplots(1,1,figsize=(16, 12), dpi=100, subplot_kw={'aspect': 'equal'})

ax1.set_yticks([int(j) for j in range(0,4)])
ax1.set_xticks([int(j) for j in range(-4,5)])

for label in ax1.get_xticklabels() + ax1.get_yticklabels():
    label.set_fontsize(15)
for tick in ax1.get_xticklines() + ax1.get_yticklines():
    tick.set_markeredgewidth(2)
    tick.set_markersize(6)

im = ax1.imshow(velocity, cmap=cm.jet,     interpolation='nearest',origin='lower',vmin=0,vmax=1.7, extent=[-4.50,4.50,0,3])
ax1.set_xlim(-4,4)

divider = make_axes_locatable(ax1)
cax = divider.append_axes("right", size="2.5%", pad=0.3)
cb=plt.colorbar(im,cax=cax)
cb.set_label('Speed [$m/s$]')

plt.savefig("speed_400.png")
plt.close(fig)

rawDescription: How to limit the range of the x-axis with imshow()?

description: Limit the range of the x-axis with imshow()


code:
get(key, namespace=None)

get_multi(keys, key_prefix='', namespace=None)

rawDescription: how do I return all memcached values in Google App Engine?

description: Return all memcached values in Google App Engine


code:
from IPython.config import Application
log = Application.instance().log

rawDescription: IPython.parallel - can I write my own log into the engine logs?


rawDescription: Regular expression and Python

description: Regular expression and Python


code:
sqs = SearchQuerySet().models(Post)
sqs1 = sqs.filter(title_auto=q)
sqs2 = sqs.filter(body_auto=q)

sqs = sqs1 | sqs2

rawDescription: Django Haystack autocompletion on two (multiple) fields


code:
import logging

logger = logging.getLogger(__name__)
configured = False

def configure_logging():
    global configured
    if not configured:
        logger.setLevel(logging.DEBUG) # or whatever
        console = logging.StreamHandler()
        file = logging.FileHandler('/path/to/file')
        #set a level on the handlers if you want;
        #if you do, they will only output events that are >= that level
        logger.addHandler(console)
        logger.addHandler(file)
        configured = True

rawDescription: Managing loggers with Python logging

description: Managing loggers with Python logging


code:
class Rating(models.Model):
    user = models.ForeignKey(User)
    answer = models.ForeignKey(Answer)
    rating = models.BooleanField(default=0, related_name='rating')

answers = Answer.objects.filter(question__category__id=category_id).annotate(
    rating_sum=Count(rating__rating)).order_by('-rating_sum')

rawDescription: How to write query for joining three tables with filter and order by condition in django

description: Write query for joining three tables with filter and order by condition in django


code:
df.dtypes
for colname, coltype in df.dtypes.iteritems():
    print(colname, coltype)

rawDescription: how to write a loop to know the type of all columns in a data frame?

description: Write a loop to know the type of all columns in a data frame


rawDescription: PySerial App runs in shell, by not py script


code:
import threading
def func1(a,b):
    def func2():
        def func4():
            return func3(a,b)
        return threading.Thread(target=func4)
    return func2

func2=func1(a,b)
func2()

rawDescription: Calling a function within a closure in python


code:
from __future__ import absolute_import

import mirad.fetcher_tasks as tasks
from mirad.models.models import SourceModel
from mirad.settings import *
from celery.task.control import inspect

parse_feed_tasks = list()

def fetch():

        for source in SourceModel.objects(active=True):
            a = tasks.parse_feed.delay(source)

rawDescription: ImportError: No module named control

description: ImportError: No module named control


code:
from collections import OrderedDict
import urllib
urllib.urlencode(OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')]))
# Out: 'k1=v1&k2=v2&k3=v3'

rawDescription: Keeping url parameters in order when encoding with urllib


code:
class Article(models.Model):
    title = models.CharField(blank=False, max_length=80)
    slug = models.SlugField(max_length=80)
    revision_1 = models.OneToOneField(ArticleRevision, related_name='_unused_1')
    revision_2 = models.OneToOneField(ArticleRevision, related_name='_unused_2')

    def __unicode__(self):
        return self.title

rawDescription: How to model one way one-to-one relationship in Django

description: Model one way one-to-one relationship in Django


code:
from collections import defaultdict
file_list = glob.glob('/scratch/project/*')

methods = defaultdict([])
for outfile in file_list:
    #indices = (#function that obtains indices)
    #data    = (#function that obtains primary data)

    methods[method].append([indices,data])

frames = [ DataFrame(method_list,columns[indices,method])
         for method, method_list in methods.items() ]

# concat
combine_frame = pd.concat(frames,axis=1)

# set your combined index
result = combine_frame.set_index(indicies)

rawDescription: Creating a large database from many files with pandas


code:
import logging, os, time

PING_HOST='10.10.10.10'  # some host on the other side of the VPN

while True:
    retcode = os.system('ping -c 1 %s' % PING_HOST)

    if retcode:
       # perform action for lost connection
       logging.warn('Lost visibility with %s' % PING_HOST)

    time.sleep(10)  # sleep 10 seconds

rawDescription: Continuous check for VPN Connectivity - Python


code:
command = raw_input("Enter command: ")
while(True):
    print(command)
    if command.rstrip('\r\n') == "end":
        break
    else:
        tn.write(command.encode("utf-8"))
        ret1 = tn.read_until(b"_DNE", timeout = 10)
        print(ret1)
        command = raw_input("Enter command: ")

rawDescription: Python loop won't exit on specific user input


rawDescription: Python: initialize multi-dimensional list


code:
d = {}

lines = [line.strip() for line in open('test.txt')]

for line in lines:
    title, minutes = line.rsplit(maxsplit=1)
    d[title] = int(minutes[:-3])

print(d)

rawDescription: Splitting Python list to smaller substrings


code:
import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,size=(250, 250))
        panel = wx.Panel(self, -1)
        panel.SetBackgroundColour('white')
        self.browserList=wx.ListCtrl(panel, pos=(20,150), size=(250,100),style = wx.LC_REPORT|wx.BORDER_SUNKEN)
        self.browserList.InsertColumn(0, '', width=50)
        self.browserList.InsertColumn(1, 'Browser: ', width=200)

        self.list=wx.ImageList(40,40)
        self.browserList.SetImageList(self.list, wx.IMAGE_LIST_SMALL)
        images=['mozilla.png','chrome.png']
        x=0
        for i in images:
            img=wx.Image(i, wx.BITMAP_TYPE_ANY)
            img=wx.BitmapFromImage(img)
            browserimg=self.list.Add(img)
        self.browserList.InsertImageItem(x, 0)
        self.browserList.InsertImageItem(x, 1)

        self.browserList.SetStringItem(0, 1, "Mozilla Firefox")
        self.browserList.SetStringItem(1, 1, "Google Chrome")

class MyApp(wx.App):
     def OnInit(self):
         frame = MyFrame(None, -1, 'frame')
         frame.Show(True)
         return True

app = MyApp(0)
app.MainLoop()

rawDescription: WxPython ListCtrl: One Column with Images and One with a String


code:
if any(name in dict for name in set):
    print('Yay')

rawDescription: How to move onto the next iteration of a loop within a loop in python?

description: Move onto the next iteration of a loop within a loop in python


rawDescription: Comparing all elements of two tuples (with all() functionality)


code:
import pandas as pd

df = pd.DataFrame.from_records(data)
# In [38]: df
# Out[38]:
#    disease_id                     disease_name    manufacturer_name  medication_id medication_name  practice_id           practice_name practice_state
#    0          16                 Type II Diabetes         Novo Nordisk             68         Victoza            1  Cambridge Hospital Inc             MA
#    1          12  Pulmonary Arterial Hypertension             Actelion             39         Opsumit            1  Cambridge Hospital Inc             MA
#    2          16                 Type II Diabetes             Intarcia             29        ITCA-650            1  Cambridge Hospital Inc             MA
#    3          12  Pulmonary Arterial Hypertension      GlaxoSmithKline             22          Flolan            1  Cambridge Hospital Inc             CA
#    4          12  Pulmonary Arterial Hypertension  United Therapeutics              4         Adcirca            1  Cambridge Hospital Inc             CA

res = {}
res['medication'] = df[['medication_id', 'medication_name']].to_dict(orient='records')

# In [49]: res
# Out[49]:
# {
#     'medication': [
#         {'medication_id': 68, 'medication_name': 'Victoza'},
#         {'medication_id': 39, 'medication_name': 'Opsumit'},
#         {'medication_id': 29, 'medication_name': 'ITCA-650'},
#         {'medication_id': 22, 'medication_name': 'Flolan'},
#         {'medication_id': 4, 'medication_name': 'Adcirca'}]
# }

rawDescription: Converting a python data structure from one form to another


code:
import re
r = re.compile(r'\d+$')
[int(m.group()) for m in (r.search(item) for item in mylist) if m]

rawDescription: return trailing set of nums from string python

description: Return trailing set of nums from string python


code:
class Spam(object):
    def __init__(self, description, value):
        self.description = description
        self.value = value

    @property
    def description(self):
        return self._description

    @description.setter
    def description(self, d):
        if not d: raise Exception("description cannot be empty")
        self._description = d

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, v):
        if not (v > 0): raise Exception("value must be greater than zero")
        self._value = v

rawDescription: Correct approach to validate attributes of an instance of class


rawDescription: How to get the time to milliseconds resolution python

description: Get the time to milliseconds resolution python


code:
class User(models.Model):
    name = models.CharField(max_length=128)

class Event(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(User, through='Role')

    def __unicode__(self):
        return self.name

class Role(models.Model):
    person = models.ForeignKey(User)
    group = models.ForeignKey(Event)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

rawDescription: How to create a triple-join table with Django

description: Create a triple-join table with Django


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

# some fake data
data = np.random.randn(1000)
# evaluate the histogram
values, base = np.histogram(data, bins=40)
#evaluate the cumulative
cumulative = np.cumsum(values)
# plot the cumulative function
plt.plot(base[:-1], cumulative, c='blue')
#plot the survival function
plt.plot(base[:-1], len(data)-cumulative, c='green')

plt.show()

rawDescription: cumulative distribution plots python

description: Cumulative distribution plots python


code:
import urllib
response = urllib.urlopen("http://www.py4inf.com/cover.jpg")
content = response.read()
outf = open("cover.jpg", 'wb')
outf.write(content)
outf.close()

rawDescription: Retrieving an image over HTTP in Python

description: Retrieving an image over HTTP in Python


code:
#!/usr/bin/env python3.5
import asyncio
import sys
from asyncio.subprocess import PIPE, STDOUT

async def get_lines(shell_command):
    p = await asyncio.create_subprocess_shell(shell_command,
            stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    return (await p.communicate())[0].splitlines()

async def main():
    # get commands output concurrently
    coros = [get_lines('"{e}" -c "print({i:d}); import time; time.sleep({i:d})"'
                       .format(i=i, e=sys.executable))
             for i in reversed(range(5))]
    for f in asyncio.as_completed(coros): # print in the order they finish
        print(await f)

if sys.platform.startswith('win'):
    loop = asyncio.ProactorEventLoop() # for subprocess' pipes on Windows
    asyncio.set_event_loop(loop)
else:
    loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

rawDescription: Asynchronously receive output from long running shell commands with asyncio (Python 3.4+)?


code:
old = {1: 'one', 2: 'two'}
new = {1: 'newone', 2: None, 3: 'new'}

old.update( (k,v) for k,v in new.iteritems() if v is not None)

# {1: 'newone', 2: 'two', 3: 'new'}

rawDescription: Update a dictionary with another dictionary, but only non-None values


code:
import IPython
IPython

rawDescription: uninstall ipython mac os x

description: Uninstall ipython mac os x


code:
from django.contrib.auth.models import User, Group, Permission
from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get(app_label='myapp', model='BlogPost')
permission = Permission.objects.create(codename='can_publish',
                                       name='Can Publish Posts',
                                       content_type=content_type)
user = User.objects.get(username='duke_nukem')
group = Group.objects.get(name='wizard')
group.permissions.add(permission)
user.groups.add(group)

rawDescription: User groups and permissions

description: User groups and permissions


code:
class MyClass(object):

    all_instances = {}

    def __new__(cls, unique_id, x, y, z):
        instance = cls.all_instances.get(unique_id)
        if instance is not None:
            instance.is_initialized = True
        else:
            instance = super(MyClass, cls).__new__(cls, unique_id, x, y, z)
            instance.is_initialized = False
        return instance

    def __init__(self, unique_id, x, y, z):
        if self.is_initialized:
            return
        # Do initialization here.

rawDescription: Reassign self in init

description: Reassign self in init


code:
from pylab import subplot, show, draw
ax = subplot(111)
props = dict(boxstyle='round', facecolor='red', alpha=0.3)
t = ax.text(0.03, 0.97, 'test', transform=ax.transAxes, fontsize=10, verticalalignment='top', bbox=props)
show()
bb = t.get_bbox_patch()
bb.set_facecolor('blue')
draw()

rawDescription: Change facecolor in text matplotlib

description: Change facecolor in text matplotlib


code:
col_index=1
i=0
while i<4:
    start_cell = worksheetworksheet.get_addr_int(10, col_index)
    end_cell = worksheetworksheet.get_addr_int(20, col_index+2)
    cell_values_list=worksheetworksheet.range('%s:%s' % (start_cell, end_cell))
    ...
    ...
    col_index=col_index+3
    i=i+1

rawDescription: while loop incrementing range in django

description: While loop incrementing range in django


code:
from datetime import datetime
from pytz import timezone

customer_time_zone = 'America/Los_Angeles'

#gets a non naive datetime (utc)
utcnow = datetime.utcnow()
utcnow = utcnow.replace(tzinfo=pytz.utc)

#localize current utc with customer_time_zone
relative_time = utcnow.astimezone(timezone(customer_time_zone))
utcnow, relative_time
relative_time.hour
utcnow.hour

rawDescription: compare the same time in different time zones in python

description: Compare the same time in different time zones in python


code:
def get_object(self, request, object_id):
    obj = super(YourModelAdmin, self).get_object(request, object_id)
    for key, value in request.GET.items():
        setattr(obj, key, value)
    return obj

rawDescription: Django-admin: Changing field values in change form before rendering


code:
vertices = list(zip(x, y))
list(zip(vertices, vertices[1:] + [vertices[0]]))

rawDescription: Creating line segment lists from x,y lists in Python


code:
pattern = re.compile(r'\s*(.*?)\s*(?:AE|BE)')
pattern.findall('')
pattern.findall('bar BE')
pattern.findall('foo AE')
pattern.findall('foo AE bar BE')

rawDescription: Capture both of two optional groups

description: Capture both of two optional groups


code:
class MyCalendar(QtGui.QCalendarWidget):
  def __init__(self,parent=None):
    QtGui.QCalendarWidget.__init__(self,parent)

  def paintCell(self, painter, rect, date):
    QtGui.QCalendarWidget.paintCell(self, painter, rect, date)
    if date.day() % 5 == 0: # example condition based on date
      painter.drawText(rect.bottomLeft(), "test")

rawDescription: Custom calendar cell in PyQt

description: Custom calendar cell in PyQt


code:
class DocumentForm(forms.Form):
    form1 = forms.FileField()
    form2 = forms.FileField()

rawDescription: How Can I attach multiple forms to a single submit button in Django?

description: Attach multiple forms to a single submit button in Django


code:
import nltk
sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')
sent_detector._params.abbrev_types.add('hon')
sent_detector.tokenize(your_text)

rawDescription: How to get the first sentence from the following paragraph?

description: Get the first sentence from the following paragraph


code:
#!/usr/bin/env python

from distutils.core import setup

setup(
    name="foo",
)

rawDescription: Can I use a requirements.txt file to handle local python directories?

description: Use a requirements.txt file to handle local python directories


code:
def cursor_to_dicts(cursor, field_names):
    for row in cursor:
        row_dict = {}
        for field in field_names:
            val = row.getValue(field)
            row_dict[field] = getattr(val, '__geo_interface__', val)
        yield row_dict

fc = '/path/to/fc'
fields = [f.name for f in arcpy.ListFields(fc)]   # get field list
features = list(cursor_to_dicts(arcpy.SearchCursor(fc), fields))

rawDescription: Loading a feature class in a list using arcpy : strange behaviour of SearchCursor


code:
from django.db.models import Count
results = AdminEnteredRestaurant.objects.annotate(num_photos=Count('restaurant__photo')) \
                                        .filter(num_photos__lte=1) \
                                        .filter(restaurant__menu__isnull =True)

rawDescription: Filter by one-to-many relation based off of object count in Django


code:
class DownloadableMixin():
    """
    Manages a ticket response, where a ticket is a signed response that gives a user limited access to a resource
    for a time frame of 5 secs.

    Therefore, file downloads can request a ticket for a resource and gets a ticket in the response that he can
    use for non-ajax file-downloads.
    """

    MAX_AGE = 5

    def check_ticket(self, request):
        signer = TimestampSigner()
        try:
            unsigned_ticket = signer.unsign(request.QUERY_PARAMS['ticket'], max_age=self.__class__.MAX_AGE)
        except SignatureExpired:
            return False
        except BadSignature:
            return False

        if self.get_requested_file_name() == unsigned_ticket:
            return True
        return False

    def get_ticket(self):
        signer = TimestampSigner()
        return signer.sign(self.get_requested_file_name())

    def has_ticket(self, request):
        return 'ticket' in request.QUERY_PARAMS

    def requires_ticket(self, request):
        return 'download' in request.QUERY_PARAMS

    def get_requested_file_name(self):
        raise NotImplementedError('Extending classes must define the requested file name.')

rawDescription: User Sessions in an oauth2 django app

description: User Sessions in an oauth2 django app


code:
def points(*args):
  return list(product(*[range(n) for n in args]))

rawDescription: python coordinates generator

description: Python coordinates generator


rawDescription: Populate wx.StaticText controls with dictionary key:value pairs


rawDescription: One Function in Python to Iterate Over Concurrent Lists to be Used in Equation


code:
def p_expression_assign(t):
    'expression : NAME EQUALS expression'
    t[0] = names[t[1]] = t[3]

rawDescription: How to implement multiple assignment in an interpreter written in python?

description: Implement multiple assignment in an interpreter written in python


code:
class Foo(object):
    def __get__(self, obj, type=None):
        return self

    def __call__(self, x):
        print(x)

foo = Foo()

class A(object):
    def __init__(self):
        self.f = foo
class B(object):
    f = foo

foo(1) # 1
a = A()

a.f(1) # 1
print(a.f)               #<function foo at 0x2321d10>
print(a.f.__get__(a, A)) #<function foo at 0x2321d10>

b = B()
b.f(1) # 1

print(b.f)               #<__main__.Foo object at 0x7fa8c260be10>

rawDescription: How to make python function always unbound even assigned to a class attribute

description: Make python function always unbound even assigned to a class attribute


code:
cur.execute(
    """INSERT INTO some_table (an_int, a_date, a_string)
        VALUES (%s, %s, %s);""",
    (10, datetime.date(2005, 11, 18), "O'Reilly"))

rawDescription: Escape input data for postgres

description: Escape input data for postgres


rawDescription: Pandas: Group by date and the median of another variable


code:
with open('your_file.csv') as f:
    reader = csv.reader(f)
    header = next(reader)

rawDescription: Processing one row of a csv file

description: Processing one row of a csv file


code: [mylist[i] for i in range(start,stop,step)]

rawDescription: stepping in python-bitstring 2.2.0

description: Stepping in python-bitstring 2.2.0


code:
from matplotlib import pyplot as plt
from matplotlib.patches import Ellipse

fig = plt.figure()
ax = fig.add_subplot(111)
ax.add_artist(Ellipse(xy=(1, 1), width=2, height=2, facecolor='g', edgecolor='k', alpha=.1))
plt.show()

rawDescription: Why is my ellipse not appearing?

description: Why is my ellipse not appearing


code:
class LogTemplateView(TemplateView):
    template_name = "mylog.html"
    apache_log_file = "apache.error.log"
    django_log_file = "django.log"

    def get_context_data(self, **kwargs):
        """
        This has been overriden to give the template access to the log files.
        i.e. {{ apache_log_file }} and {{ django_log_file }}
        """
        context = super(LogTemplateView, self).get_context_data(**kwargs)
        context["apache_log_file"] = self.tail(open(self.apache_log_file, "r"), 20)
        context["django_log_file"] = self.tail(open(self.django_log_file, "r"), 20)
        return context

    # Credit: Armin Ronacher - http://stackoverflow.com/a/692616/1428653
    def tail(f, n, offset=None):
        """Reads a n lines from f with an offset of offset lines.  The return
        value is a tuple in the form ``(lines, has_more)`` where `has_more` is
        an indicator that is `True` if there are more lines in the file.
        """
        avg_line_length = 74
        to_read = n + (offset or 0)

        while 1:
            try:
                f.seek(-(avg_line_length * to_read), 2)
            except IOError:
                # woops.  apparently file is smaller than what we want
                # to step back, go to the beginning instead
                f.seek(0)
            pos = f.tell()
            lines = f.read().splitlines()
            if len(lines) >= to_read or pos == 0:
                return lines[-to_read:offset and -offset or None], \
                       len(lines) > to_read or pos > 0
            avg_line_length *= 1.3

rawDescription: How can I open two log files in one HTML page in Django?

description: Open two log files in one HTML page in Django


code:
present = []
absent = []
for word in firstList:
    lb,ub = 0,len(secondList) - 1
    found = False
    while lb <= ub:
        mid = (lb + ub) // 2
        if secondList[mid] == word:
            found = True
            break
        elif secondList[mid] < word:
            lb = mid + 1
        else:
            ub = mid - 1

    if found:
        present.append(word)
    else:
        absent.append(word)

rawDescription: Binary search of words in python list

description: Binary search of words in python list


code:
from nltk.corpus import wordnet as wn
wn.synsets('USA')

rawDescription: Is Python has any english dictionary that returns a list of words with the same meaning?


code:
for x in v:
   peak_index = signal.find_peaks_cwt(x, np.arange(2,10))
   peak_sum = np.sum(x[peak_index] > 3*d)
   i.append(peak_sum)
for p in i:
    print(p)

rawDescription: Trouble counting peaks in 1D array

description: Trouble counting peaks in 1D array


code:
fetcher_dict = {'X':XDataFetcher,'Y':YDataFetcher}
data_source = ...
fetcher = fetcher_dict[data_source]()

rawDescription: Good design pattern(s) for extensible program


code:
all_texts = []
for child in window.Children():
  all_texts.extend(child.Texts())
all_texts = filter(lambda t:t, all_texts) # clear empty texts

rawDescription: Getting the content of a window to a text file


code:
import os

modification_time = os.lstat(path_to_symlink).st_mtime

rawDescription: How to get modification date of a symlink in python?

description: Get modification date of a symlink in python


code: p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

rawDescription: Python messing vim when spawning

description: Python messing vim when spawning


code:
table = ""
while i < _list1:
    j = 0#need to reset j on each iteration of i
    _list2 = len(tup[i])
    table += "
"
    while j < _list2:
        table=+"" + tup[i][j] + "	"
        j += 1
    table += "
"
    i += 1
return table

rawDescription: How do I generate a HTML table from a two-dimensional list?

description: Generate a HTML table from a two-dimensional list


code:
def __unicode__(self):
   return '%s %s' % (self.app_id.app_name, self.environ_name)

rawDescription: django - model unicode() show foreignkey object attribute

description: Django - model unicode() show foreignkey object attribute


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

today = datetime.date.today()

imsiDate = [datetime.date(2016, 1, 11), datetime.date(2016, 1, 14), datetime.date(2016, 1, 18), ]
imsiUp = [13, 6, 24]
imsiDown = [4, 23, 1]

ax = plt.subplot()
ax.xaxis_date()

ax.yaxis.grid()
plotUp = ax.bar(imsiDate, imsiUp, width=0.75, color='r', align='center')
plotDown = ax.bar(imsiDate, imsiDown, width=0.75, color='y', align='center', bottom=imsiUp)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.xaxis.set_minor_locator(mdates.DayLocator())

#limits
t0 = today - datetime.timedelta(7)
t1 = today
ax.set_xbound(t0, t1)

ax.set_xmargin(0.75)
ax.autoscale_view()                    # <----  THIS
plt.xticks(rotation='vertical')
plt.subplots_adjust(bottom=0.25)

plt.show()

rawDescription: Plot marginal for x-axis

description: Plot marginal for x-axis


code:
def reduce_ws(txt):
    ntxt = txt.strip()
    return ' '+ ntxt + ' '

j = '    Hello World     '
print(reduce_ws(j))

rawDescription: How to reduce whitespace in Python?

description: Reduce whitespace in Python


code:
list_students = []
list_score = []
list_outof = []

how=int(input("how many students in your class?"))
for i in range(how):
   student=str(input("Enter name of student " +str(i+1)+":"))
   list_students.append(student)

for student in list_students:
    score=int(input(" " + student +":"))
    list_score.append(score)
    outof=int(input("what was the exam out of?"))
    list_outof.append(outof)

print("The percentage scores are:")
for index, student in enumerate(list_students):
    print (student,":",(list_score[index]/list_outof[index])*100.0,"%")

rawDescription: python 3: im a beginner and i need to know what im missing. how do i make it state each childs name individually?

description: Python 3: im a beginner and i need to know what im missing. how do i make it state each childs name individually


code:
special_col = ['cll_n', 'clName']

with open('myfile.csv', 'r') as fh:
    rdr = csv.DictReader(fh)

    # now we need to figure out which column is used
    for c in special_col:
        if c in rdr.fieldnames:
            break  # found the column name
    else:
        raise IOError('No special column in file')

    # now execute your existing code, but group by the
    # column using lambda row: row[c] instead of row 7
    call_existing_code(rdr, c)

def call_existing_code(rdr, c):
    # set up an output file using csv.DictWriter; you can
    # replace the original column with the new column, and
    # control the order of fields

    with open('output.csv', 'w') as fh:
        wtr = csv.DictWriter(fh, fieldnames=['list', 'of', 'fields'])
        wtr.writeheader()

        for row in groupby(rdr, lambda r: r[c]):

            # [process the row as needed here]

            wtr.writerow(row)

rawDescription: Divide csv file by column value

description: Divide csv file by column value


code:
class BaseClass(object):
    def foo(self):
        return 'foo'
    def bar(self):
        return 'bar'
    def methods_implemented(self):
        """This does work."""
        overriden = []
        for method in ('foo', 'bar'):
            this_method = getattr(self, method)
            base_method = getattr(BaseClass, method)
            if this_method.__func__ is not base_method.__func__:
                overriden.append(method)
        return overriden

class SubClass(BaseClass):
    def foo(self):
        return 'override foo'

o = SubClass()
o.methods_implemented()

rawDescription: How can a python base class tell whether a sub class has overriden its methods?


code: self.h += int(node.h)

rawDescription: Floating point layouting and rounding

description: Floating point layouting and rounding


code:
from ctypes import windll, byref, Structure, WinError, POINTER, WINFUNCTYPE
from ctypes.wintypes import BOOL, HMONITOR, HDC, RECT, LPARAM, DWORD, BYTE, WCHAR, HANDLE

_MONITORENUMPROC = WINFUNCTYPE(BOOL, HMONITOR, HDC, POINTER(RECT), LPARAM)

class _PHYSICAL_MONITOR(Structure):
    _fields_ = [('handle', HANDLE),
                ('description', WCHAR * 128)]

def _iter_physical_monitors(close_handles=True):
    """Iterates physical monitors.

    The handles are closed automatically whenever the iterator is advanced.
    This means that the iterator should always be fully exhausted!

    If you want to keep handles e.g. because you need to store all of them and
    use them later, set `close_handles` to False and close them manually."""

    def callback(hmonitor, hdc, lprect, lparam):
        monitors.append(HMONITOR(hmonitor))
        return True

    monitors = []
    if not windll.user32.EnumDisplayMonitors(None, None, _MONITORENUMPROC(callback), None):
        raise WinError('EnumDisplayMonitors failed')

    for monitor in monitors:
        # Get physical monitor count
        count = DWORD()
        if not windll.dxva2.GetNumberOfPhysicalMonitorsFromHMONITOR(monitor, byref(count)):
            raise WinError()
        # Get physical monitor handles
        physical_array = (_PHYSICAL_MONITOR * count.value)()
        if not windll.dxva2.GetPhysicalMonitorsFromHMONITOR(monitor, count.value, physical_array):
            raise WinError()
        for physical in physical_array:
            yield physical.handle
            if close_handles:
                if not windll.dxva2.DestroyPhysicalMonitor(physical.handle):
                    raise WinError()

def set_vcp_feature(monitor, code, value):
    """Sends a DDC command to the specified monitor.

    See this link for a list of commands:
    ftp://ftp.cis.nctu.edu.tw/pub/csie/Software/X11/private/VeSaSpEcS/VESA_Document_Center_Monitor_Interface/mccsV3.pdf
    """
    if not windll.dxva2.SetVCPFeature(HANDLE(monitor), BYTE(code), DWORD(value)):
        raise WinError()

# Switch to SOFT-OFF, wait for the user to press return and then back to ON
for handle in _iter_physical_monitors():
    set_vcp_feature(handle, 0xd6, 0x04)
    raw_input()
    set_vcp_feature(handle, 0xd6, 0x01)

rawDescription: Sending DDC/CI commands to monitor on Windows using Python?


code:
from zope.interface import implementer
from twisted.internet.protocol import Protocol
from twisted.internet.interfaces import IPullProducer

def serializePosition(position):
    "... take a 'position', return some bytes ..."

@implementer(IPullProducer)
class MovementUpdater(Protocol, object):
    def updatePosition(self, newPosition):
        if newPosition != self.currentPosition:
            self.currentPosition = newPosition
            self.needToSendPosition()

    waitingToSend = False

    def needToSendPosition(self):
        if not self.waitingToSend:
            self.waitingToSend = True
            self.transport.registerProducer(self, False)

    def resumeProducing(self):
        self.transport.write(serializePosition(self.currentPosition))
        self.transport.unregisterProducer()
        self.waitingToSend = False

    def stopProducing(self):
        "nothing to do here"

rawDescription: Detect when TCP is congested python twisted socket server


code:
def colorswap(pixel):
    """Shifts the channels of the image."""
    return (pixel[1], pixel[2], pixel[0])

def applyfilter(image, func):
    """ Applies a function to each pixel of an image."""
    width,height = im.size
    pixel = image.load()
    for y in range(0, height):
        for x in range(0, width):
            pixel[x,y] = func(pixel[x,y])

applyfilter(image, colorswap)

rawDescription: Is there an Image.point() method in PIL that allows you to operate on all three channels at once?


code:
# Warning, untested, sorry if it's broken.
@inlineCallbacks
def retry(deferredThing, delay=30.0, retryCount=5):
    retries = retryCount
    while True:
        try:
            result = yield deferredThing()
        except:
            if not retries:
                raise
            retries -= 1
            log.err()
            yield deferLater(reactor, delay, lambda : None)
        else:
            returnValue(result)

rawDescription: How do I design a twisted factory to handle disconnects?

description: Design a twisted factory to handle disconnects


rawDescription: Python regex grouping

description: Python regex grouping


code:
query = 'DELETE FROM boyd.%s WHERE teamid = %%s AND id = %%s AND year = %%s' % (statstype)
self.executequery(query, values[0:3])

rawDescription: python, psycopg2, and bound parameters

description: Python, psycopg2, and bound parameters


code:
In [14]: start = -2
In [15]: stop = 4
In [16]: num = 3

In [17]: np.linspace(start,stop,num)
Out[17]: array([-2.,  1.,  4.])

rawDescription: Get value in range proportional to number in python 3.4


code:
import StringIO
from PIL import Image

im = Image.open(StringIO.StringIO(buffer))

rawDescription: How to render visually a big pandas dataframe (~7000 lines, 3 columns)?

description: Render visually a big pandas dataframe (~7000 lines, 3 columns)


code:
res = [{ 'key': key,
         'values': [{'x': each['x'], 'y': each['y']}
                    for each in arr if each['key'] == key] }
       for key in all_keys]

rawDescription: Combine elements by the key in list

description: Combine elements by the key in list


code:
import pygame, random

screen = pygame.display.set_mode((800,600))

draw_on = False
last_pos = (0, 0)
color = (255, 128, 0)
radius = 10

def roundline(srf, color, start, end, radius=1):
    dx = end[0]-start[0]
    dy = end[1]-start[1]
    distance = max(abs(dx), abs(dy))
    for i in range(distance):
        x = int( start[0]+float(i)/distance*dx)
        y = int( start[1]+float(i)/distance*dy)
        pygame.draw.circle(srf, color, (x, y), radius)

try:
    while True:
        e = pygame.event.wait()
        if e.type == pygame.QUIT:
            raise StopIteration
        if e.type == pygame.MOUSEBUTTONDOWN:
            color = (random.randrange(256), random.randrange(256), random.randrange(256))
            pygame.draw.circle(screen, color, e.pos, radius)
            draw_on = True
        if e.type == pygame.MOUSEBUTTONUP:
            draw_on = False
        if e.type == pygame.MOUSEMOTION:
            if draw_on:
                pygame.draw.circle(screen, color, e.pos, radius)
                roundline(screen, color, e.pos, last_pos,  radius)
            last_pos = e.pos
        pygame.display.flip()

except StopIteration:
    pass

pygame.quit()

rawDescription: How to create MS Paint clone with Python and pygame

description: Create MS Paint clone with Python and pygame


code:
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter

highlighted = highlight('# Some Python code', PythonLexer(), HtmlFormatter())

rawDescription: Display Pretty Code in Django

description: Display Pretty Code in Django


code:
def upgrade():
    #...
    op.alter_column('my_table', 'my_column', type_=DOUBLE, existing_nullable=False)
    #...

rawDescription: Creating Double precision columns using SqlAlchemy from Alembic


rawDescription: Multidimensional Matrix in Numpy

description: Multidimensional Matrix in Numpy


code: print("Value = '%s'" % locals()['value'])

rawDescription: How to dynamically import variables after executing python script from within another script

description: Dynamically import variables after executing python script from within another script


code:
user_ns = users.get_current_user().user_id()
entity_ns = my_entity.key.namespace()      # NDB datastore
# entity_ns = my_entity.key().namespace()  # DB datastore
if user_ns == entity_ns:
    # Save the entity if the namespaces are the same
    my_entity.put()

rawDescription: How to implement security with Google App Engine datastore namespaces?

description: Implement security with Google App Engine datastore namespaces


code:
import datetime
import struct

TZFILE_MAGIC = 'TZif'.encode('US-ASCII')

def leap_seconds(f):
    """
    Return a list of tuples of this format: (timestamp, number_of_seconds)
        timestamp: a 32-bit timestamp, seconds since the UNIX epoch
        number_of_seconds: how many leap-seconds occur at timestamp

    """
    fmt = ">4s c 15x 6l"
    size = struct.calcsize(fmt)
    (tzfile_magic, tzfile_format, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt,
        typecnt, charcnt) =  struct.unpack(fmt, f.read(size))
    #print("DEBUG: tzfile_magic: {} tzfile_format: {} ttisgmtcnt: {} ttisstdcnt: {} leapcnt: {} timecnt: {} typecnt: {} charcnt: {}".format(tzfile_magic, tzfile_format, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt, typecnt, charcnt))

    # Make sure it is a tzfile(5) file
    assert tzfile_magic == TZFILE_MAGIC, (
            "Not a tzfile; file magic was: '{}'".format(tzfile_magic))

    # comments below show struct codes such as "l" for 32-bit long integer
    offset = (timecnt*4  # transition times, each "l"
        + timecnt*1  # indices tying transition time to ttinfo values, each "B"
        + typecnt*6  # ttinfo structs, each stored as "lBB"
        + charcnt*1)  # timezone abbreviation chars, each "c"

    f.seek(offset, 1) # seek offset bytes from current position

    fmt = '>{}l'.format(leapcnt*2)
    #print("DEBUG: leapcnt: {}  fmt: '{}'".format(leapcnt, fmt))
    size = struct.calcsize(fmt)
    data = struct.unpack(fmt, f.read(size))

    lst = [(data[i], data[i+1]) for i in range(0, len(data), 2)]
    assert all(lst[i][0] < lst[i+1][0] for i in range(len(lst)-1))
    assert all(lst[i][1] == lst[i+1][1]-1 for i in range(len(lst)-1))

    return lst

def print_leaps(leap_lst):
    # leap_lst is tuples: (timestamp, num_leap_seconds)
    for ts, num_secs in leap_lst:
        print(datetime.datetime.utcfromtimestamp(ts - num_secs+1))

if __name__ == '__main__':
    import os
    zoneinfo_fname = '/usr/share/zoneinfo/right/UTC'
    with open(zoneinfo_fname, 'rb') as f:
        leap_lst = leap_seconds(f)
    print_leaps(leap_lst)

rawDescription: Extract historic leap seconds from tzdata


code:
class ProductFilter(django_filters.FilterSet):
    nameprice = NamePriceFilter()

    class Meta:
        model = Product
        fields = ['nameprice']

rawDescription: Altering django-filter default behaviour


code:
condition = np.zeros_like(A, dtype='bool')
condition[0:2, 0:1] = (A[0:2, 0:1] % 2 ==0)

rawDescription: Search a Numpy Array based on array index


code:
def loadIO(buffer, **kwds):
    """load an object that was stored with dill.temp.dumpIO

    buffer: buffer object

    >>> dumpfile = dill.temp.dumpIO([1, 2, 3, 4, 5])
    >>> dill.temp.loadIO(dumpfile)
    [1, 2, 3, 4, 5]
    """
    import dill as pickle
    if PY3:
        from io import BytesIO as StringIO
    else:
        from StringIO import StringIO
    value = getattr(buffer, 'getvalue', buffer) # value or buffer.getvalue
    if value != buffer: value = value() # buffer.getvalue()
    return pickle.load(StringIO(value))

def dumpIO(object, **kwds):
    """dill.dump of object to a buffer.
Loads with "dill.temp.loadIO".  Returns the buffer object.

    >>> dumpfile = dill.temp.dumpIO([1, 2, 3, 4, 5])
    >>> dill.temp.loadIO(dumpfile)
    [1, 2, 3, 4, 5]
    """
    import dill as pickle
    if PY3:
        from io import BytesIO as StringIO
    else:
        from StringIO import StringIO
    file = StringIO()
    pickle.dump(object, file)
    file.flush()
    return file

rawDescription: Pickle data with a persistent_id to a binary object (dumps and loads)


code:
with open("filename", 'rt', encoding="utf8") as infile:
    text = infile.read()

text = text[:20] + 'inserted text' + text[20:]

with open("filename", 'wt', encoding="utf8") as outfile:
    outfile.write(text)

rawDescription: python open() function issue

description: Python open() function issue


code:
import glob, os, shutil

files = glob.iglob(os.path.join(source_dir, "*.ext"))
for file in files:
    if os.path.isfile(file):
        shutil.copy2(file, dest_dir)

rawDescription: How do I copy files with specific file extension to a folder in my python (version 2.5) script?

description: Copy files with specific file extension to a folder in my python (version 2.5) script


code:
from statsmodels.discrete.discrete_model import Logit
import numpy as np
np.random.seed(42)

n, d = 20, 10
y = np.random.randint(2, size=n)
X = np.random.rand(n, d)

res = Logit(y, X).fit()

did_converge = res.mle_retvals["converged"]

rawDescription: statsmodels.api convergence failure

description: Statsmodels.api convergence failure


code:
from collections import defaultdict

g = {0:[(1,5),(2,3)],1:[(2,2)]}
r = defaultdict(list)

for origin, targets in g.iteritems():
    for target, weight in targets:
        r[target].append((origin, weight))

rawDescription: Reversing edges in a digraph

description: Reversing edges in a digraph


code: plt.plot(rels.index, rels.AAPL)

rawDescription: Convert a timestamp to date and plot() equivilant in matplotlib


code:
my_return.addStep(ShellCommand(command=["qmake", "{0}.pro".format(pro_name)],
                               env={'PATH': [qt_path, "${PATH}"]}))

rawDescription: How do I append to the PATH environment variable for a BuildBot ShellCommand

description: Append to the PATH environment variable for a BuildBot ShellCommand


code:
import itertools

for args in itertools.product(param_1, param_2, param_3, param_4):
    do_something(*args)

rawDescription: Python avoid multiple nested loops

description: Python avoid multiple nested loops


code:
import dis
def f(): return 7.0

def g(): return float(7)

dis.dis(f)
dis.dis(g)

rawDescription: Is it less computationally intensive to use 7.0 or float(7) in Python?


code:
@app.before_request
def log_request_info():
    app.logger.debug('Headers: %s', request.headers)
    app.logger.debug('Body: %s', request.get_data())

rawDescription: How can I log request POST body in Flask?

description: Log request POST body in Flask


rawDescription: Stop a program before it uses too much memory


code:
# forms.py
class LBooleanVForm(Form):
    def __init__(self,LTV, *args, **kwargs):
        super(LBooleanVForm, self).__init__(*args, **kwargs)
        self.fields[LTV.name] = BooleanField()

class LFloatVForm(Form):
    def __init__(self,LTV, *args, **kwargs):
        super(LFloatVForm, self).__init__(*args, **kwargs)
        self.fields[LTV.name] = FloatField()

class LTextVForm(Form):
    def __init__(self,LTV, *args, **kwargs):
        super(LTextVForm, self).__init__(*args, **kwargs)
        self.fields[LTV.name] = TextInput()

class LDateVForm(Form):
    def __init__(self,LTV, *args, **kwargs):
        super(LDateVForm, self).__init__(*args, **kwargs)
        self.fields[LTV.name] = DateField()

# views.py
ltv = LV.objects.filter(l_t=lt)
lvForm = []
for ltVars in ltv:
    if ltVars.type == 'bool':
        newField = LetterBooleanVariableForm(ltVars)
    elif ltVars.type == 'date':
        newField = LetterDateVariableForm(ltVars)
    elif ltVars.type == 'float':
        newField = LetterFloatVariableForm(ltVars)
    elif ltVars.type == 'text':
        newField = LetterTextVariableForm(ltVars)
    else:
        raise Http404
    lvForm.append(newField)

rawDescription: Changing form elements names and id's

description: Changing form elements names and id's


code:
# -*- coding: utf-8 -*-
from subprocess import PIPE, Popen
import fcntl
import os
import select
import sys

proc = Popen(['wget', 'http://speedtest.london.linode.com/100MB-london.bin'], stdin = PIPE, stderr = PIPE, stdout = PIPE)

while proc.poll() == None:
    fcntl.fcntl(
            proc.stderr.fileno(),
            fcntl.F_SETFL,
            fcntl.fcntl(proc.stderr.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK,
            )

    buf = ''
    while proc.poll() == None:
        readx_err = select.select([proc.stderr.fileno()], [], [], 0.1)[0]
        if readx_err:
            chunk = proc.stderr.read().decode('utf-8')
            buf += chunk
            if '\n' in buf and '%' in buf and '.' in buf:
                print (buf.strip().split())
                buf = ''
        else:
            break
proc.wait()

rawDescription: How to get wget command info with Python?

description: Get wget command info with Python


code:
class Hidden(object):
  __hidden = False

dir(Hidden)

rawDescription: Access local classvariable from inherited instance


code:
strs = '85033ba6c'
re.sub(r'[A-Za-z]',lambda m:m.group(0).upper(),strs,1)

rawDescription: Capitalize first letter in string if first character is not letter?


code:
class Student(models.Model):
    name = models.CharField(max_length=50)
    birth_date = models.DateField()
    std_ID_card = models.IntegerField()
    group = models.ForeignKey('Group')

class Group(models.Model):
    group_name = models.CharField(max_length=50)
    captain = models.ForeignKey('Student', related_name='%(class)s_captain')

rawDescription: Interconnected ForegnKey

description: Interconnected ForegnKey


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

df = pd.DataFrame({'color': ['blue','blue','yellow','blue','yellow'], 'area': [2,2,3,4,4]})
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2,2)
#Hide upper left corner plot and create two new subplots
ax1.axis('off')
ax = fig.add_subplot(2,4,1)
ax0 = fig.add_subplot(2,4,2)
#Plot
ax3.plot([[2,2], [3,6]])
ax4.plot([[3,6], [2,2]])
df.area.hist(by=df.color, ax=(ax,ax0)) #Pass both new subplots

rawDescription: How to plot in a specific axis with DataFrame.hist(by=) in pandas

description: Plot in a specific axis with DataFrame.hist(by=) in pandas


code: df.groupby('Session#')['Outcome'].apply(lambda x: (x == 'Correct').sum()/len(x))

rawDescription: Conditional Sum/Average/etc... CSV file in Python


code:
from functools import wraps

def convert_orc(f):
    @wraps(f)
    def wrapper(self, opponent, *args, **kwargs):
        if isinstance(Snaga, orc):
            raise DeprecationWarning(...)
            return f(self, convert_to_urukhai(opponent), *args, **kwargs)
        else:
            return f(self, opponent, *args, **kwargs)
    return wrapper

class Warrior():
    @convert_orc
    def slash_orc(self, opponent, sword, shield):
       ...

    @convert_orc
    def hack_orc(self, opponent, warhammer):
       ...

rawDescription: Modifying call arguments of multiple methods in class


code:
word_list = {'hi' : 'test', 'how' : 'teddy'}

with open("document.txt") as main:
    with open('done.txt', 'w') as new_main:
        input_data = main.read()
        for key, value in word_list.iteritems():
            input_data = input_data.replace(key, value)

        new_main.write(input_data)

rawDescription: Python replace string in text file with value from list


code:
dest = "C:/Test2.csv"
with open(dest,'w') as f:
    writer = csv.writer(f)
    writer.writerows(sort)

rawDescription: Sorting excel data using more than 1 column


rawDescription: Renaming values in pandas

description: Renaming values in pandas


code:
import subprocess

PIPE = subprocess.PIPE
pd = subprocess.Popen(['/usr/bin/zip', '-r', 'files', 'files'],
                      stdout=PIPE, stderr=PIPE)
stdout, stderr = pd.communicate()

rawDescription: Better way to zip files in Python (zip a whole directory with a single command)?


code:
rain = 0
snow = 1
M[rain, snow]

rawDescription: getting matrix element using dictionary-like index in Python

description: Getting matrix element using dictionary-like index in Python


code:
from collections import defaultdict
d = defaultdict(dict)
for line in open('input_file','r'):
    line = line.strip()
    a,b = line.split(',')
    node = a.split('=')[1]
    key, value = b.split('=')
    d[node][key] = value

rawDescription: How can I create a dictionary in python from a txt file?

description: Create a dictionary in python from a txt file


code:
def log(msg):
  if DEBUG:
    logger.log(msg)

rawDescription: Improving python code

description: Improving python code


code:
evens = []
odds = []

amt = int(input("prompt"))

while (amt != -1):
    if amt % 2 == 0: # even
        evens.append(amt)
    else:
        odds.append(amt)
    amt = int(input("prompt"))

print("odds: " + str(float(sum(odds)) / len(odds)))
print("evens: " + str(float(sum(evens)) / len(evens)))

rawDescription: Even Odd Separate Average Python 3.4

description: Even Odd Separate Average Python 3.4


code:
s = aliased(Tags)
e = aliased(Tags)
sr = aliased(R_Incident_Tags)
er = aliased(R_Incident_Tags)

qry = (session.query(s.name, e.name, func.count(e.name)).
        select_from(s, e, sr, er).
        filter(s.category=='service').
        filter(e.category=='event').
        filter(e.uid == er.tag_uid).
        filter(s.uid == sr.tag_uid).
        filter(er.incident_uid == sr.incident_uid).
        group_by(s.name, e.name)
        )

rawDescription: SQLAlchemy: Converting Self-Ref JOIN, COUNT, GROUP BY SELECT


code:
from bs4 import BeautifulSoup

content='
Hello, the web site is Google
.
The search engine is Baidu
.'
soup = BeautifulSoup(content, 'html.parser')

# find all `a`
all_a = soup.findAll('a')

for a in all_a:
    # find `href` in `a`
    href = a['href']

    #print('--- before ---')
    #print(soup)

    # add `href` to `previousSibling`
    a.previousSibling.replaceWith(a.previousSibling + href)

    # remove `a`
    a.extract()

    #print('--- after ---')
    #print(soup)

print(soup)

'
Hello, the web site is https://www.google.com
.
The search engine is https://www.baidu.com
.'

rawDescription: Replace <a> </a> with href in BeautifulSoup


code:
list(itertools.combinations(['a', 'b', 'c', 'd'], 2))
list(itertools.combinations(['a', 'b', 'c', 'd'], 3))

rawDescription: finding all combinations of a list of any count

description: Finding all combinations of a list of any count


code:
import math
10**math.floor(math.log10(.009))
10**math.floor(math.log10(.06))
10**math.floor(math.log10(1234))

rawDescription: need a function for determing the scale of a value

description: Need a function for determing the scale of a value


code:
class Base:
    def __init__(self):
        self.x = 'Base'

    @classmethod
    def foo(cls):
        return 'ball'

    def __str__(self):
        return self.x

rawDescription: How do I call a method when I have not defined a variable name?

description: Call a method when I have not defined a variable name


code:
import zipfile, lxml.etree

# open zipfile
zf = zipfile.ZipFile('my_doc.docx')
# use lxml to parse the xml file we are interested in
doc = lxml.etree.fromstring(zf.read('docProps/core.xml'))
# retrieve creator
ns={'dc': 'http://purl.org/dc/elements/1.1/'}
creator = doc.xpath('//dc:creator', namespaces=ns)[0].text

rawDescription: Python: How to Modify metadata of Microsoft Office files?


code:
APPS = [
    'django.contrib.auth',
    # ...
]

MY_APPS = [
    'myapp1',
    # ...
]

INSTALLED_APPS = APPS + MY_APPS

rawDescription: Get a List of Project Specific Apps in Django


code:
import re
re.sub(r'!|\?|,', '', text)

rawDescription: Python - Shortest way to format a string to an url


code:
X = np.random.randn(3, 4)
lr = LogisticRegression()
X = np.random.randn(3, 4)
y = [1, 0, 0]
lr.fit(X, y)
lr.predict_proba(X[0])

rawDescription: How do I apply scikit-learn's LogisticRegression for some decimal data?

description: Apply scikit-learn's LogisticRegression for some decimal data


code:
import multiprocessing as mp
import time

def slow_func():
    while True:
        for i in xrange(99999):
            j = i*i

def main():
    num_processes = 4

    for _ in range(num_processes):
            process = mp.Process(target = slow_func)
            process.daemon = True
            process.start()

    while True:
        time.sleep(1)

if __name__ == '__main__':
    main()

rawDescription: How to fully take advantage of multi-cores by python

description: Fully take advantage of multi-cores by python


code:
import sys
import Image, ImageDraw, ImageFont

# Assumption: some other piece of code separates the data in the following
# format.
line1 = [("Pos.  :", 0), ("123456789012345", 0)]
line2 = [("Name. :", 0), ("ABCDEFGHIJKLMNO", 0)]
line3 = [("Str.  ", 0), (":", -0.5), ("SOMESTRINGSOMEST", -0.5)]
line4 = [("Wave 1:", 0), ("_XXXX_X____X_X_", 0)]
line5 = [("Wave 2:", 0), ("__XX_XXX_X__X_X", 0)]
line_data = [line1, line2, line3, line4, line5]
# Texts to draw over the last element, in specific positions,
# of lines present in line_data.
subscript = {
        2: { # Meaning: third item in line_data
            0: "170",  # Meaning: draw "170" over the first char
            len(line3[-1][0]) - 1: "185", # Draw "185" over the last char
            7: "180",   # Meaning: draw "180" over the eight char
           },
        4: {5: "hi"},
        3: {6: "ops"}
        }

# If the following fonts are not mono spaced, you are going to suffer.
#
# Normal font.
font = ImageFont.truetype('FreeMono.ttf', 40)
# Font for subscript.
font_tiny = ImageFont.truetype('FreeMono.ttf', 20)

im = Image.new("RGBA", (1000, 1000), 'white')
draw = ImageDraw.Draw(im)
line_offset = 4
start_y = 6

width_A, height_A = font.getsize('A')
_, height_tiny_A = font_tiny.getsize('A')

# Collect even columns from the last item of list line1.
even_columns = []
x = 0
for i, (text, _) in enumerate(line1):
    for j, letter in enumerate(text):
        if i == len(line1) - 1 and not j % 2:
            even_columns.append(x)
        x += width_A

# Write all lines.
width = 0
l_start_y = start_y
for di, data in enumerate(line_data):
    x = 0
    for i, (text, xoff) in enumerate(data):
        for j, letter in enumerate(text):
            # Apply x offset.
            extra = width_A * xoff
            draw.text((x + extra, l_start_y), letter, font=font, fill='black')
            x += width_A
    width = max(x, width)
    l_start_y += height_A + line_offset

# Collect letter positions from the lines that will have subscripts.
letter_pos = {}
for k in subscript:
    letter_pos[k] = {}
    x = sum(len(text) for text, _ in line_data[k][:-1]) * width_A
    text, xoff = line_data[k][-1]
    for i in range(len(text)):
        extra = width_A * xoff
        letter_pos[k][i] = x + extra
        x += width_A
# Write all subscripts.
for k, v in subscript.items():
    line = line_data[k]
    for pos, text in v.items():
        x = letter_pos[k][pos]
        y = start_y + (line_offset + height_A) * k
        y -= height_tiny_A * 0.4 # XXX A poor heuristic that worked here.
        draw.text((x, y), text, font=font_tiny, fill='black')
        width = max(width, int(x + font_tiny.getsize(text)[0]))

# Draw grey columns.
columns = Image.new(im.mode, im.size, 'white')
mask = Image.new("L", im.size, 'white')
for x in even_columns:
    columns.paste((128, 128, 128), (x, line_offset, x + width_A, l_start_y))
    mask.paste(164, (x, line_offset, x + width_A, l_start_y), )
im = Image.composite(im, columns, mask)

# Crop and save the resulting image.
im.crop((0, 0, width, l_start_y + 2)).save(sys.argv[1])

rawDescription: How can i format Text in python like i would in Illustrator?

description: Format Text in python like i would in Illustrator


code:
parallel_coordinates(data[['postcode','2005','2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015']], 'postcode')
plt.yscale('log') ## <- should be enough to define log scaling on your y-axis here
plt.show()

rawDescription: Adjust axis scaling with pandas parallel_coordinates


code:
import numpy as np
import matplotlib.pyplot as plt
from mpldatacursor import HighlightingDataCursor, DataCursor

def main():
    fig, axes = plt.subplots(nrows=2, ncols=2)
    for ax, marker in zip(axes.flat, ['o', '^', 's', '*']):
        x, y = np.random.random((2,20))
        ax.plot(x, y, ls='', marker=marker)
    IndexedHighlight(axes.flat, point_labels=[str(i) for i in range(20)])
    plt.show()

class IndexedHighlight(HighlightingDataCursor):
    def __init__(self, axes, **kwargs):
        # Use the first plotted Line2D in each axes
        artists = [ax.lines[0] for ax in axes]

        kwargs['display'] = 'single'
        HighlightingDataCursor.__init__(self, artists, **kwargs)
        self.highlights = [self.create_highlight(artist) for artist in artists]
        plt.setp(self.highlights, visible=False)

    def update(self, event, annotation):
        # Hide all other annotations
        plt.setp(self.highlights, visible=False)

        # Highlight everything with the same index.
        artist, ind = event.artist, event.ind
        for original, highlight in zip(self.artists, self.highlights):
            x, y = original.get_data()
            highlight.set(visible=True, xdata=x[ind], ydata=y[ind])
        DataCursor.update(self, event, annotation)

main()

rawDescription: How to pick a point in a subplot and highlight it in adjacent subplots in matplotlib(extension to region of points)

description: Pick a point in a subplot and highlight it in adjacent subplots in matplotlib(extension to region of points)


code:
app = QtGui.QApplication(sys.argv)

translator = QtCore.QTranslator(app)
locale = QtCore.QLocale.system().name()
path = QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)
translator.load('qt_%s' % locale, path)
app.installTranslator(translator)

rawDescription: QMessageBox change text of standard button


code: np.genfromtxt(" ".join(ln.split()[N:]) for ln in f)

rawDescription: Skip a specified number of columns with numpy.genfromtxt()


code:
filename = 'where your data lives'
with open(filename, 'rb') as f:
   encoded_data = f.read()
decoded_data = encoded_data.decode("UTF16")

# do stuff, resulting in result (all on unicode strings)
result = text_to_json(decoded_data)

encoded_result = result.encode("UTF-16")  #really, just using UTF8 for everything makes things a lot easier
outfile = 'where your data goes'
with open(outfile, 'wb') as f:
    f.write(encoded_result)

rawDescription: Encoding issue when writing to text file, with Python


rawDescription: URL encoding for Python OAuth2

description: URL encoding for Python OAuth2


rawDescription: Python - Deleting the first 2 lines of a string


code:
import collections

def cut(dict_, maxdepth, replaced_with=None):
    """Cuts the dictionary at the specified depth.

    If maxdepth is n, then only n levels of keys are kept.
    """
    queue = collections.deque([(dict_, 0)])

    # invariant: every entry in the queue is a dictionary
    while queue:
        parent, depth = queue.popleft()
        for key, child in parent.items():
            if isinstance(child, dict):
                if depth == maxdepth - 1:
                    parent[key] = replaced_with
                else:
                    queue.append((child, depth+1))

rawDescription: How to cut a very "deep" json or dictionary in Python?

description: Cut a very "deep" json or dictionary in Python


code:
import xlrd, xlwt
from xlutils.copy import copy

rb = xlrd.open_workbook("Path/To/Doc", formatting_info=True) #Make Readable Copy
wb = copy(rb) #Make Writeable Copy

ws1 = wb.get_sheet(1) #Get sheet 1 in writeable copy
ws1.write(1, 11, 'test') #Write 'test' to cell (1, 11)

ws2 = wb.get_sheet(2) #Get sheet 2 in writeable copy
ws2.write(3, 14, '135') #Write '135' to cell (3, 14)

wb.save("New/File/Path") #Save the newly written copy. Enter the same as the old path to write over

rawDescription: Easy way to fill in an Excel file with Python


code:
from fpdf import FPDF
import webbrowser

pdf=FPDF()
pdf.add_page()
pdf.set_font('Arial','B',16)

# Save top coordinate
top = pdf.y

# Calculate x position of next cell
offset = pdf.x + 40

pdf.multi_cell(40,10,'Hello World!,how are you today',1,0)

# Reset y coordinate
pdf.y = top

# Move to computed offset
pdf.x = offset

pdf.multi_cell(100,10,'This cell needs to beside the other',1,0)

pdf.output('tuto1.pdf','F')

webbrowser.open_new('tuto1.pdf')

rawDescription: How to get MultiCells in Pyfpdf Side by side?

description: Get MultiCells in Pyfpdf Side by side


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

x = np.linspace(0,10,100)
y = np.random.random(100)
y2 = np.random.random(100)

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.scatter(x,y)
ax1.annotate("$C_{3}H_{8}$", xy=(0.9,0.9),xycoords='axes fraction',
             fontsize=14)

ax2 = fig.add_subplot(212)
ax2.scatter(x,y2)
ax2.annotate("$CO_{2}$", xy=(0.9,0.9),xycoords='axes fraction',
             fontsize=14)

fig.show()

rawDescription: How to make a legend with only text

description: Make a legend with only text


code:
import urllib2
req = urllib2.Request('http://www.example.com/', data="abc", headers={'Content-type': 'text/plain'})
r = urllib2.urlopen(req)

rawDescription: Python urllib post with different content type than urlencoded


rawDescription: Turn on namespace mode with Python xml.sax


code:
class Category(models.Model):
    ...

    @property
    def image(self):
        return self.photo or u'DEFAULT_PIC'

# usage
category.image

rawDescription: can django ORM handle conditional mysql statements

description: Can django ORM handle conditional mysql statements


code: conn.execute(Product.insert(), [dict(name=name) for name in names])

rawDescription: How to bulk insert data to mysql with python

description: Bulk insert data to mysql with python


code:
from eve import Eve
app = Eve()

@app.route("/x")
def hello():
    return "Hello World!"

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

rawDescription: EVE - define custom flask controllers

description: EVE - define custom flask controllers


code:
sql.execute("INSERT OR IGNORE INTO foo(data) VALUES(?);" ("Some text.", ))
last_row_id = sql.execute("SELECT id FROM foo WHERE data = ?;" ("Some text. ", ))

rawDescription: SQLite insert or ignore and return original _rowid_


code:
filename = filechooserdialog.get_filename()
if not filename.endswith('.xyz'):
    filename += '.xyz'

rawDescription: pygtk : saving the project file with suffix ".xyz"

description: Pygtk : saving the project file with suffix ".xyz"


code: subchild = root.find('child/subchild')

rawDescription: Python object wrapper for lxml etree?

description: Python object wrapper for lxml etree


code: new_adj = [x for x in adj if gx.d[x][2] == 'white']

rawDescription: Python list remove and iterating over a list


code: maximum = max(data[0] for data in dic.values())

rawDescription: Max/Min value of Dictionary of List

description: Max/Min value of Dictionary of List


code:
import time
now = time.time()
...
later = time.time()
difference = int(later - now)

rawDescription: find time difference in seconds as an integer with python

description: Find time difference in seconds as an integer with python


code:
assert_that(obj.exportToDict(), has_entries(
                                    { 'state': 2347,
                                      'neighbours': contains_inanyorder(1,2,3) }))

rawDescription: Python unittest - asserting dictionary with lists


code: new_arr = np.where(second == 0, first, second)

rawDescription: Numpy combine all nonzero elements of one array in to another


code:
def reposetup(ui, repo):
    # ...

    class bookmark_repo(repo.__class__):
        def rollback(self):
            if os.path.exists(self.join('undo.bookmarks')):
                util.rename(self.join('undo.bookmarks'), self.join('bookmarks'))
            return super(bookmark_repo, self).rollback()

        # ...

    repo.__class__ = bookmark_repo

rawDescription: Reclassing an instance in Python

description: Reclassing an instance in Python


code: z = [a+b for a,b in zip(x,y)]

rawDescription: How to add integers from one list to another in ascending order?

description: Add integers from one list to another in ascending order


code:
my_dict = {}
for list in lists:
  my_dict[list[0]] = list[:]

rawDescription: Create dictionary from list python

description: Create dictionary from list python


code:
import bisect

class mystore:
    def __init__(self, constructor):
        self.store = []
        self.constructor = constructor
        self.empty = constructor()

    def __getitem__(self, key):
        i, k = self.lookup(key)
        if k == key:
            return v
        # key not present, create a new item for this key.
        value = self.constructor()
        self.store.insert(i, (key, value))
        return value

    def __setitem__(self, key, value):
        i, k = self.lookup(key)
        if k == key:
            self.store[i] = (key, value)
        else:
            self.store.insert(i, (key, value))

    def lookup(self, key):
        i = bisect.bisect(self.store, (key, self.empty))
        if 0 <= i < len(self.store):
            return i, self.store[i][0]
        return i, None

if __name__ == '__main__':
    s = mystore(set)
    s['a'] = set(['1'])
    print(s.store)
    s['b']
    print(s.store)
    s['a'] = set(['2'])
    print(s.store)

rawDescription: Python defaultdict for large data sets

description: Python defaultdict for large data sets


code:
name = StringField(
    'Name',
    validators = [Optional(), Length(max = 100)],
    filters = [lambda x: x or None]
)

rawDescription: Get None from a Fields data in instead of an empty string


code:
import socket

def mysend(sock, msg):
    totalsent = 0
    while totalsent < MSGLEN:
        sent = sock.send(msg[totalsent:])
        if sent == 0:
            raise RuntimeError("socket connection broken")
        totalsent = totalsent + sent

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect(("where ever you have your other computer", "port number"))

i = 2
mysend(s, str(i))

rawDescription: Easiest Way to Transfer Data Over the Internet, Python


code:
import matplotlib.pyplot as plt
import seaborn as sns

# Set style
sns.set(style="whitegrid", color_codes=True)

# Load some sample data
titanic = sns.load_dataset("titanic")

# Make the barplot
bar = sns.barplot(x="sex", y="survived", hue="class", data=titanic);

# Define some hatches
hatches = ['-', '+', 'x', '\\', '*', 'o']

# Loop over the bars
for i,thisbar in enumerate(bar.patches):
    # Set a different hatch for each bar
    thisbar.set_hatch(hatches[i])

plt.show()

rawDescription: Is it possible to add hatches to each individual bar in seaborn.barplot?


code:
import numpy as np
v1 = np.array([23, 20, 13, 24, 25, 28, 26, 17, 18, 29])
v2 = np.array([37, 46, 41, 40, 40, 39, 43, 42, 45, 56])
v3 = np.array([101, 120, 110, 140])

def myfilter(v1, v2, v3): # how I would parse your "DataClass" code
    valid_ixs = (v1 >= 20) & (v2 >= 40) & (v2 <= 45)
    if any(valid_ixs): # could also use valid_ixs.sum()
        return v3[v3 > 115]
    return v3
print(myfilter(v1, v2, v3))

# what you're doing in python
v1 = v1[v1 >= 20]
v2 = v2[(v2 >= 40) & (v2 <= 45)]
v3 = v3[v3 > 115] if v1 else v3

rawDescription: Is there a language in Python that can be used to implement logical data cuts?


code:
idx = pd.IndexSlice
df.loc[idx[:, :, 'C1', :],:]

rawDescription: "Too many indexers" with DataFrame.loc

description: "Too many indexers" with DataFrame.loc


code:
import time, multiprocessing

class Test(multiprocessing.Process):
    def __init__(self, manager):
        super().__init__()
        self.quit = manager.Event()
        self.dict = manager.dict()

    def stop(self):
        self.quit.set()
        self.join()

    def run(self):
        self.dict['item'] = 0
        while not self.quit.is_set():
            time.sleep(1)
            self.dict['item'] += 1

m = multiprocessing.Manager()
t = Test(m)
t.start()
for x in range(10):
    time.sleep(1.2)
    print(t.dict)
t.stop()

rawDescription: How to share object tree with process fork?

description: Share object tree with process fork


code:
class Server(protocol.Protocol):
    clients = set()

    def dataReceived(self, data):
        #do something on the server side
        pass

    def connectionMade(self):
        Server.clients.add(self)

    def connectionLost(self):
        Server.clients.remove(self)

    @classmethod
    def message(cls):
        for client in cls.clients:
            client.transport.write('got GET request\n')

rawDescription: Controlling Twisted based server from a web interface?


code:
#!/usr/bin/env python

import matplotlib
matplotlib.use('TkAgg')

from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
# implement the default mpl key bindings
from matplotlib.backend_bases import key_press_handler

from matplotlib.figure import Figure

import sys
if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk

root = Tk.Tk()
root.wm_title("Embedding in TK")

f = Figure(figsize=(5,4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0,3.0,0.01)
s = sin(2*pi*t)

a.plot(t,s)

# a tk.DrawingArea
canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

toolbar = NavigationToolbar2TkAgg( canvas, root )
toolbar.update()
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

def on_key_event(event):
    print('you pressed %s'%event.key)
    key_press_handler(event, canvas, toolbar)

canvas.mpl_connect('key_press_event', on_key_event)

def _quit():
    root.quit()     # stops mainloop
    root.destroy()  # this is necessary on Windows to prevent
                    # Fatal Python Error: PyEval_RestoreThread: NULL tstate

button = Tk.Button(master=root, text='Quit', command=_quit)
button.pack(side=Tk.BOTTOM)

Tk.mainloop()

rawDescription: Matplotlib output in Tkinter

description: Matplotlib output in Tkinter


code:
import seaborn as sns
sns.lmplot(x='one',y='two',data=df,fit_reg=True)

rawDescription: Can I draw a regression line and show parameters using scatterplot with a pandas dataframe?

description: Draw a regression line and show parameters using scatterplot with a pandas dataframe


code:
upsized = np.zeros([7, 7])
upsized[:5, :5] = a

rawDescription: numpy.resize() rearanging instead of resizing?

description: Numpy.resize() rearanging instead of resizing


code:
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

# Create server
server = SimpleXMLRPCServer(("localhost", 8000),
                            requestHandler=RequestHandler)
server.register_introspection_functions()

# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)

# Register a function under a different name
def adder_function(x,y):
    return x + y
server.register_function(adder_function, 'add')

# Register an instance; all the methods of the instance are
# published as XML-RPC methods (in this case, just 'div').
class MyFuncs:
    def div(self, x, y):
        return x // y

server.register_instance(MyFuncs())

# Run the server's main loop
server.serve_forever()

rawDescription: Is there a proper way to use Python code from PHP?


code:
import boto.ec2.autoscale
region = 'ap-southeast-2'
conn = boto.ec2.autoscale.connect_to_region(region, aws_access_key_id="<access_key", aws_secret_access_key="<secret_key>")
mygroups = conn.get_all_groups()
...

rawDescription: Python and boto with autoscaling -- How to connect to a region


code:
L0 = {}
L1 = {}
for net, cells in FP['NetC'].items(): # use .iteritems() if you're using Python 2
    L0[net] = {}
    L1[net] = {}
    for cell in cells:
        L0[net][cell] = FP['CellD_NM'][cell]['X0']
        L1[net][cell] = FP['CellD_NM'][cell]['X1']

rawDescription: Sorting two hashes into one in Python

description: Sorting two hashes into one in Python


code:
logcat_process = subprocess.Popen('adb logcat -v time > logcat.log', shell=True)
time.sleep(5)

save_stdout = sys.stdout
sys.stdout = open(r'/youlib..../trash.txt', 'w')

os.kill((logcat_process.pid)+1, signal.SIGKILL)

# regain stdout to screen
sys.stdout.close()
sys.stdout = save_stdout

rawDescription: Python - How to hide output after killed specified process


code:
import facebook
import requests
import json
import urllib
import urllib2

#def some_action(post):
    #print posts['data']
 #   print(post['created_time'])

access_token = 'ENTER ACCESS TOKEN'
url = 'https://graph.facebook.com/v2.4/ENTER FACEBOOK USERNAME/IDNUMBER FOLLOWED BY ?fields=posts.since(1406851200).limit(50)%7Bcreated_time%2Cmessage%2Ccomments.limit(2000)%7Bcreated_time%2Cmessage%7D%7D&access_token='

html = url + access_token

data = json.load(urllib2.urlopen(html))
with open('penguin.txt', 'w') as textfile:
    json.dump(data, textfile)

rawDescription: Pull comments from Facebook API (Python, JSON)


code:
import re
fileData = [] #data from file.txt parsed through regex

with open("file.txt") as f:
    for line in f:
        regExp = re.match(r"(\d+)\s+(\d+)\s(\d+)", line)  #extracts data from row in file
        fileData.append((int(regExp.group(1)), int(regExp.group(2)), int(regExp.group(3)))) #make 2-d list of data
maxIndex = max(fileData, key=lambda x: x[0])[0] #biggest index in the list (5 in this case)

finaList = [] #the list where your output will be stored
for i in range(1, maxIndex+1): #you example output showed a 1-indexed dict
    thisDict = {} #start with empty dict
    for item in fileData:
        if item[0] == i:
            thisDict[item[1]] = item[2] #for every item with same index as this dict, add new key-value to dict
    finaList.append(thisDict) #add this dict to output list

print(finaList)

rawDescription: Modifying a dictionary contained within a list


code:
from django.db import connection, models

class MyManager(Manager):
    def raw_as_qs(self, raw_query, params=()):
        """Execute a raw query and return a QuerySet.  The first column in the
        result set must be the id field for the model.
        :type raw_query: str | unicode
        :type params: tuple[T] | dict[str | unicode, T]
        :rtype: django.db.models.query.QuerySet
        """
        cursor = connection.cursor()
        try:
            cursor.execute(raw_query, params)
            return self.filter(id__in=(x[0] for x in cursor))
        finally:
            cursor.close()

class MyModel(models.Model):
    objects = MyManager()

rawDescription: Unions and intersections of RawQuerySets and QuerySets in Django


code:
shutdown_mode=False

def alarm_handler(signum, frame):
        sys.exit(0)

def sigterm_handler(signum):
     global shutdown_mode
     if not shutdown_mode:
            shutdown_mode=True
            signal.signal(signal.SIGALRM, alarm_handler)
            signal.alarm(10)

rawDescription: Python: Override default SIGTERM handler


code: f = open(file, 'a').write(what)

rawDescription: Writing to a specific row without overwriting others


code:
for i in range(11):
    box = locals().get('box' + str(i))
    if box is not None:
        boxes.append(box)

rawDescription: Append series of items to list with similar names in Python


code:
islands = [False, False, False, True, True, False, False, False, True, True, True, False]
islands_starts = [v[0]+1 for v in list(enumerate(zip(islands, islands[1:]))) if v[1] == (False, True)]
#[3, 8]
islands_ends = [v[0] for v in list(enumerate(zip(islands, islands[1:]))) if v[1] == (True, False)]
#[4, 10]
separated_islands = [[False if p not in range(i[0],i[1]+1) else True for p in range(0,len(islands))] for i in zip(islands_starts,islands_ends)]
#[[False, False, False, True, True, False, False, False, False, False, False, False],
#[False, False, False, False, False, False, False, False, True, True, True, False]]

rawDescription: getting rid of loops

description: Getting rid of loops


rawDescription: Is there a way to tell where your python file is?


code:
from alembic import op
import sqlalchemy as sa

old_options = ('nonexistent_executable', 'signal', 'success', 'timed_out')
new_options = sorted(old_options + ('output_limit_exceeded',))

old_type = sa.Enum(*old_options, name='status')
new_type = sa.Enum(*new_options, name='status')
tmp_type = sa.Enum(*new_options, name='_status')

tcr = sa.sql.table('testcaseresult',
                   sa.Column('status', new_type, nullable=False))

def upgrade():
    # Create a tempoary "_status" type, convert and drop the "old" type
    tmp_type.create(op.get_bind(), checkfirst=False)
    op.execute('ALTER TABLE testcaseresult ALTER COLUMN status TYPE _status'
               ' USING status::text::_status');
    old_type.drop(op.get_bind(), checkfirst=False)
    # Create and convert to the "new" status type
    new_type.create(op.get_bind(), checkfirst=False)
    op.execute('ALTER TABLE testcaseresult ALTER COLUMN status TYPE status'
               ' USING status::text::status');
    tmp_type.drop(op.get_bind(), checkfirst=False)

def downgrade():
    # Convert 'output_limit_exceeded' status into 'timed_out'
    op.execute(tcr.update().where(tcr.c.status==u'output_limit_exceeded')
               .values(status='timed_out'))
    # Create a tempoary "_status" type, convert and drop the "new" type
    tmp_type.create(op.get_bind(), checkfirst=False)
    op.execute('ALTER TABLE testcaseresult ALTER COLUMN status TYPE _status'
               ' USING status::text::_status');
    new_type.drop(op.get_bind(), checkfirst=False)
    # Create and convert to the "old" status type
    old_type.create(op.get_bind(), checkfirst=False)
    op.execute('ALTER TABLE testcaseresult ALTER COLUMN status TYPE status'
               ' USING status::text::status');
    tmp_type.drop(op.get_bind(), checkfirst=False)

rawDescription: Altering an Enum field using Alembic

description: Altering an Enum field using Alembic


code:
import smtplib
from email.mime.text import MIMEText

class GmailHandler():
    """
    IMPORTANT NOTE:
    in order to access a gmail account with this handler,
    your account needs 'foreign-access' enabled (follow these steps):
    login to the account
    go here--> https://accounts.google.com/b/0/DisplayUnlockCaptcha
    press 'Continue'
    Done.
    """

    def __init__(self, gmail, password):
        self.gmail = gmail
        self.password = password

    def send_mail(self, receivers, subject, text):

        if not isinstance(receivers, list):
            receivers = [receivers]

        # Send the message via our own SMTP server, but don't include the envelope header
        smtp = smtplib.SMTP("smtp.gmail.com", 587)
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        smtp.login(self.gmail, self.password)

        for receiver in receivers:

            msg = MIMEText(text)
            msg['Subject'] = subject
            msg['From'] = self.gmail
            msg['To'] = receiver
            smtp.sendmail(self.gmail, receiver, str(msg))

        smtp.quit()

rawDescription: Sending email via Python and Google SMTP server


code:
argument_list = [] #keep this blank, just decalring it for later
fields = ('title') #any fields in your model you'd like to search against
query_string = 'Foo Bar' #search terms, you'll probably populate this from some source

for query in query_string.split(' '):  #breaks query_string into 'Foo' and 'Bar'
    for field in fields:
        argument_list.append( Q(**{field+'__icontains':query_object} ) )

query = Entry.objects.filter( reduce(operator.or_, argument_list) )

# --UPDATE-- here's an args example for completeness

order = ['publish_date','title'] #create a list, possibly from GET or POST data
ordered_query = query.order_by(*orders()) # Yay, you're ordered now!

rawDescription: Constructing Django filter queries dynamically with args and kwargs


rawDescription: Fastest way to generate number like 66666 when the number of digits is given


code: Chi_min = str(min(chi)) or "null"

rawDescription: How to print a 'null' for any of many values that may have no value

description: Print a 'null' for any of many values that may have no value