code:
from datetime import timedelta

def daterange(start_date, end_date):
    for n in range((end_date - start_date).days):
        yield start_date + timedelta(n)

class StatusEntry(models.Model):
    name = models.TextField()
    date = models.DateField()
    status = models.BooleanField()

    def __unicode__(self):
        return "%s - %s - %s" % (self.name, unicode(self.status), unicode(self.date))

    def save(self, fill=True):
        if fill and not self.id: # autofill on insert, not on update
            newest = StatusEntry.objects.all().order_by("-date")[:1]
            if newest and newest[0].date < self.date:
                for date in daterange(newest[0].date + timedelta(1), self.date):
                    entry = StatusEntry(name=self.name, date=date, status=False)
                    entry.save(fill=False)
        super(StatusEntry, self).save()

rawDescription: django auto entry generation

description: Django auto entry generation


code:
import sys
import random
from PyQt4 import QtCore, QtGui

class QCustomTableWidgetItem (QtGui.QTableWidgetItem):
    def __init__ (self, value):
        super(QCustomTableWidgetItem, self).__init__(QtCore.QString('%s' % value))

    def __lt__ (self, other):
        if (isinstance(other, QCustomTableWidgetItem)):
            selfDataValue  = float(self.data(QtCore.Qt.EditRole).toString())
            otherDataValue = float(other.data(QtCore.Qt.EditRole).toString())
            return selfDataValue < otherDataValue
        else:
            return QtGui.QTableWidgetItem.__lt__(self, other)

class QCustomTableWidget (QtGui.QTableWidget):
    def __init__ (self, parent = None):
        super(QCustomTableWidget, self).__init__(parent)
        self.setColumnCount(2)
        self.setRowCount(5)
        for row in range(self.rowCount()):
            self.setItem(row, 0, QCustomTableWidgetItem(random.random() * 1e4))
            self.setItem(row, 1, QtGui.QTableWidgetItem(QtCore.QString(65 + row)))
        self.setSortingEnabled(True)

myQApplication = QtGui.QApplication([])
myQCustomTableWidget = QCustomTableWidget()
myQCustomTableWidget.show()
sys.exit(myQApplication.exec_())

rawDescription: Sorting QTableWidget Items Numerically

description: Sorting QTableWidget Items Numerically


code:
import multiprocessing as mp

instances = [ClassName() for i in range(no_inst)]

def dosomething(inst):
    for data in dataset:
        inst.dosomething(data)

num_procs = 4 #however many processors you'll use
pool = mp.Pool(num_procs)
pool.map(dosomething,instances)

rawDescription: Python: How can i use multiprocessing to speed up operating on class instances?


code:
df1['Start Date'] = pd.DatetimeIndex(df1['Start Date'])
df1.set_index('Start Date', inplace=True)

df2['DATE'] = pd.to_datetime(df2.DATE)
df2.set_index('DATE', inplace=True)

sums = df2.groupby(df1.index.asof).sum()
pd.concat([df1, sums], axis=1)

rawDescription: How to sum specific columns based on dates

description: Sum specific columns based on dates


code:
import urllib2

url = "http://translate.google.com/translate_tts?tl=en&q=text"
request = urllib2.Request(url)
request.add_header('User-agent', 'Mozilla/5.0')
opener = urllib2.build_opener()

f = open("data.mp3", "wb")
f.write(opener.open(request).read())
f.close()

rawDescription: How to pass a string + web url and receive the response using python

description: Pass a string + web url and receive the response using python


code: result_list = [match.value for match in jsonpath_ex.find(json.loads(input_string))]

rawDescription: How do I provide an input string to jsonpath?

description: Provide an input string to jsonpath


code:
[
    {
        'content': 'stuff',
        'timestamp': '123456789'
    },
    {
        'content': 'weird stuff',
        'timestamp': '93828492'
    }
]

rawDescription: Dealing with JSON with duplicate keys

description: Dealing with JSON with duplicate keys


code:
import matplotlib.pyplot as plt
from numpy.random import randn

# plot something
fig, ax = plt.subplots()
cax = ax.imshow(randn(100,100))

# create the color bar
cbar = fig.colorbar(cax)
cbar.set_label('dBZ', color = "white")

# update the text
t = cbar.ax.get_yticklabels();
labels = [item.get_text() for item in t]
cbar.ax.set_yticklabels(labels, color = 'white')
plt.show()

rawDescription: Change color of cbar legend text python

description: Change color of cbar legend text python


code:
f = open('C:/Users/Sikander/Desktop/bradpitt.html')
text = f.read()
while('<a href="http://' in text):
    #process it
    text = text[text.index('<a href="http://')+16:]

rawDescription: Code runs one time and stops, doesn't loop?


code:
import subprocess

child = subprocess.Popen([flash_filepath])
# At this point, the child process runs concurrently with the current process

# Do other stuff

# And later on, when you need the subprocess to finish or whatever
result = child.wait()

rawDescription: Run external program concurrently in Python


code:
def allChildren(self, l = None):
    if(l==None):
        l = list()

    l.append(self)
    for child in self.children:
        l = child.allChildren(l)
    return l

rawDescription: Python: printing all nodes of tree unintentionally stores data


code:
def pytest_generate_tests(metafunc):
    params = [("input", "output")]
    metafunc.parametrize(("test_case", "result"), params)

rawDescription: Using funcarg value in pytest_generate_tests function


code:
from collections import defaultdict
h = defaultdict(list)
h['a'].append('b')
h

rawDescription: How to make lists automatically instantiate on use in Python as they do in Perl?

description: Make lists automatically instantiate on use in Python as they do in Perl


code:
import Image
import matplotlib.pyplot as plt
import cStringIO
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch, cm

from reportlab.lib.utils import ImageReader

fig = plt.figure(figsize=(4, 3))
plt.plot([1,2,3,4])
plt.ylabel('some numbers')

imgdata = cStringIO.StringIO()
fig.savefig(imgdata, format='png')
imgdata.seek(0)  # rewind the data

Image = ImageReader(imgdata)

c = canvas.Canvas('test.pdf')
c.drawImage(Image, cm, cm, inch, inch)
c.save()

rawDescription: How to drawImage a matplotlib figure in a reportlab canvas?

description: DrawImage a matplotlib figure in a reportlab canvas


code:
import subprocess
proc = subprocess.Popen('/full/path/start %s' % filename)
proc.kill()

rawDescription: Terminating started Popen subprocess in Python


code:
def updateGUI():
    '''Force update of GTK mainloop during a long-running process'''
    while gtk.events_pending():
        gtk.main_iteration(False)

def wait_2s():
    for i in range(10):
        time.sleep(0.2)
        updateGUI()

rawDescription: Sleep without lock Gtk.main() in a function


code:
class profile(models.Model):
    name = models.CharField(max_length = 1200)
    description = models.TextField(default= 'description default')

    def __str__(self):
        return self.name

rawDescription: Name field does not reflect Add profile in Admin in Django


code:
import base
import functions

class DietPizza(base.BasePizza):
    @staticmethod
    def get_ingredients():
        return functions.istrue()

rawDescription: Python Abstract Proper Way of Calling Library Imported in Base Class


rawDescription: Converting to Hex in Python

description: Converting to Hex in Python


code: [(m.group(0), m.start()) for m in re.finditer('[aeiou]',s)]

rawDescription: Implementing preg_match_all in Python

description: Implementing preg_match_all in Python


code:
class HomePageDispatchView(View):
    def dispatch(self, request, *args, **kwargs):
        if request.user.type == PREMIUM:
            return PremiumHomePage.as_view()(request, *args, **kwargs)
        else:
            return RegularHomePage.as_view()(request, *args, **kwargs)

rawDescription: How to navigate to different class views in django based on user type?

description: Navigate to different class views in django based on user type


code:
from dateutil.parser import parse
from mx.DateTime import DateFrom
date = DateFrom(parse('Apr, 2012'))

rawDescription: datetime conversion using python

description: Datetime conversion using python


code:
#!/usr/bin/env python

import pygtk
pygtk.require('2.0')
import gtk, sys, cairo
from math import pi

def expose (widget, event):
    cr = widget.window.cairo_create()

    # Sets the operator to clear which deletes everything below where an object is drawn
    cr.set_operator(cairo.OPERATOR_CLEAR)
    # Makes the mask fill the entire window
    cr.rectangle(0.0, 0.0, *widget.get_size())
    # Deletes everything in the window (since the compositing operator is clear and mask fills the entire window
    cr.fill()
    # Set the compositing operator back to the default
    cr.set_operator(cairo.OPERATOR_OVER)

    # Draw a fancy little circle for demonstration purpose
    cr.set_source_rgba(0.5,1.0,0.0,1)
    cr.arc(widget.get_size()[0]/2,widget.get_size()[1]/2,
           widget.get_size()[0]/2,0,pi*2)
    cr.fill()

def main (argc):

    win = gtk.Window()

    win.set_decorated(False)

    # Makes the window paintable, so we can draw directly on it
    win.set_app_paintable(True)
    win.set_size_request(100, 100)

    # This sets the windows colormap, so it supports transparency.
    # This will only work if the wm support alpha channel
    screen = win.get_screen()
    rgba = screen.get_rgba_colormap()
    win.set_colormap(rgba)

    win.connect('expose-event', expose)

    win.show()

rawDescription: How to get transparent background in window with PyGTK and PyCairo?

description: Get transparent background in window with PyGTK and PyCairo


code:
def _loadPackagePlugins(package):
  "Load plugins from a specified package."
  ppath = package.__path__
  pname = package.__name__ + "."
  for importer, modname, ispkg in pkgutil.iter_modules(ppath, pname):
    module = __import__(modname, fromlist = "dummy")

rawDescription: Plugin design question

description: Plugin design question


code: failTaskCnt = sum(1 for task in self._tasks if task.IsTaskFail())

rawDescription: How to use filter in Python with a function which belongs to an object which is an element on the list being filtered?

description: Use filter in Python with a function which belongs to an object which is an element on the list being filtered


code:
import nltk
uni_dist = nltk.FreqDist(['the', 'dog', 'went', 'to', 'the', 'park'])
uni_dist
uni_dist2 = nltk.FreqDist('the dog went to the park')
uni_dist2

rawDescription: My NLTK code almost does what I need it to, but not quite


code:
class ARequestMessage(messages.Message):
  name = messages.StringField(1, required=True)
  in_list = messages.StringField(2, repeated=True)

rawDescription: protorpc reading list from caller with FieldList

description: Protorpc reading list from caller with FieldList


code:
class AttrDict(dict):
    """A dictionary with attribute-style access. It maps attribute access to
    the real dictionary.  """
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)

    def __getstate__(self):
        return self.__dict__.items()

    def __setstate__(self, items):
        for key, val in items:
            self.__dict__[key] = val

    def __repr__(self):
        return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self))

    def __setitem__(self, key, value):
        return super(AttrDict, self).__setitem__(key, value)

    def __getitem__(self, name):
        return super(AttrDict, self).__getitem__(name)

    def __delitem__(self, name):
        return super(AttrDict, self).__delitem__(name)

    __getattr__ = __getitem__
    __setattr__ = __setitem__

    def copy(self):
        return AttrDict(self)

rawDescription: How to create a persistant class using pickle in Python

description: Create a persistant class using pickle in Python


cmd: /opt/local/bin/python -u $file

rawDescription: ImportError when trying to import python module in SublimeText2


code:
for i in range(100):
    b = np.arange(10) * np.random.randint(10)

    ax[0].clear()
    ax[1].clear()

    ax[0].bar(a,b,align='center')
    # ...

rawDescription: Updating bar and plot subplots over loop iterations


code:
from collections import Counter
Counter(map(len, lis))

rawDescription: Count characters of strings in a list and categorize into groups


code:
import requests
import re
from bs4 import BeautifulSoup

req = requests.get(url)
req.raise_for_status()

html_doc = req.text.encode(req.encoding)
soup = BeautifulSoup(html_doc)

links = soup.findAll(href=re.compile("\.pdf$"))

for link in links:
    req = requests.get(link)
    # here, you'll want to use r.content, since it's probably a binary file
    content = req.content
    # write the bytes to a file

rawDescription: Access web page and download *.ext files, where ext can be set python script


code:
j = 2
re.findall(r"[a-zA-Z]\s", string)[j]

rawDescription: How to use * or + with brackets in regular expressions in Python?

description: Use * or + with brackets in regular expressions in Python


code:
input_file = open("namesandnumbers.txt", "r")
the_dict = {}
for line in input_file:
    initial = line.replace("\n","").split(" ")
    key = initial[0]
    number = int(initial[1])
    value = tuple([int(x) for x in initial[2: number + 2]])
    the_dict[key] = value

rawDescription: Text file to Tuple to Dictionary in Python


rawDescription: Python regex not greedy enough, multiple groups


code:
import webbrowser
webbrowser.open('http://google.co.kr', new=2)

rawDescription: How can I open a website in my web browser using Python?

description: Open a website in my web browser using Python


code:
import pexpect
import os
os.system('bin/pip install pexpect')
import pexpect

rawDescription: How to install and import python module in the same script?

description: Install and import python module in the same script


code:
f = open('/Users/Desktop/febROSTER2012.xls')
f.name

rawDescription: Get path from open file in Python

description: Get path from open file in Python


code:
data = open("OWS.txt", 'r')
output = open("result.txt", 'w')

chunk = []
for line in data:
    chunk.append(line)
    if line[0] == 'W':
        if 'bike' in str(chunk):
            for line in chunk:
                output.write(line)
        chunk = []

rawDescription: Slicing data block by block using Python


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

x = np.linspace(0, 10*np.pi, 1000)
y = np.sin(x*2) + np.sin(x + 1)

plt.plot(x, y, marker='o', markevery=0.05)

plt.show()

rawDescription: Plotting a curve with equidistant (arc-length) markers


code:
import ctypes
import ctypes.wintypes

ctypes.windll.kernel32.GetLargestConsoleWindowSize.restype = ctypes.wintypes._COORD
coord = ctypes.windll.kernel32.GetLargestConsoleWindowSize(ctypes.windll.kernel32.GetStdHandle(-11))
print(type(coord))
print(coord.X, coord.Y)

rawDescription: Casting to ctypes.wintypes

description: Casting to ctypes.wintypes


code:
from itertools import groupby
groups = groupby(both, lambda x: x[0]) # Group `both` by the zeroth index of its members
group = next(groups) # Get the first group in groups
group
list(group[1]) # Cast the group iterable into a list for display purposes

rawDescription: Modify list with python by index[0] value


code:
with open('Archive_2016-02-23.csv','rb') as f:
    reader = csv.reader( (line.replace('\0','') for line in f) )
    reader.next()
    for row in reader:
        for f,b in zip(l_headers, row):
            globals()[f]=b   #makes each header name into a variable with values

rawDescription: String with 'hidden' characters cannot convert to float


code:
import sys
from PyQt4 import QtGui, QtCore

class QExampleLabel (QtGui.QLabel):
    def __init__(self, parentQWidget = None):
        super(QExampleLabel, self).__init__(parentQWidget)
        self.initUI()

    def initUI (self):
        self.setPixmap(QtGui.QPixmap('input.png'))

    def mousePressEvent (self, eventQMouseEvent):
        self.originQPoint = eventQMouseEvent.pos()
        self.currentQRubberBand = QtGui.QRubberBand(QtGui.QRubberBand.Rectangle, self)
        self.currentQRubberBand.setGeometry(QtCore.QRect(self.originQPoint, QtCore.QSize()))
        self.currentQRubberBand.show()

    def mouseMoveEvent (self, eventQMouseEvent):
        self.currentQRubberBand.setGeometry(QtCore.QRect(self.originQPoint, eventQMouseEvent.pos()).normalized())

    def mouseReleaseEvent (self, eventQMouseEvent):
        self.currentQRubberBand.hide()
        currentQRect = self.currentQRubberBand.geometry()
        self.currentQRubberBand.deleteLater()
        cropQPixmap = self.pixmap().copy(currentQRect)
        cropQPixmap.save('output.png')

if __name__ == '__main__':
    myQApplication = QtGui.QApplication(sys.argv)
    myQExampleLabel = QExampleLabel()
    myQExampleLabel.show()
    sys.exit(myQApplication.exec_())

rawDescription: How to crop a image and save?

description: Crop a image and save


code:
import random
r = lambda: random.randint(0,255)
print('#%02X%02X%02X' % (r(),r(),r()))

rawDescription: Generating a Random Hex Color in Python

description: Generating a Random Hex Color in Python


code:
s1 = pd.Series([1, 2], index=['A', 'B'], name='s1')
s2 = pd.Series([3, 4], index=['A', 'B'], name='s2')
pd.concat([s1, s2], axis=1)
pd.concat([s1, s2], axis=1).reset_index()

rawDescription: Combining two Series into a DataFrame in pandas


rawDescription: How to set background of matplotlib with two rearranged axes?

description: Set background of matplotlib with two rearranged axes


code:
n=3
d1 = {key: value for i, (key, value) in enumerate(d.items()) if i < n}
d2 = {key: value for i, (key, value) in enumerate(d.items()) if i >= n}

rawDescription: Splitting a python dict from a certain key


code:
class my_class():
    def __init__(self):
        self.list_A = []
        self.list_B = []
        self.dict = { "A":self.list_A, "B":self.list_B }

    def add_to_list(self, key):
        # Logic in here
        self.dict.get(key[:1]).append(key)

if __name__ == "__main__":
    c = my_class()
    c.add_to_list("Apple")
    c.add_to_list("Bus")
    c.add_to_list("Airplane")
    print(c.dict["A"])
    print(c.dict["B"])

rawDescription: How do I choose the correct list depending on an argument value?

description: Choose the correct list depending on an argument value


code: b = map(float, a)

rawDescription: Python and arrays

description: Python and arrays


code: canvas1 = Canvas(rightPanel, bg='black', highlightthickness=0)

rawDescription: How to get rid of widget border in Tk()

description: Get rid of widget border in Tk()


rawDescription: Transpose Pandas Pivot Table

description: Transpose Pandas Pivot Table


rawDescription: How can I do 'a' + 1 #=> 'b' in python?

description: Do 'a' + 1 #=> 'b' in python


code:
with open("users") as input_file:
    for line in input_file:
        username, password = line.split('|')
        print("Username:", username.strip())
        print("Password:", password.strip())

rawDescription: How do i split a continuous string that is made up of two different word that are separated with "|" where i have to print just the first word?

description: Split a continuous string that is made up of two different word that are separated with "|" where i have to print just the first word


code:
for filter in (field_a, field_b):
    try:
        obj = session.query(model).filter_by(filter).one()
    except NoObjFound:
        pass # or 'continue'
    else:
        update_the_obj(obj)
        break
else:
    insert_into_db(brand_new_obj)

rawDescription: Python Nested Try/Except/Else for Control Flow


code:
s
s.diff()
s.diff().fillna(0)

rawDescription: Dates to Durations in Pandas

description: Dates to Durations in Pandas


code:
df
ts = df['name'].value_counts()
ts.name = 'occ'
df.join(ts, on='name')

rawDescription: value_counts not working properly

description: Value_counts not working properly


code:
from django.test import TestCase, RequestFactory
from .views import my_view

class SimpleTest(TestCase):
    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()

    def test_details(self):
        # Create an instance of a POST request.
        request = self.factory.post('/your/url', data={'your':'data'})

        # NOW you can customise your request instance!
        # (i.e. remove the Content-Type header)
        request.META.pop('CONTENT_TYPE', None)

        # Actually use the request to test my_view()
        # as if it were deployed at /customer/details
        response = my_view(request)
        self.assertEqual(response.status_code, 400)

rawDescription: How can I make an HTTP request with no Content-Type header using django.test.Client?

description: Make an HTTP request with no Content-Type header using django.test.Client


code:
import os
from Tkinter import *

def directory(folder):
    return '\n'.join(os.listdir(folder))  # turn list into multiline string

class App:
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        files = directory(os.path.expandvars('%temp%'))
        self.label = Label(root, text=files)
        self.label.pack(side=LEFT)

root = Tk()
app = App(root)
root.mainloop()

rawDescription: Accessing Temp Directory On Tkinter

description: Accessing Temp Directory On Tkinter


code:
class Parent(pw.Model):
    name = pw.CharField()

    class Meta:
        database = db

    @property
    def kid(self):
        return self.children.get()

class Child(pw.Model):
    name = pw.CharField()
    parent = pw.ForeignKeyField(Parent, related_name="children")

    class Meta:
        database = db

rawDescription: peewee: Get a single model instead of SelectQuery when back-referencing a foreign key

description: Peewee: Get a single model instead of SelectQuery when back-referencing a foreign key


code: b = [row[row>0] for row in a]

rawDescription: remove certain elements from numpy array without destroying the structure

description: Remove certain elements from numpy array without destroying the structure


code:
class V:
    """Defines a 2D vector"""
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def __bool__(self):
        return self.x != 0 or self.y != 0

    # Python 2 compatibility
    __nonzero__ = __bool__

rawDescription: How to define when a class is empty

description: Define when a class is empty


code:
# -*- coding: utf-8 -*-
import csv
from collections import defaultdict
from statistics import mean

class_file = 'scores.csv'
open_file = open(class_file)
csv_file = csv.reader(open_file)

def main():
    # First, use student name to group by all scores, this will
    # generate structure like this:
    # {
    #     'Andrew': [1, 2, 3, 4, 5]),
    #     'Luck': [10, 20]),
    # }
    score_groups = defaultdict(list)
    for name, score in csv_file:
        score_groups[name].append(int(score))

    # Secondary, use the 3 latest socres only
    l3_score_groups = [(key, value[-3:]) for key, value in score_groups.items()]

    print('1. Alphabetical order with each students highest score.')
    l3_highest_score_groups = [(key, max(values)) for key, values in l3_score_groups]
    for name, score in sorted(l3_highest_score_groups, key=lambda x: x[0]):
        print(name, score)

    print('2. By the highest score, highest to lowest.')
    l3_highest_score_groups = [(key, max(values)) for key, values in l3_score_groups]
    for name, score in sorted(l3_highest_score_groups, key=lambda x: x[1], reverse=True):
        print(name, score)

    print('3. Average score, highest to lowest.')
    l3_aver_score_groups = [(key, mean(values)) for key, values in l3_score_groups]
    for name, score in sorted(l3_aver_score_groups, key=lambda x: x[1], reverse=True):
        print(name, score)

if __name__ == '__main__':
    main()

rawDescription: Storing last 3 scores and deleting older scores and calculating average?


code:
# d is the dictionary
# notbusy is a list
d[ notbusy.pop() ] = ... # init the socket

rawDescription: Is a python dictionary the best data structure to solve this problem?


code:
import webbrowser

# generate an URL
url = 'https://' + 'www.google.com'
webbrowser.open(url)

rawDescription: Open URL in new tab from IPython Notebook/Jupyter cell


code:
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

rawDescription: Yield multiple objects at a time from an iterable object?


code:
lst = [52.0, 55.0, 567.0, 92.0, 2.0, 5.0]

def foo(lst):
    bar = ''
    for i in lst:
        i = format(i, '.2f')
        bar+= '${}, '.format(str(i))
    bar = bar.rstrip(', ')
    return '{'+bar+'}'

print(foo(lst))

rawDescription: Using a loop + string accumulator to format a List


code:
import datetime

timestring = datetime.datetime.now().time().isoformat()

timeobj = datetime.datetime.strptime(timestring, "%H:%M:%S.%f").time()

description: Python: serializing/deserializing datetime.time


code:
import importlib, os

pkg = 'some_pkg'  # this must be a python package

for x in os.listdir(pkg):
    try:
        module = importlib.import_module(pkg + '.' + x.replace('.py', ''))
        fnc = getattr(module, 'foo')
        fnc()
        # break in case you want to stop at the first 'foo' fnc you find
    except:
        print('no foo here, or not a module!')

rawDescription: Python: Create list of user-defined methods from a module and referencing/calling them by user input


code:
import urllib
f = { 'eventName' : 'myEvent', 'eventDescription' : "cool event"}
urllib.urlencode(f)

rawDescription: Python urlencode querystring

description: Python urlencode querystring


code:
application = webapp.WSGIApplication(
                                     [
                                        ('test', TestPage)
                                        ('.+', MainPage),
                                     ],
                                     debug=True)

rawDescription: Google app engine regular expression

description: Google app engine regular expression


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

from tkinter import *

# init our application's root window
root = Tk()
root.geometry('480x480')

# let's provide same sample coordinates with the desired text as tuples in a list
coords = [(30,30,'X'), (90,90,'X'), (120,120,'X'), (240,240,'X'), (270,270,'X'), (360,360,'O')]

# interate through the coords list and read the coordinates and the text of each tuple
for c in coords:
    l = Label(root, text=c[2])
    l.place(x=c[0], y=c[1])

# start a loop over the application
root.mainloop()

rawDescription: Tkinter - Coordinates

description: Tkinter - Coordinates


code:
message = input("What would you like your message to be? ")

key = input("What would you like your offset to be? ")

count = 0
while count == 0:
    mode = str(input("Would you like to encrypt or decrypt? "))
    if mode == "encrypt" or mode == "Encrypt" or mode == "E" or mode == "e":
        count = count + 1
    elif mode == "decrypt" or mode == "Decrypt" or mode == "D" or mode == "d":
        count = count + 1
    else:
        print("You need to enter in a valid answer. Please try again. ")

letters = "abcdefghijklmnopqrstuvwxyz"

translated_message = ""

index = 0
for character in message:
    if character in letters:
       number = letters.find(character)
       if mode == "encrypt" or mode == "Encrypt" or mode == "E" or mode == "e":
           number = number + (ord(key[index]) - ord('a'))
       elif mode == "decrypt" or mode == "Decrypt" or mode == "D" or mode == "d":
           number = number - (ord(key[index]) - ord('a'))
       index = index+1
       index = index % len(key)

       if number >= len(letters):
            number = number - len(letters)
       elif number < 0:
            number = number + len(letters)

       translated_message = translated_message + letters[number]

    else:
         translated_message = translated_message + character

print(translated_message)

rawDescription: Caesar Cipher with a Keyword - Python

description: Caesar Cipher with a Keyword - Python


rawDescription: Understanding Python references

description: Understanding Python references


code: autodoc_member_order = 'bysource'

rawDescription: Autodoc params?

description: Autodoc params


code:
class Task(models.Model):
    ...
    class Meta:
        permissions = (
            ("view_task", "Can see available tasks"),
            ("change_task_status", "Can change the status of tasks"),
            ("close_task", "Can remove a task by setting its status as closed"),
        )

rawDescription: When to programmatically create custom Django permissions?


code:
def try_until(func, max_tries, sleep_time):
    for _ in range(0,max_tries):
        try:
            return func()
        except:
            sleep(sleep_time)
    raise WellNamedException()

rawDescription: Determine how many items are in Python JoinableQueue


code:
import numpy as np
import pylab as plt
from matplotlib import rc, rcParams, colors

rc('text', usetex=True)
rcParams['font.size'] = 10
rcParams['axes.labelsize'] = 8

def plot(Z_s, CWL, filter_id, spectral_type, model_mag, mag, plot_name):
    f= ['U38', 'B', 'V', 'R', 'I', 'MB420', 'MB464', 'MB485', 'MB518',
        'MB571', 'MB604', 'MB646', 'MB696', 'B753', 'MB815', 'MB856',
        'MB914']
    wavetable = CWL/(1+Z_s)
    dd = model_mag-mag
    nplist = ['E', 'Sbc', 'Scd', 'Irr', 'SB3', 'SB2']
    minimum, maximum = (0., 16.)
    Z = [[0, 0],[0, 0]]
    levels = list(np.linspace(0, 1, len(f)+1))
    NUM_COLORS = len(f)
    cmap = plt.get_cmap('gist_rainbow')
    mycolor = []
    for i in range(NUM_COLORS):
         mycolor.append(cmap(1.*i/NUM_COLORS))
    mymap = colors.LinearSegmentedColormap.from_list('mycolors', mycolor)
    CS3 = plt.contourf(Z, levels, cmap=mymap)
    coords = CS3.get_array()
    coords = coords[:-1] + np.diff(coords)/2.
    FILTER = filter_id
    SED = spectral_type
    dummy = 2
    xmin = 1000
    xmax = 9000
    ymin = -3
    ymax = 3
    fig, axes = plt.subplots(nrows=5, figsize=(5, 6),
            gridspec_kw=dict(height_ratios=[0.35, 0.05, 1, 1, 1]))
    fig2, axes2 = plt.subplots(nrows=5, figsize=(5, 6),
            gridspec_kw=dict(height_ratios=[0.35, 0.05, 1, 1, 1]))
    fig.subplots_adjust(wspace=0, hspace=0)
    fig2.subplots_adjust(wspace=0, hspace=0)
    axes_all = np.concatenate((axes[dummy:], axes2[dummy:]))
    dummy_axes = np.concatenate((axes[:dummy], axes2[:dummy]))
    for ax in axes_all:
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')
        ax.axhline(y=0, color='k')
        ax.set_xlim(xmin, xmax)
        ax.set_ylim(ymin, ymax)
        ax.set_xticks([])
        ax.set_yticks(np.linspace(ymin, ymax, 4, endpoint=False))
        ax.set_ylabel(r'$\Delta$ MAG', fontsize=10)
    axes[-1].set_xticks(np.linspace(xmin, xmax, 16, endpoint=False))
    axes2[-1].set_xticks(np.linspace(xmin, xmax, 16, endpoint=False))
    plt.setp(axes[-1].xaxis.get_majorticklabels(), rotation=30)
    plt.setp(axes2[-1].xaxis.get_majorticklabels(), rotation=30)
    axes[-1].set_xlabel(r'WL($\AA$)', fontsize=10)
    axes2[-1].set_xlabel(r'WL($\AA$)', fontsize=10)
    for ax in dummy_axes:
        for s in ax.spines.values():
            s.set_visible(False)
        ax.xaxis.set_ticks_position('none')
        ax.yaxis.set_ticks_position('none')
        ax.set_xticks([])
        ax.set_yticks([])
    for axes_i in [axes, axes2]:
        cbar = plt.colorbar(CS3, ticks=[], orientation='horizontal',
                            cax=axes_i[0])
        for s, lab in enumerate(f):
            cbar.ax.text(coords[s], 0.5, lab, fontsize=8, va='center',
                     ha='center', rotation=90,
                     transform=cbar.ax.transAxes)
    for (j, d) in enumerate(nplist):
         bf = (SED==j)
         if (j<3):
             k = j
             ax = axes[k+dummy]
             ax.text(8500, 2.1, nplist[j], {'color': 'k', 'fontsize': 10})
             for i in range(len(f)):
                  bb = np.where(FILTER[bf]==i)[0]
                  ax.scatter(wavetable[bb], dd[bb],  s=1, color=mycolor[i])
         else:
             k = j-3
             ax = axes2[k+dummy]
             ax.text(8500, 2.1, nplist[j], {'color': 'k', 'fontsize': 10})
             for i in range(len(f)):
                  bb = np.where(FILTER[bf]==i)[0]
                  ax.scatter(wavetable[bb], dd[bb], s=1, color=mycolor[i])
    fname = '.'.join([plot_name, nplist[0], nplist[1], nplist[2], 'png'])
    fig.savefig(fname)
    fname = '.'.join([plot_name, nplist[3], nplist[4], nplist[5], 'png'])
    fig2.savefig(fname)

if __name__=='__main__':
    a = np.loadtxt('calibration.photometry.information.capak.cat')
    Z_s = a[:, 0]
    CWL = a[:, 1]
    filter_id = a[:, 2]
    spectral_type = a[:, 3]
    model_mag = a[:, 4]
    mag = a[:, 5]
    plot_name = 'test'
    plot(Z_s, CWL, filter_id, spectral_type, model_mag, mag, plot_name)

rawDescription: adjust the position of colorbar and equalize the size of subplots

description: Adjust the position of colorbar and equalize the size of subplots


code:
import fcntl
import sys
import termios

with open(sys.argv[1], 'w') as fd:
    for c in "ls\n":
        fcntl.ioctl(fd, termios.TIOCSTI, c)

rawDescription: Unable to fake terminal input with termios.TIOCSTI


code:
mergedTable.radius = mergedTable.radius.astype(int)
mergedTable.drop_duplicates()

rawDescription: Can't remove duplicates from DataFrame with drop_duplicates


code:
b = 0
def a():
    return b

def c(d=a):    # When it's a parameter, the call will be evaluated and its return
               # value will be used. Instead, just use the function name, because
    return d() # within the scope of the function, the call will be evaluated every time.

rawDescription: making the Python function default value be evaluated each time the function is called

description: Making the Python function default value be evaluated each time the function is called


code: soup.new_tag('a', href='#', id='link1', **{'class':'classname'})

rawDescription: python beautifulsoup new_tag: assign class as an attribute

description: Python beautifulsoup new_tag: assign class as an attribute


code:
def split_list(list_, size, name):
    d = {}
    for i, x in enumerate(list_):
        d[name + str(i+1)] = x
    return d

rawDescription: How can I create dictionary specifying keys names as a input variable

description: Create dictionary specifying keys names as a input variable


code:
import urllib.request

try:
    url = 'https://www.census.gov/popest/data/counties/asrh/2014/files/CC-EST2014-ALLDATA.csv'
    headers = {}
    headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0'
    req = urllib.request.Request(url, headers=headers)
    resp = urllib.request.urlopen(req)
    respData = resp.read()

    with open('Vintage2014.csv', 'w') as saveFile:
        saveFile.write(respData.decode('latin-1'))

except Exception as e:
    print(str(e))

rawDescription: using python 3.5 saving csv from url drops CR and LF

description: Using python 3.5 saving csv from url drops CR and LF


code:
from mayavi import mlab
import numpy as np
mlab.plot3d(np.random.rand(10), np.random.rand(10), np.random.rand(10))
mlab.plot3d(np.random.rand(10), np.random.rand(10), np.random.rand(10))
mlab.plot3d(np.random.rand(10), np.random.rand(10), np.random.rand(10))
mlab.plot3d(np.random.rand(10), np.random.rand(10), np.random.rand(10))

rawDescription: Multiple Plots in Mayavi

description: Multiple Plots in Mayavi


rawDescription: Return common element indices between two numpy arrays


code:
angle_in_radians = angle_in_degrees * math.pi / 180
line_length = 100
center_x = 250
center_y = 250
end_x = center_x + line_length * math.cos(angle_in_radians)
end_y = center_y + line_length * math.sin(angle_in_radians)

rawDescription: Rotate line in Tkinter Canvas

description: Rotate line in Tkinter Canvas


code:
from tkFileDialog import askopenfilename

path = askopenfilename()

f = open(path, 'r') # OR DO WHAT YOU WANT WITH PATH

rawDescription: I need to load an excel file into python 2.7 using an interface


code:
import nltk.tree
t = nltk.tree.Tree.fromstring("(TOP (S (NP-SBJ (NNP Ms.) (NNP Haag) ) (VP (VBZ plays) (NP (NNP Elianti) )) (. .) ))")
t.pos()

rawDescription: Clean the data in an efficient way in Python


code:
def my_parser(date, time):
    import datetime
    DATE_FORMAT = '%d:%m:%Y'
    TIME_FORMAT = '%H:%M:%S'
    date = datetime.datetime.strptime(date, DATE_FORMAT)
    time_weird_date = datetime.datetime.strptime(time, TIME_FORMAT)
    return datetime.datetime.combine(date, time_weird_date.time())

import pandas as pd
from cStringIO import StringIO

data = """\
some stuff I dont want
some stuff I dont want
some stuff I dont want
some stuff I dont want
Date(dd-mm-yy),Time(hh:mm:ss),Julian_Day
01:07:2013,05:40:41,182.236586,659,1638.400000
01:07:2013,05:44:03,182.238924,659,1638.400000
01:07:2013,05:47:48,182.241528,659,1638.400000
01:07:2013,05:52:21,182.244687,659,1638.400000
"""

pd.read_csv(StringIO(data), skiprows=5, index_col=0,
            parse_dates={'datetime':['date', 'time']},
            names=['date','time', 'Julian_Day', 'col_2', 'col_3'],
            date_parser=my_parser)

rawDescription: Pandas DateTimeIndex

description: Pandas DateTimeIndex


rawDescription: How to save figures to pdf as raster images in matplotlib

description: Save figures to pdf as raster images in matplotlib


code:
from mock import Mock, patch
import json

@patch('my_tornado_server.mongo_db_connection.query')
def test_a_random_handler_returns_some_json(self, mock_mongo_query):

    request = Mock()
    # Set any other attributes on the request that you need
    mock_mongo_query.return_value = ['pink', 'orange', 'purple']

    application = Mock()
    handler = RandomHandler(application, request)
    handler.write = Mock()

    handler.get('some_arg')

    self.assertEqual(handler.write.call_args_list, json.dumps({'some': 'data'}))

rawDescription: unit testing in tornado

description: Unit testing in tornado


code:
from gevent import monkey
def main():
    monkey.patch_thread()
# etc, etc
t = threading.Thread(target=bcastserver.serve_forever)
t.setDaemon(True)
t.start()
tradeserver.serve_forever()

rawDescription: How can I keep multiple gevent servers serving forever?

description: Keep multiple gevent servers serving forever


code:
from selenium.webdriver.support.ui import Select

select = Select(driver.find_element_by_id('stuff_devicessettings_Modbus_TCP'))
select.select_by_visible_text("No device connected")

rawDescription: Selecting a combo box using selenium webdriver xpath


code:
import sqlite3

c = sqlite3.Connection(':memory:')
c.execute('CREATE TABLE data (a, b, c)')

c.executemany('INSERT INTO data VALUES (?, ?, ?)', [
    (1, None,    1),
    (1,    0,    3),
    (1,    0,    3),
    (1,    2,    3),
    (2, None,    1),
    (2,    0, None),
    (2,    2,    2),
    (2,    2,    4),
    (2,    2, None),
])

# queries
# ...

rawDescription: What's a good data model for cross-tabulation?


code:
image1 = imread("/path/to/image1")
image2 = imread("/path/to/image2")
image3 = image1 - image2

rawDescription: How to subtract two images using python opencv2 to get the foreground object

description: Subtract two images using python opencv2 to get the foreground object


code: [a.split("|") for a in answers]

rawDescription: How to split text array?

description: Split text array


code:
src = """
print '!!!'
import os
"""

obj = compile(src, '', 'exec')
eval(obj, {'__builtins__': {'__import__':__builtins__.__import__}})

rawDescription: Why I can call 'print' from 'eval'

description: Why I can call 'print' from 'eval'


code:
class NonscientificDecimalField(DecimalField):
    """ Prevents values from being displayed with E notation, with trailing 0's
        after the decimal place  truncated. (This causes precision to be lost in
        many cases, but is more user friendly and consistent for non-scientist
        users)
    """
    def value_from_object(self, obj):
        def remove_exponent(val):
            """Remove exponent and trailing zeros.
               >>> remove_exponent(Decimal('5E+3'))
               Decimal('5000')
            """
            context = decimal.Context(prec=self.max_digits)
            return val.quantize(decimal.Decimal(1), context=context) if val == val.to_integral() else val.normalize(context)

        val = super(NonscientificDecimalField, self).value_from_object(obj)
        if isinstance(val, decimal.Decimal):
            return remove_exponent(val)

rawDescription: A trailing zero appears inconsistently on my DecimalField


rawDescription: plotting points with different colors by name in matplotlib

description: Plotting points with different colors by name in matplotlib


code:
for i, box in enumerate(boxes.get_children()):
    tooltip = mpld3.plugins.LineLabelTooltip(box, label=bins[i])
    mpld3.plugins.connect(fig, tooltip)

rawDescription: Using MPLD3 to make an interactive bar chart


code:
self.__dict__.update(
    variable1 = 1,
    variable2 = 2,
    variable3 = 'hello')

rawDescription: Python: convenient way to initialize lots of class members


code:
import os
import eyed3
folder = raw_input('Please enter the folder of music')
files = os.listdir(folder) # This will give us a list of all of the MP3s in that folder
artist = folder.split('/')[-1]

for x in files:
    mp3 = eyed3.load(folder + '/' + x) # Loads each and every MP3
    mp3.tag.artist = unicode(artist, "UTF-8") # Sets the "artist" tag to the artist name
    mp3.tag.save() # Saves tag

rawDescription: Setting "Album Artist" using eyed3?

description: Setting "Album Artist" using eyed3


code: [i for i in os.listdir('/home/dir/') if i.endswith(".ab")]

rawDescription: Use re module in python re.compile('*ab')


code:
_cache = {}

def get_page_type(type_name):
    if type_name not in _cache:
        _cache[type_name] = PageType.objects.get(type=type_name)
    return _cache[type_name]

rawDescription: How to lazily evaluate ORM call after fixtures are loaded into db in Django?

description: Lazily evaluate ORM call after fixtures are loaded into db in Django


code:
import  wx

class MyFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent)
        self.splitter = wx.SplitterWindow(self)

        pan1 = wx.Window(self.splitter, style=wx.BORDER_SUNKEN)
        pan1.SetBackgroundColour("yellow")
        wx.StaticText(pan1, -1, "My Left Panel")

        pan2 = wx.Window(self.splitter, style=wx.BORDER_SUNKEN)
        pan2.SetBackgroundColour("orange")
        wx.StaticText(pan2, -1, "my Right Panel")

        self.splitter.SplitVertically(pan1, pan2, -100)

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = MyFrame(None)
    frame.Show()
    app.MainLoop()

rawDescription: Resizable divider line in wxpython?

description: Resizable divider line in wxpython


code:
all_tracks = pd.DataFrame(
    [(t.title, t.genre, t.tag_list, t.created_at, t.last_modified,
      t.permalink_url, t.playback_count, t.duration)
     for t in tracks],
    columns=['title', 'genre', 'tag_list', 'created_at', 'last_modified',
             'permalink_url', 'playback_count', 'duration'])

rawDescription: passing elements returned by an API to a Pandas DF

description: Passing elements returned by an API to a Pandas DF


code:
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
    import threading
    class InterruptableThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.result = None

        def run(self):
            try:
                self.result = func(*args, **kwargs)
            except:
                self.result = default

    it = InterruptableThread()
    it.start()
    it.join(timeout_duration)
    if it.isAlive():
        return default
    else:
        return it.result

rawDescription: Ruby timeout for Python?

description: Ruby timeout for Python


code:
parser = argparse.ArgumentParser()
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
                    default=sys.stdin)
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
                    default=sys.stdout)
parser.parse_args(['input.txt', 'output.txt'])
parser.parse_args([])

rawDescription: Optional stdin in Python with argparse

description: Optional stdin in Python with argparse


code:
df = pd.read_csv('mycsv.csv', parse_dates=['simpleDate'])
df.max()

rawDescription: Pandas returns Dec 31 as max date, not the next year


code: set(tuple(sorted(l)) for l in a)

rawDescription: Removing permutations from a list of tuples


code:
import string
alpha = string.ascii_lowercase

dic_alpha = {ltr: alpha.index(ltr) for ltr in alpha }

to_bin = lambda i: '{0:05b}'.format(i)
dic_alpha_bin = {key : list(to_bin(val)) for key,val in dic_alpha.iteritems()}

lst_c1 = ['bit0','bit1','bit2','bit3','bit4']
lst_c2 = ['bit5','bit6','bit7','bit8','bit9']

df[lst_c1] = df['home_team'].apply(lambda x: pd.Series(dic_alpha_bin[x]))
df[lst_c2] = df['away_team'].apply(lambda x: pd.Series(dic_alpha_bin[x]))

rawDescription: how can i change string to binary columns in pandas

description: Change string to binary columns in pandas


code:
x1= A[:,0][:4]
x2= A[:,0][4:]
c0= A[:,1]
y_meas1= A[:,2][:4]
y_meas2= A[:,2][4:]

plt.plot(x1,y_meas1,'-b')
plt.plot(x2,y_meas2,'-g')

plt.title('Reaction')
plt.legend(['Data1', 'Data2'], loc='lower right')
plt.show()

rawDescription: Separating arrays with numpy to plot with matplotlib in python


code:
value = [17, 18, 19, 0, 1]
valueIndex = range(len(value))
valueIndex
valueRemapped = [float(x)/valueIndex[-1] if x > 0 else x for x in valueIndex]
valueRemapped
tempresult = zip(value, valueRemapped)
tempresult
tempresult.sort(key=operator.itemgetter(0))
tempresult
[x[1] for x in tempresult]

rawDescription: Convert list into index and range of 0-1.0


rawDescription: Matplotlib: How to plot using values stored in an array?


code:
df = pd.read_excel('filename.xlsm')
df.set_index(keys= ['index_col'], inplace=True)
df['col_to_plot'].plot(legend = True)

rawDescription: "None" in legend pandas python

description: "None" in legend pandas python


code:
class MyForm(ModelForm):
   class Meta:
      model = YourModel

   some_field = forms.CharField(required=False, help_text="Whatever you want")

rawDescription: Changing properties of inherited field

description: Changing properties of inherited field


code:
import sys

@GET("/some/path/extensions/:module/:func/:params")
def callmodule(module, func, params):
    D = dict(params)
    # Pull module instance from systems stack
    moduleInstance = sys.modules[module]
    # Grab method from module
    functionInstance = getattr(moduleInstance,func)
    # Pass "D" variable to function instance
    functionInstance(D)

rawDescription: python web framework -- dynamic routes to extension modules

description: Python web framework -- dynamic routes to extension modules


code:
your_dict = { 1:{'foo':123}}
your_dict[1]['foo']

rawDescription: extracting value from double dictionary python

description: Extracting value from double dictionary python


code:
True and True
True and False
False and True
True and 'x'
False and 'x'
'x' and True
'x' and False
'x' and 'y'
'l' and 'o'
s.count('l' and 'o')
s.count('o')
s.count('l') + s.count('o')

rawDescription: Count multiple letters in string Python

description: Count multiple letters in string Python


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

x = np.random.randn(10000)

nbins = 20

n, bins = np.histogram(x, nbins, density=1)
pdfx = np.zeros(n.size)
pdfy = np.zeros(n.size)
for k in range(n.size):
    pdfx[k] = 0.5*(bins[k]+bins[k+1])
    pdfy[k] = n[k]

pl.plot(pdfx, pdfy)

rawDescription: Probability Distribution Function Python


code:
import utils
class Login(object):
    def GET(self):
        if utils.session.login:
            return "OK"
        else:
            return "Please login."

rawDescription: Best app layout for webpy

description: Best app layout for webpy


code:
class OtherGuysClass:

    def buggedMethod(self, items):
        for item in items:
            a = self.convert(item)
            print(a * 5)

    def convert(self, str):
        return int(str)

if __name__ == "__main__":
    try:
        OtherGuysClass().buggedMethod([1, 2, None, 5])
    except Exception as e:
        print("Bugged method crashed: " + str(e))

    # Replace convert with our own method that returns 0 for None and ""
    o = OtherGuysClass()
    original_convert = o.convert
    def float_convert(str):
        if str:
            return original_convert(str)
        return 0
    o.convert = float_convert
    o.buggedMethod(["1", "2", None, "5"])

rawDescription: Modify interior of a looping function at runtime


code:
def process_build_finished(app, exception):
    if exception is not None:
        return

    target_files = []
    for doc in app.env.found_docs:
        target_filename = app.builder.get_target_uri(doc)
        target_filename = os.path.join(app.outdir, target_filename)
        target_filename = os.path.abspath(target_filename)
        target_files.append(target_filename)

    ...

rawDescription: Find names of all generated HTML files in Sphinx extension


code:
def Squaring():
  List = eval(input(": "))
  r = []
  for i in List:
    r.append(int(i) ** 2)

  return r

def main():
  x = Squaring()
  print('[' + ','.join(map(str, x)) + ']')

main()

rawDescription: How to remove empty spaces from a list? Why the `if` statement does not work?

description: Remove empty spaces from a list? Why the `if` statement does not work


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

# Generate data
freq_groups = [1.7, 2.3, 5.0, 8.4]
num = 50
x = np.random.normal(0, 0.5, num)
y = np.random.normal(0.2, 0.5, num)
year = 9 * np.random.random(num) + 1993.5
frequencies = np.random.choice(freq_groups, num)

symbols = ['o', '^', 's', 'd']

# Plot data
fig, ax = plt.subplots(figsize=(8, 9))
for freq, marker in zip(freq_groups, symbols):
    mask = np.isclose(freq, frequencies)
    scat = ax.scatter(x[mask], y[mask], c=year[mask], s=100, marker=marker,
                      cmap='jet_r', vmin=year.min(), vmax=year.max(),
                      label='{:0.1f} GHz'.format(freq), color='black')

ax.legend(loc='upper left', scatterpoints=1)
ax.set(xlabel='Relative RA (mas)', ylabel='Relative Dec (mas)')
ax.invert_xaxis()
cbar = fig.colorbar(scat, orientation='horizontal')
cbar.set_label('Epoch (year)')
cbar.formatter.useOffset = False
cbar.update_ticks()
fig.tight_layout()

plt.show()

rawDescription: How to make a scatter plot of different sizes, colour, and positions?

description: Make a scatter plot of different sizes, colour, and positions


code:
import numpy as np

ind = np.where( df.col1.isnull() & df.col1.shift(-1).notnull() )

df.loc[df.index[ind], "col1"] = df.loc[df.index[ind], "col2"]

rawDescription: Python Pandas: Selecting previous row of matching row


code:
import logging
from imp import reload
reload(logging)
LOG_FILENAME = r'logging_example.out'

logging.basicConfig(filename=LOG_FILENAME ,level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

f = open(LOG_FILENAME, 'rt')
try:
    body = f.read()
finally:
    f.close()

print('FILE:')
print (body)

rawDescription: python logging not saving to file

description: Python logging not saving to file


code:
search_replace_dict = {
    "$HOSTNAME": 'HOSTNAME',
    "$IOSCURRENT": 'IOSCURRENT',
    "$IOSOLD": 'IOSOLD'}

with open("router-input.txt") as input_file, open('output.txt','w') as output_file:
    for each_line in input_file:
        for key, value in search_replace_dict.items():
            each_line = each_line.replace(key, value)
        output_file.write(each_line)

rawDescription: Replace multiple text values in a single file


code:
from __future__ import print_function
from twisted.web.client import Agent, BrowserLikePolicyForHTTPS
from twisted.internet.task import react
from twisted.internet.ssl import Certificate
from twisted.internet.protocol import Protocol
from twisted.python.filepath import FilePath
from twisted.internet.defer import inlineCallbacks, Deferred

@inlineCallbacks
def main(reactor):
    customPolicy = BrowserLikePolicyForHTTPS(
        Certificate.loadPEM(FilePath("your-trust-root.pem").getContent())
    )
    agent = Agent(reactor, customPolicy)
    response = yield agent.request(
        "GET", "https://your-web-site.example.com/"
    )
    done = Deferred()
    class CaptureString(Protocol):
        def dataReceived(self, data):
            print("Received:", data)
        def connectionLost(self, reason):
            done.callback(None)
    response.deliverBody(CaptureString())
    yield done

react(main)

rawDescription: Twisted Python How To Create a twisted.web.client.BrowserLikePolicyForHTTPS with a custom trustRoot?


code:
import json

with open("record.json", "r") as infile:
    data = json.load(infile)
    for genre in data:
        for movie_genre in data[genre]:
            if "Aux" not in data[genre][movie_genre].keys():
                data[genre][movie_genre]["Aux"] = {"director": "MR J", "Producer": "Mr K"}

with open("record.json", "w") as outfile:
    outfile.write(json.dumps(data, indent=2))

rawDescription: Python : Find a node in JSON if not then enter the node


code:
from lxml import etree
doc = etree.parse("data.xml")
for con in doc.xpath("//specification"):
    for cons in con.xpath("./@body"):
        with open("output.txt", "w") as cons_out:
            content = cons.split("inv: name =")[1]
            cons_out.write(content)
        cons_out.close()

rawDescription: Use Python with lxml to parse a xml document and write elements into a text file


code:
user = authenticate(username=username, password=password)
if user is not None:
    if user.is_active:
        login(request, user)

rawDescription: How to make override Django login

description: Make override Django login


code:
def xview_event_handler(e):
    e.widget.update_idletasks()
    e.widget.xview_moveto(1)
    e.widget.unbind('<Expose>')

a = Tk()
text = StringVar(a, value='qwertyuiopasdfghjklzxcvbnm1234567890')
b = ttk.Entry(a, textvariable=text)
b.grid()
b.bind('<Expose>', xview_event_handler)

rawDescription: Why does tkinter's Entry.xview_moveto fail?


code: USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"

rawDescription: Browser rendered URL and Scraped URL are different. Please explain


code:
result = b_edge
tmp_dict = { (i[0],i[1]): i[2] for i in edges }
for index_j, j in enumerate(b_edge):
    for index_i, i in enumerate(j):
        if i in tmp_dict:
            result[index_j][index_i] = result[index_j][index_i] + (tmp_dict[i],)

rawDescription: Compare flat list and nested list

description: Compare flat list and nested list


code:
pkt = pcap[0]
hexdump(pkt[DNS])

rawDescription: Getting raw data using Scapy

description: Getting raw data using Scapy


code:
UserRecord.objects.annotate(time_plus_freq=F('enter_time')+F('frequency'))\
    .filter(time_plus_freq__lt=cur_time)

rawDescription: Django filter based on retrieved values

description: Django filter based on retrieved values


code:
def specialconvolve(a):
    # sorry, you must pad the input yourself
    rowconvol = a[1:-1,:] + a[:-2,:] + a[2:,:]
    colconvol = rowconvol[:,1:-1] + rowconvol[:,:-2] + rowconvol[:,2:] - 9*a[1:-1,1:-1]
    return colconvol

rawDescription: Improving Numpy Performance

description: Improving Numpy Performance


code:
import subprocess

p = subprocess.Popen(['/bin/bash', '-c', "echo 'select user from mysql.user;' | mysql" ],
    stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

lines = [line for line in p.stdout]

rawDescription: Capture output from a mysql select statement using python


code:
import glob
my_new_list = glob.glob("/your/folder/*")

rawDescription: Automatically creating a list in Python

description: Automatically creating a list in Python


code:
import dis
method1 = lambda: (127 / 60) * 60
method2 = lambda: 127 - 127 % 60
dis.dis(method1)
dis.dis(method2)

rawDescription: Why is time difference on calculating this so big?


code:
r, g, b = im.split()              # split the image into separate color planes
im = Image.merge("RGB", (g, g, g))  # merge them back, using the green plane for each

rawDescription: Image bit manipulation in Python

description: Image bit manipulation in Python


rawDescription: How do I get this JSON into a python list or dictionary?

description: Get this JSON into a python list or dictionary


code:
import re

f = open(fi+'.o2','r')
# f = ['this exe is a mba person',
#      'this exe combo offer is for mba only.',
#      'the exe suite is for mba person.']
word = 'exe'
word1 = 'mba'

for line in f:
    # check if both words are in the line
    if word in line and word1 in line:
        # remove the 'exe' and a space
        subs = re.sub(r'\bexe ', '', line)
        # replace 'mba' with 'mba executive'
        print(re.sub(r'\bmba\b', r'mba executive', subs))

# this is a mba executive person
# this combo offer is for mba executive only.
# the suite is for mba executive person.

rawDescription: how to use file pointers to edit a text document after a specific line or word

description: Use file pointers to edit a text document after a specific line or word


code: aDict = { chr(x):x for x in range(129) }

rawDescription: How to create a dict with space, quotes, dots, double quotes and etc

description: Create a dict with space, quotes, dots, double quotes and etc


code: output = input*input.swapaxes(1,2)

rawDescription: Outer products using theano/numpy.tensordot


code:
class Foo(object):
    d = {'foo': 'bar'}
    (lambda stuff: d[stuff])('foo')
class Foo(object):
    d = {'foo': 'bar'}
    def f(stuff):
        d[stuff]
    f('foo')

rawDescription: Lambdas, callable class instances, and scoping; why doesn't it work in Python 2.7?


code:
import random
ids = random.sample(Book.objects.values_list('pk', flat=True), 100)
Book.objects.filter(pk__in=ids).delete()

rawDescription: Delete N random objects Django orm

description: Delete N random objects Django orm


rawDescription: Calling upon a defined function with users input


code:
with open('test.csv', 'r') as file:
    data = file.read().split('\n')

for row in range(1, len(data)):
    third_col= data[x].split(',')
    with open('t' + str(x) + '.txt', 'w') as output:
        output.write(third_col[2])

rawDescription: How to extract data from rows in .csv file into separate .txt files using python?

description: Extract data from rows in .csv file into separate .txt files using python


code:
f = open('C:/file.txt', 'w')
f.read()

rawDescription: example of opening a new text file in a certain place on the computer in python

description: Example of opening a new text file in a certain place on the computer in python


code:
import socket
socket.getfqdn()

rawDescription: How to get fully qualified host name in Python?

description: Get fully qualified host name in Python


code:
class CustomWordsMiddleware(object):

   def process_response(self, request, response):

       if request.user.settings == 'lumberjack':
           response.content = response.content.replace("object", "tree")
           response.content = response.content.replace("objects", "trees")

       return response

rawDescription: Django - replacing string in whole project


code: re.split('\n\-{4,}\n', input)

rawDescription: Separate text from hyphens line

description: Separate text from hyphens line


code:
import matplotlib.pyplot as plt
import random
x = []
a,seed,c,m,n = 128,10,0,509,500
for i in range (1,n):
   new_seed=(a*seed+c)%m
   seed = new_seed
   x.append( new_seed)

a,seed,c,m,n = 269,10,0,2048,500
y= []
for i in range (1,n):
   new_seed=(a*seed+c)%m
   seed = new_seed
   y.append( new_seed)
plt.plot(x,y)
plt.show()

rawDescription: How to plot 500 pairs of successive random numbers in python?

description: Plot 500 pairs of successive random numbers in python


code:
import pandas as pd
xl_workbook = pd.ExcelFile("my_data.xlsx")  # Load the excel workbook
df = xl_workbook.parse("Sheet 1")  # Parse the sheet into a dataframe
x1_list = df['x1'].tolist()  # Cast the desired column into a python list

rawDescription: How to read from xlsx file and storing specific column values into an array in python?

description: Read from xlsx file and storing specific column values into an array in python


code:
import timeit
timeit.timeit('a > 0', 'a = 1', number=10**7)
timeit.timeit('a > 0', 'a = 0', number=10**7)
timeit.timeit('a != 0', 'a = 1', number=10**7)
timeit.timeit('a != 0', 'a = 0', number=10**7)

rawDescription: Is >0 faster than !=0 for an int?

description: Is >0 faster than !=0 for an int


code:
import os
from subprocess import Popen
try:
    from subprocess import DEVNULL # Python 3
except ImportError:
    DEVNULL = open(os.devnull, 'r+b', 0)

Popen(['pdflatex', 'file.tex'], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL)

rawDescription: How to stop subprocess.Popen waiting for user input in python

description: Stop subprocess.Popen waiting for user input in python


code:
while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

        ballrect = ballrect.move(speed)
        if ballrect.left < 0 or ballrect.right > width:
            speed[0] = -speed[0]
        if ballrect.top < 0 or ballrect.bottom > height:
            speed[1] = -speed[1]

    screen.fill(black)
    screen.blit(ball, ballrect)
    pygame.display.flip()

rawDescription: pygame only updates when mouse active over game window?

description: Pygame only updates when mouse active over game window


code:
def lowpriority():
    """ Set the priority of the process to below-normal."""

    import sys
    try:
        sys.getwindowsversion()
    except:
        isWindows = False
    else:
        isWindows = True

    if isWindows:
        # Based on:
        #   "Recipe 496767: Set Process Priority In Windows" on ActiveState
        #   http://code.activestate.com/recipes/496767/
        import win32api,win32process,win32con

        pid = win32api.GetCurrentProcessId()
        handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
        win32process.SetPriorityClass(handle, win32process.BELOW_NORMAL_PRIORITY_CLASS)
    else:
        import os

        os.nice(1)

rawDescription: Change process priority in Python, cross-platform


code:
old_path.replace(old_path[:old_path.index("ghi")],"/jkl/mno/")
In [4]: old_path.replace(old_path[:old_path.index("ghi")],"/jkl/mno/" )
Out[4]: '/jkl/mno/ghi/f.txt'

rawDescription: replace part of path - python

description: Replace part of path - python


rawDescription: How do you draw an ellipse/oval in turtle graphics (python)?

description: Draw an ellipse/oval in turtle graphics (python)


code:
import itertools

L = 3
d = 1
counter = 0
with open("question1.xyz","w") as text_file:
    text_file.write("\ncomment goes here\n")
    for x,y,z in itertools.product(range(L),repeat = 3):
        text_file.write('H %f %f %f\n' % (x, y, z))
        counter=counter+1

rawDescription: Creating a 3D lattice with periodic boundaries - create every combination of (x,y,z)


code:
import matplotlib.pylab as plt
from ast import literal_eval
from operator import itemgetter

with open("your_file") as f:
    lst = literal_eval(f.read())
    x,y = map(itemgetter(0),lst), map(itemgetter(1),lst)
    plt.plot(x,y)
    plt.show()

rawDescription: Take a list of coordinates and plot them on a graph


code:
# don't do the 'from tkinter import *' thing to avoid namespace clashes
import tkinter   # assuming Python 3 for simplicity's sake
import tkinter.ttk as ttk

root = tkinter.Tk()

f = tkinter.Frame(relief='flat')
lF = ttk.LabelFrame(root, labelwidget=f, borderwidth=4)
lF.grid()
b = ttk.Button(lF, text='gonzo')
b.grid()

root.mainloop()

rawDescription: ttk: how to make a frame look like a labelframe?

description: Ttk: how to make a frame look like a labelframe


code:
from sympy import *
mu, sigma, s = symbols("mu sigma s")
expr = exp(mu*s+(sigma*s)**2/2)
f = lambdify((mu, sigma, s), expr.diff(s, 2))
f(2, 0.5, 0)

rawDescription: How to calculate derivative of moment generating function in python?

description: Calculate derivative of moment generating function in python


code:
# Generate the new curve
x = np.linspace(0, 4*np.pi, N)
y = a*np.sin(k*x + w) + b

source.data = dict(x=x, y=y)

rawDescription: What is a fast and proper way to refresh/update plots in Bokeh (0.11) server app?


code:
import pandas as pd
t = pd.Timestamp('2000-02-09 00:00:00')
t = t.replace(hour=13, minute=0, second=0)

rawDescription: change time in timestamp

description: Change time in timestamp


code:
import gui
ui = None

def start():
  selected = "web"
  log("going to start gui " + selected)
  global ui
  __import__("gui.%s" % selected) # if you're importing a submodule that
                                  # may not have been imported yet
  ui = getattr(gui, selected)
  ui.start()

rawDescription: python import module to work globally

description: Python import module to work globally


code:
avatar_size = (59,59)
method = Image.NEAREST if im.size == avatar_size else Image.ANTIALIAS
formatted_im = ImageOps.fit(im, avatar_size, method = method, centering = (0.5,0.5))
formatted_im.save('foo.jpg', 'JPEG', quality=95)

rawDescription: ImageOps.fit is blurring my image

description: ImageOps.fit is blurring my image


code:
proc= subprocess.Popen(['python27','scriptA.py',file],cwd="C:\\pythonPrograms\\",stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate()
sortedop= subprocess.Popen(['sort'],cwd="C:\pythonPrograms\\",stdout=subprocess.PIPE,stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
out, err = sortedop.communicate(out)
countReducer= subprocess.Popen(['python27', 'scriptB.py'],cwd="C:\pythonPrograms\\",stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
out, err = countReducer.communicate(out)
fd = open(file+".json", 'w')
countpostprocesser= subprocess.Popen(['python27', 'scriptC.py'],cwd="C:\pythonPrograms\\",stdout=fd, stderr=subprocess.STDOUT)
out, err = countpostprocesser.communicate(out)

rawDescription: Using piping with subprocess.Popen

description: Using piping with subprocess.Popen


rawDescription: How to check if a button is clicked in wxpython with a conditional 'if - else' statement?

description: Check if a button is clicked in wxpython with a conditional 'if - else' statement


code:
return render_to_response('my_template.html',
                        my_data_dictionary,
                        context_instance=RequestContext(request))

rawDescription: Why request.get_full_path is not available in the templates?


code:
def calculateCorrelation(data_1, data_2, dist):
    """
    Fill the correlation matrix between data_1 and data_2
    :param data_1: dictionary {key : [coordinates]}
    :param data_2: dictionary {key : [coordinates]}
    :param dist: minimum distance between coordinates to be considered, in kilometers.
    :return: numpy array containing the correlation between each complaint category.
    """
    pool = Pool(processes=20)
    results = []

    data_1 = collections.OrderedDict(sorted(data_1.items()))
    data_2 = collections.OrderedDict(sorted(data_2.items()))
    data_1_size = len(data_1)
    data_2_size = len(data_2)

    corr = numpy.zeros((data_1_size, data_2_size))

    for index_1, key_1 in enumerate(data_1):
        for index_2, key_2 in enumerate(data_2):  # Forming pairs
            type_1 = data_1[key_1]  # List of data in data_1 of type *i*
            type_2 = data_2[key_2]  # List of data in data_2 of type *j*
            result = pool.apply_async(correlation, args=[type_1, type_2, dist])
            results.append((result, index_1, index_2))
    for result, index_1, index_2 in results:
        corr[index_1, index_2] = result.get()
    pool.close()
    pool.join()

rawDescription: Using Python pool inside loop

description: Using Python pool inside loop


code:
from datetime import datetime, timedelta

request.session['x'] = dict(dt=datetime.now(), value='something')

MAX_AGE = timedelta(seconds=240)

if ('x' in request.session and datetime.now() - request.session['x']['dt'] > MAX_AGE):
    del request.session['x']

rawDescription: How do I set a session to expire within 4 minutes?

description: Set a session to expire within 4 minutes


code:
index = 0
for link in context["object_list"]:
    if link.publicreply_set.exists():
        ...
        index += 1

rawDescription: Appending objects to a list and keeping the index intact even when certain iterations are excluded


rawDescription: Checking tuples values in dictionary

description: Checking tuples values in dictionary


rawDescription: Finding a tuple with greatest value

description: Finding a tuple with greatest value


code:
from collections import OrderedDict
from Bio import SeqIO

s6633 = SeqIO.read("6633_seq.embl", "embl")

def make_dict_realgenes(x):
    dict = OrderedDict()
...

rawDescription: Parse from file to dictionary in correct order, in Python


rawDescription: Python multiple list comprehensions containing ranges of tuples in one list


code: plt.scatter(x_vals, y_vals,  c = z_vals, cmap = 'rainbow')

rawDescription: Colour Map on scatter plot

description: Colour Map on scatter plot


code:
with open('file_name.txt','w') as f:
    res = itertools.permutations('abcdefghijklmnopqrstuvwxyz',5) # 5 is the length of the result.
    for i in res:
       f.write(''.join(i)+'\n')

rawDescription: Saving output in python

description: Saving output in python


code:
class Employee(Base):
    __tablename__ = "employee"
    # Columns
    id = Column(Integer, primary_key=True, autoincrement=True)
    representative_id = Column(Integer, ForeignKey('employee.id'))
    parent_id = Column(Integer, ForeignKey('employee.id'))
    affiliate_id = Column(Integer, ForeignKey('employee.id'))

    # Relatonships
    representative = relationship("Employee",
                         primaryjoin="Employee.representative_id==Employee.id",
                         remote_side=[id])
    parent = relationship("Employee",
                         primaryjoin="Employee.parent_id==Employee.id",
                         remote_side=[id])
    affiliate = relationship("Employee",
                         primaryjoin="Employee.affiliate_id==Employee.id",
                         remote_side=[id])

rawDescription: SQLAlchemy relationships: more than one self-referenced columns


code:
loggernames = [ ... ]
level = logging.DEBUG
handler = logging.StreamHandler()
handler.setLevel(level)
handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))

for name in loggernames:
    logging.getLogger(name).addHandler(handler)

rawDescription: Redirect logging to console during command


code: name = soup.find(id = 'lblKName').contents[0]

rawDescription: Python, attain a certain text from html

description: Python, attain a certain text from html


code:
import re
s = 'A:dog=one|B:cat=two|A:horse=three|A:tiger=four|B:mouse=five|A:snake=six'
re.sub(r'A:\w+', r'\g<0>A', s)

rawDescription: Python: replace all substring matched

description: Python: replace all substring matched


code:
import re
s='(twoplusthree)plusfour'
list(filter(None, re.split(r"(plus|[()])", s)))

rawDescription: Python: How can I include the delimiter(s) in a string split?


code:
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

#vectors to plot: 4D for this example
y1=[1,2.3,8.0,2.5]
y2=[1.5,1.7,2.2,2.9]

x=[1,2,3,8] # spines

fig,(ax,ax2,ax3) = plt.subplots(1, 3, sharey=False)

# plot the same on all the subplots
ax.plot(x,y1,'r-', x,y2,'b-')
ax2.plot(x,y1,'r-', x,y2,'b-')
ax3.plot(x,y1,'r-', x,y2,'b-')

# now zoom in each of the subplots
ax.set_xlim([ x[0],x[1]])
ax2.set_xlim([ x[1],x[2]])
ax3.set_xlim([ x[2],x[3]])

# set the x axis ticks
for axx,xx in zip([ax,ax2,ax3],x[:-1]):
  axx.xaxis.set_major_locator(ticker.FixedLocator([xx]))
ax3.xaxis.set_major_locator(ticker.FixedLocator([x[-2],x[-1]]))  # the last one

# EDIT: add the labels to the rightmost spine
for tick in ax3.yaxis.get_major_ticks():
  tick.label2On=True

# stack the subplots together
plt.subplots_adjust(wspace=0)

plt.show()

rawDescription: Parallel Coordinates plot in Matplotlib

description: Parallel Coordinates plot in Matplotlib


code:
ab = zip(A, B)
ab.sort(key=lambda values: int(values[1]), reverse=True)
A, B = zip(*ab)

rawDescription: Apply a transformation to a list based on the sorting of another list


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

from matplotlib.ticker import AutoMinorLocator

N = 1000
x = np.linspace(0, 5, N)
y = x**2

fig, ax = plt.subplots()

ax.plot(x, y)

minor_locator = AutoMinorLocator(2)
ax.xaxis.set_minor_locator(minor_locator)
plt.grid(which='minor')

plt.show()

rawDescription: How can i set the location of minor ticks in matplotlib

description: Set the location of minor ticks in matplotlib


rawDescription: Storing int or str in the list

description: Storing int or str in the list


code:
class NewVistorTest(unittest.TestCase):
    ...

if __name__ == '__main__':
    unittest.main(warnings='ignore')

rawDescription: selenium test not opening a browser django

description: Selenium test not opening a browser django


code: queryset = MyModel.objects.filter(date__year=2011, date__month=3, date__day=18)

rawDescription: Retrieving date from a datetime column in python/django


code:
class ScrollBar:
    # ... code ...
    def render(self, display, x, y):
        self.subSurface.blit(self.handle_image, (0, self.handle_pos))
        self.subSurface.blit(self.upbtn_image, (0, 0))
        self.subSurface.blit(self.dnbtn_image, (0, self.height - self.btn_height))
        # ... other rendering operations
        display.blit(self.subSurface, (x, y))

rawDescription: Pygame Surface Mechanics

description: Pygame Surface Mechanics


code:
def test_sum(self):
    my_model = MyModel(field_one=1,
                       field_two=2,
                       field_three=3,
                       )
    self.assertEqual(my_model.sum, 6)

rawDescription: Mock instance isn't using property code

description: Mock instance isn't using property code


code:
from PyQt4 import QtCore, QtGui

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        # add a few widgets for testing
        widget = QtGui.QWidget(self)
        edit = QtGui.QTextEdit(widget)
        button = QtGui.QPushButton('Button', widget)
        layout = QtGui.QVBoxLayout(widget)
        layout.addWidget(edit)
        layout.addWidget(button)
        self.setCentralWidget(widget)
        menu = self.menuBar().addMenu('&File')
        menu.addAction('&Quit', self.close)
        menu = self.menuBar().addMenu('&Edit')
        menu.addAction('&Clear', edit.clear)
        QtGui.qApp.installEventFilter(self)
        # make sure initial window size includes menubar
        QtCore.QTimer.singleShot(0, self.menuBar().hide)

    def eventFilter(self, source, event):
        # do not hide menubar when menu shown
        if QtGui.qApp.activePopupWidget() is None:
            if event.type() == QtCore.QEvent.MouseMove:
                if self.menuBar().isHidden():
                    rect = self.geometry()
                    # set mouse-sensitive zone
                    rect.setHeight(25)
                    if rect.contains(event.globalPos()):
                        self.menuBar().show()
                else:
                    rect = QtCore.QRect(
                        self.menuBar().mapToGlobal(QtCore.QPoint(0, 0)),
                        self.menuBar().size())
                    if not rect.contains(event.globalPos()):
                        self.menuBar().hide()
            elif event.type() == QtCore.QEvent.Leave and source is self:
                self.menuBar().hide()
        return QtGui.QMainWindow.eventFilter(self, source, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 300, 100)
    window.show()
    sys.exit(app.exec_())

rawDescription: PyQT4 QMenuBar Visibilty toggled by MouseOver


code:
foo = set()
foo.add('word')
'word' in foo
'bar' in foo

rawDescription: Efficient data structure and/or algorithm for searching if a word is in a set of words?


code:
fig= plt.figure()
plt.plot(range(10))
fig.savefig("save_file_name.pdf")
plt.close()

rawDescription: prevent plot from showing in ipython notebook

description: Prevent plot from showing in ipython notebook


code:
for line in fileinput.input(
   getattr(rsyslog_object, 'instance%d_rules' % instancenumber),
   mode='r'):
    ...

rawDescription: How should I refer to any arbitrary class attributes starting with a fixed string and differing by their ending numbers?


rawDescription: How can I loop over a tuple with two tuple elements and print a nice formatted string result of multiplying the tuple elements?

description: Loop over a tuple with two tuple elements and print a nice formatted string result of multiplying the tuple elements


code:
s.Foo = bar_2.oogaBooga()
s.Bar = BAZ.BAZOID()
q = spam.egg_soup()

rawDescription: Naming attributes and methods

description: Naming attributes and methods


code: source = open(template_instance.origin.name, 'r').read()

rawDescription: Get the source of a Django template

description: Get the source of a Django template


code:
m = Model1.objects.filter(desadder=1)
len(m)
m[0]
m = Model1.objects.filter(desadder=1)
len(m)
m[0]

rawDescription: How to count number of items in queryset without count()

description: Count number of items in queryset without count()


code:
import cPickle

# write to cPickle
cPickle.dump( thing_to_save, open( "filename.pkl", "wb" ) )

# read from cPickle
thing_to_save = cPickle.load( open( "filename.pkl", "rb" ) )

rawDescription: How do I save a 3D Python/NumPy array as a text file?

description: Save a 3D Python/NumPy array as a text file


code:
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool

to_engine = create_engine('sqlite:///%s' % temp_file_name, poolclass=NullPool)

rawDescription: File locks in SQLite

description: File locks in SQLite


rawDescription: Check if two items are in a list, in a particular order?


rawDescription: How to split a pandas dataframe into multiple columns

description: Split a pandas dataframe into multiple columns


code:
bla = re.compile(u'^[A-Za-z]{5}\d{6}$')
bla.match('abcde123456').group()

rawDescription: Need to select a formatted string in Python


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
x = np.linspace(0,4,1000)
y = np.exp(x)
plt.plot(x, y)
ax = plt.gca()
ax.set_yscale('log')
plt.tick_params(axis='y', which='minor')
ax.yaxis.set_minor_formatter(FormatStrFormatter("%.1f"))
plt.show()

rawDescription: How to show minor tick labels on log-scale with Matplotlib

description: Show minor tick labels on log-scale with Matplotlib


code:
import sys
import fileinput

for line in fileinput.input('my_text_file.txt', inplace=True):
    x = process_result(line)
    if x:
        line = line.replace('something', x)

    sys.stdout.write(line)

rawDescription: Python : Text Replacement In Large Files


code:
import cStringIO
import base64

pixBuf = gtkImage.get_pixbuf()

fH = cStringIO.StringIO()
pixBuf.save_to_callback(fH.write, "png")
encodedBuffer = base64.b64encode(fH.getvalue()) #base64 encoded png

rawDescription: How to convert Gtk.Image to base64

description: Convert Gtk.Image to base64


code:
from string import maketrans

intab = "abcdefghijklmnopqrstuvwxyz"
outtab = "cdefghijklmnopqrstuvwxyzab"
trantab = maketrans(intab, outtab)

inputfile = open("your_file_here.txt","r")
s = inputfile.read()

translation = s.translate(trantab)

print(translation)

rawDescription: encryption / decryption using dictionaries

description: Encryption / decryption using dictionaries


code:
sf = ax.plot_surface(x,y,z,rstride=5,cstride=5,color='r',linewidth=0.1,shade=0) # - this function
sf.remove()

rawDescription: How to clear surface

description: Clear surface


code:
from twisted.internet import task
from twisted.internet import reactor

datagramRecieved = False
timeout = 1.0 # One second

# UDP code here

def testTimeout():
    global datagramRecieved
    if not datagramRecieved:
        reactor.stop()
    datagramRecieved = False

l = task.LoopingCall(testTimeout)
l.start(timeout) # call every second

# l.stop() will stop the looping calls
reactor.run()

rawDescription: Is it possible to set a timeout on a socket in Twisted?


code:
def sentence_split(sentence):
    new_sentence = sentence[:]
    for letter in sentence:
        if not letter.isalnum():
            new_sentence = new_sentence.replace(letter, ' ')
    return new_sentence.split()

rawDescription: How to make my code detect end of string in python?

description: Make my code detect end of string in python


code:
import random

def main():
    file_size = random.randint(4,7)
    odd_nums = range(5,20,2)
    with open('numbers.txt', 'w') as f:
        for _ in range(file_size):
            n = random.choice(odd_nums)
            f.write('{}\n'.format(n))

if __name__ == '__main__':
    main()

rawDescription: Python 3 program help. If file_size is 6, then 6 odd numbers ranging from 5 to 19 must be written to file


code:
levels = [0.0, 1.0, 2.0]
a = np.random.choice(levels, size=10)
a_array = np.vstack((a, a)).T

b = np.random.choice(levels, size=10)
b_array = np.vstack((b, b)).T

ax = plt.subplot(121)
CS = ax.contourf(a_array, 2, level=levels, colors=('r', 'g', 'b'))

ax = plt.subplot(122)
CS = ax.contourf(b_array, 2, level=levels, colors=('r', 'g', 'b'))

Cbar = plt.colorbar(CS)

Cbar.set_ticks(levels)
Cbar.set_ticklabels(["series 1", "series 2", "series 3"])

rawDescription: How to plot comparison between two categorical (Nominal) series with pandas and matplotlib

description: Plot comparison between two categorical (Nominal) series with pandas and matplotlib


code:
def foo(var=None):
    if var is None: var = [0]

rawDescription: Lifetime of a variable in python

description: Lifetime of a variable in python


code:
import numpy as np

def my_intersect(x, y):
    """my_intersect(x, y) -> xm, ym
    x, y: 1-d arrays of unique values
    xm, ym: indices into x and y giving sorted intersection
    """
    # basic idea taken from numpy.lib.arraysetops.intersect1d
    aux = np.concatenate((x, y))
    sidx = aux.argsort()
    # Note: intersect1d uses aux[:-1][aux[1:]==aux[:-1]] here - I don't know why the first [:-1] is necessary
    inidx = aux[sidx[1:]] == aux[sidx[:-1]]

    # quicksort is not stable, so must do some work to extract indices
    # (if stable, sidx[inidx.nonzero()]  would be for x)
    # interlace the two sets of indices, and check against lengths
    xym = np.vstack((sidx[inidx.nonzero()],
                     sidx[1:][inidx.nonzero()])).T.flatten()

    xm = xym[xym < len(x)]
    ym = xym[xym >= len(x)] - len(x)

    return xm, ym

def check_my_intersect(x, y):
    mx, my = my_intersect(x, y)
    assert (x[mx] == np.intersect1d(x, y)).all()

    # not really necessary: np.intersect1d returns a sorted list
    assert (x[mx] == sorted(x[mx])).all()
    assert (x[mx] == y[my]).all()

def random_unique_unsorted(n):
    while True:
        x = np.unique(np.random.randint(2*n, size=n))
        if len(x):
            break
    np.random.shuffle(x)
    return x

x = np.array([4, 1, 10, 5, 8, 13, 11])
y = np.array([20, 5, 4, 9, 11, 7, 25])

check_my_intersect(x, y)

for i in range(20):
    x = random_unique_unsorted(100+i)
    y = random_unique_unsorted(200+i)
    check_my_intersect(x, y)

rawDescription: Indices that intersect and sort two numpy arrays


rawDescription: How do you stored screen_name from the twiiter api in python?

description: Stored screen_name from the twiiter api in python


code:
import numpy_indexed as npi
common_dates = npi.intersection(min_dates, max_dates)
print(max_values[npi.indices(max_dates, common_dates)])
print(min_values[npi.indices(min_dates, common_dates)])

rawDescription: Python: Intersection of Two 2D Arrays

description: Python: Intersection of Two 2D Arrays


code:
#!/usr/bin/env python3

from kazoo.client import KazooClient
from threading import Lock

zkl = Lock()
def my_func(event):
    if event.type == 'CHILD':
        zkl.release()

zk = KazooClient(hosts='127.0.0.1:2181')
zk.start()
zkl.acquire()
children = zk.get_children("/distribute-lock", watch=my_func)
zkl.acquire()
zk.stop()

rawDescription: how to used zookeeper watch in kazoo to block program

description: Used zookeeper watch in kazoo to block program


code:
from sklearn.datasets import make_classification
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression

X, y = make_classification(n_samples=1000, n_features=100, weights=[0.1, 0.9], random_state=0)
X.shape

# build pipe: first standardize by substracting mean and dividing std
# next do classificaiton
pipe = make_pipeline(StandardScaler(), LogisticRegression(class_weight='auto'))

# fit
pipe.fit(X, y)
# predict
pipe.predict_proba(X)

# to get back mean/std
scaler = pipe.steps[0][1]
scaler.mean_
Out[12]: array([ 0.0313, -0.0334,  0.0145, ..., -0.0247,  0.0191,  0.0439])

scaler.std_
Out[13]: array([ 1.    ,  1.0553,  0.9805, ...,  1.0033,  1.0097,  0.9884])

rawDescription: Can scikit-learn's LogisticRegression() automatically normalize input data to z-scores?


rawDescription: Subtract an year from a datetime column in pandas


code:
import sqlalchemy

# using mssql as an example because sqlalchemy uses pyodbc as the default driver for MS Sql Server
engine = sqlalchemy.create_engine("mssql://myserver/mydb")
# first column of first row is returned
username = engine.scalar("select username from users where userid = 1")

rawDescription: Does pyodbc have an execute scalar function


code:
userName = ''
userNumber = ''

while not userName.isalpha():
    if userName: print('Choose a valid name!')
    userName = input('Hello there, civilian! What is your name? ')

print('It is nice to meet you, ' + userName + "! ")

while not userNumber.isnumeric():
    if userNumber: print('Choose a number please! ')
    userNumber = input('Please pick any number between 3-100. ')

for i in range(0,int(userNumber) + 1,2):
    print(i)

rawDescription: How do I make my code loop properly in python?

description: Make my code loop properly in python


code:
from lxml import etree
root = etree.fromstring(b'<x xmlns="wow"><y id="1"/><y id="2"/></x>')
root.findall('{wow}y')
ns = {'d': 'wow'}
root.findall('d:y', ns)
root.xpath('d:y', namespaces=ns)

rawDescription: python3 lxml how to find node when prefix is empty?

description: Python3 lxml how to find node when prefix is empty


rawDescription: Python: How to turn a string of binary values (arbitrary length) into hex data?


code:
oval = canvas.create_oval(10, 10, 20, 20, fill='red')
canvas.itemcget(oval, 'fill')  # => Returns 'red'

rawDescription: How to detect certain color of circle, in Tkinter?

description: Detect certain color of circle, in Tkinter


code:
from lxml import etree

def dem_apples(xml1,xml2,join_on='name'):

    tree1 = etree.fromstring(xml1)
    tree2 = etree.fromstring(xml2)

    for a1 in tree1.xpath('./apple'):
        a1_attr_set = set(dict(a1.attrib).items())
        a2_list = tree2.xpath('./apple[@{0}="{1}"]'.\
         format(join_on,a1.get(join_on)))
        for a2 in a2_list:
            a2_attr_set =  set(dict(a2.attrib).items())
            diff = a1_attr_set - a2_attr_set
            if diff:

                print(a1.get(join_on),diff,a2_attr_set-a1_attr_set)

if __name__ == '__main__':

    xml_string1="""
    <fruit>
    <apple name="a" mb="15" lb="0" write="true" value="1"/>
    <apple name="b" mb="31" lb="16" write="true" value="2"/>
    <apple name="c" mb="32" lb="32" write="true" value="3"/>
    </fruit>
    """

    xml_string2="""
    <fruit>
    <apple name="a" mb="15" lb="0" write="true" value="1"/>
    <apple name="b" mb="31" lb="16" write="true" value="3"/>
    <apple name="c" mb="32" lb="32" write="true" value="2"/>
    </fruit>
    """
    dem_apples(xml_string1,xml_string2)

rawDescription: Line by line comparison of two xml files


rawDescription: Get an index of a sorted matrix

description: Get an index of a sorted matrix


code:
from PIL import Image
import numpy as np

def SRGBResize(im, size, filter):
    # Convert to numpy array of float
    arr = np.array(im, dtype=np.float32) / 255.0
    # Convert sRGB -> linear
    arr = np.where(arr <= 0.04045, arr/12.92, ((arr+0.055)/1.055)**2.4)
    # Resize using PIL
    arrOut = np.zeros((size[1], size[0], arr.shape[2]))
    for i in range(arr.shape[2]):
        chan = Image.fromarray(arr[:,:,i])
        chan = chan.resize(size, filter)
        arrOut[:,:,i] = np.array(chan)
    # Convert linear -> sRGB
    arrOut = np.where(arrOut <= 0.0031308, 12.92*arrOut, 1.055*arrOut**(1.0/2.4) - 0.055)
    # Convert to 8-bit
    arrOut = np.uint8(np.rint(arrOut * 255.0))
    # Convert back to PIL
    return Image.fromarray(arrOut)

rawDescription: SRGB-aware image resize in Pillow

description: SRGB-aware image resize in Pillow


code:
from contextlib import contextmanager

@contextmanager
def managed(a):
    try:
        yield a
    finally:
        if a:
            cleanup(a)

with managed(get_a()) as a, managed(get_b()) as b:
    # do something here
    pass

rawDescription: How to simplify this kind of Python code?

description: Simplify this kind of Python code


code:
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.item import Item, Field

class MyItem(Item):
    url = Field()

class MySpider(CrawlSpider):
    name = "xyz"
    allowed_domains = ["xyz.nl"]
    start_urls = ["http://www.xyz.nl/Vacancies"]
    rules = (Rule(SgmlLinkExtractor(allow=[r'\/V-\d{7}\/[\w\S]+']), callback='parse_item'),
             Rule(SgmlLinkExtractor(allow=[r'\?page\=\d+\&sortCriteria\=1']), follow=True),)

    def parse_item(self, response):
        item = MyItem()
        item['url'] = response.url
        yield item

rawDescription: Scrapy different number of url return

description: Scrapy different number of url return


code:
import csv

with open('text.csv', 'rt') as f:
    age10 = [row for row in csv.reader(f) if row[1] == '10']

rawDescription: Filter and retrieve required value from csv file python


code:
import httplib
def exists(site, path):
    conn = httplib.HTTPConnection(site)
    conn.request('HEAD', path)
    response = conn.getresponse()
    conn.close()
    return response.status == 200
exists('http://www.fakedomain.com', '/fakeImage.jpg')

rawDescription: python: check if url to jpg exists

description: Python: check if url to jpg exists


code:
def x(cond):
    if cond:
        "dummy statement"
        print('Still running!')

rawDescription: Why does python keep evaluating code after `pass`?


code:
m = Message(root)
txt = Text(root, background=m.cget("background"), relief="flat",
    borderwidth=0, font=m.cget("font"), state="disabled")
m.destroy()

rawDescription: Scrollbar for Message Widget in Tkinter

description: Scrollbar for Message Widget in Tkinter


code:
class structure():

    ...

    def remove(self, point):
        del self.point_index_a[point]
        del self.point_index_b[point]

rawDescription: Deleting Class Object Instance Contained in Two Dicts in Python


code: title = re.sub(r'^([a-z]\s)*', '', 'a b c d Wikipedia Reference')

rawDescription: Remove sequential characters from the start of a string


code:
start = '|'
end = '|'

rawDescription: Python regex help needed

description: Python regex help needed


code:
from urllib import urlretrieve
urlretrieve('http://www.mysite.com/myscript.py', '/home/me/script.py')
import script

rawDescription: Add a python script at runtime

description: Add a python script at runtime


code:
from scrapy.spider import Spider
from scrapy.selector import Selector
from scrapy.http import Request
import re

from yelp2.items import YelpReviewItem

RESTAURANTS = ['sixteen-chicago']

def createRestaurantPageLinks(self, response):
    reviewsPerPage = 40
    sel = Selector(response)
    totalReviews = int(sel.xpath('//div[@class="rating-info clearfix"]//span[@itemprop="reviewCount"]/text()').extract()[0].strip().split(' ')[0])
    pages = [Request(url=response.url + '?start=' + str(reviewsPerPage*(n+1)), callback=self.parse) for n in range(totalReviews/reviewsPerPage)]
    return pages

class YelpXSpider(Spider):
    name = "yelpx"
    allowed_domains = ["yelp.com"]
    start_urls = ['http://www.yelp.com/biz/%s' % s for s in RESTAURANTS]

    def parse(self, response):
        requests = []

        sel = Selector(response)
        reviews = sel.xpath('//div[@class="review review-with-no-actions"]')
        items = []

        for review in reviews:
            item = YelpReviewItem()
            item['venueName'] = sel.xpath('//meta[@property="og:title"]/@content').extract()
            item['reviewer'] = review.xpath('.//li[@class="user-name"]/a/text()').extract()
            item['reviewerLoc'] = review.xpath('.//li[@class="user-location"]/b/text()').extract()
            item['rating'] = review.xpath('.//meta[@itemprop="ratingValue"]/@content').extract()
            item['reviewDate'] = review.xpath('.//meta[@itemprop="datePublished"]/@content').extract()
            item['reviewText'] = review.xpath('.//p[@itemprop="description"]/text()').extract()
            item['url'] = response.url
            yield item

        if response.url.find('?start=') == -1:
            requests += createRestaurantPageLinks(self, response)
            for request in requests:
                    yield request

rawDescription: Scrapy spider not including all requested pages


code:
import re

astr='My---sun--is------very-big---.'

print(re.sub('-+','-',astr))
# My-sun-is-very-big-.

rawDescription: How do I coalesce a sequence of identical characters into just one?

description: Coalesce a sequence of identical characters into just one


code:
from tkinter import Tk
from tkinter.simpledialog import askstring

root = Tk()
root.withdraw() # hide main window

config = {}
config['user'] = askstring("Title", 'new user data: ')

rawDescription: python user input without console

description: Python user input without console


rawDescription: python format a floating number to print .123 not 0.123

description: Python format a floating number to print .123 not 0.123


code:
db = con['test']
test = db.test
test.update({}, {
    '$currentDate': {
        'creation_time': { '$type': 'timestamp' }
    }
},upsert=True)

rawDescription: PyMongo, handling fields with time relative to the database time


code:
template = '<input name="#key#" value="#value#">'
html = template
data = {key:value,key:value}
for key in data.keys():
    html = html.replace("#key#", key).replace("#value#", data[value]) + "\n"
    html = html + template
#there's an extra template line here that you'll have to get rid of.
html = "\n".join(html.split("\n")[0:-1])

rawDescription: Creating a form from an object in python


rawDescription: Is there a considerable difference between comparing a number to zero with "==" or as a bool?


code:
#! /usr/bin/env python3
from multiprocessing import Barrier, Lock, Process
from time import time
from datetime import datetime

def main():
    synchronizer = Barrier(2)
    serializer = Lock()
    Process(target=test, args=(synchronizer, serializer)).start()
    Process(target=test, args=(synchronizer, serializer)).start()

def test(synchronizer, serializer):
    synchronizer.wait()
    now = time()
    with serializer:
        print(datetime.fromtimestamp(now))

if __name__ == '__main__':
    main()

rawDescription: Multiprocessing in Python: execute two functions at the exact same time


code:
import numpy as np
np.finfo(np.double).eps
np.finfo(np.single).eps

rawDescription: Comparing floating point numbers with numpy and scipy


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

data = np.arange(100, 0, -1).reshape(10, 10)

fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])

im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()

rawDescription: Add colorbar to existing axis

description: Add colorbar to existing axis


rawDescription: Assigning Variable with Value of Existing Variable from String Value


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

browser = webdriver.Firefox()
browser.maximize_window()
wait = WebDriverWait(browser, 10)

browser.get('http://demo.magentocommerce.com/')

browser.find_element_by_css_selector("a[href='/search']").click()

search = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "search-query")))
search.send_keys("phones" + Keys.RETURN)

rawDescription: Unable to submit keys using selenium with python


code:
import datetime

dt1 = "2016-04-18 20:15:07"
dt2 = "2016-04-18 20:15:07+00:00"

d1 = datetime.datetime.strptime(dt1, "%Y-%m-%d %H:%M:%S")
d2 = datetime.datetime.strptime(dt2, "%Y-%m-%d %H:%M:%S+%f:00")

print(d1)
print(d2)

if d1 == d2:
    print("times match!")

rawDescription: Python datetime objects fail to match

description: Python datetime objects fail to match


code: re.search('STATION(?P<StationName>.*?):.*?\n.*?IP Address: %s' % sta_ip, output).group("StationName")

rawDescription: Regex help in python

description: Regex help in python


rawDescription: More information in signal/slot with QPushButton


code: [uid for uid, attrs in users.items() if attrs['name'] == name_you_are_looking_for]

rawDescription: Search for value in dictionary?

description: Search for value in dictionary


code:
import re

text = 'blhpxxxx [SCRIPT MODE]> show syslog server 1 Retrieving syslog server (s) ... <EVENT SEVERITY = "Repaired" /> '

print(re.search("\<.*\>", text).group())

rawDescription: How to remove text outside tags xml

description: Remove text outside tags xml