code:
import sys
import math
from PIL import Image, ImageOps, ImageDraw

orig = ImageOps.grayscale(Image.open(sys.argv[1]))
orig_bin = orig.point(lambda x: 0 if x < 128 else 255)
im = orig_bin.load()

border = Image.new('1', orig.size, 'white')
width, height = orig.size
bim = border.load()
# Keep only border points
for x in xrange(width):
    for y in xrange(height):
        if im[x, y] == 255:
            continue
        if im[x+1, y] or im[x-1, y] or im[x, y+1] or im[x, y-1]:
            bim[x, y] = 0
        else:
            bim[x, y] = 255

# Find each border (the trivial dummy way).
def follow_border(im, x, y, used):
    work = [(x, y)]
    border = []
    while work:
        x, y = work.pop()
        used.add((x, y))
        border.append((x, y))
        for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1),
                (1, 1), (-1, -1), (1, -1), (-1, 1)):
            px, py = x + dx, y + dy
            if im[px, py] == 255 or (px, py) in used:
                continue
            work.append((px, py))

    return border

used = set()
border = []
for x in xrange(width):
    for y in xrange(height):
        if bim[x, y] == 255 or (x, y) in used:
            continue
        b = follow_border(bim, x, y, used)
        border.append(b)

# Find the corners and centroid of each rectangle.
rectangle = []
for b in border:
    xmin, xmax, ymin, ymax = width, 0, height, 0
    mean_x, mean_y = 0, 0
    b = sorted(b)
    top_left, bottom_right = b[0], b[-1]
    for x, y in b:
        mean_x += x
        mean_y += y
    centroid = (mean_x / float(len(b)), mean_y / float(len(b)))
    b = sorted(b, key=lambda x: x[1])
    curr = 0
    while b[curr][1] == b[curr + 1][1]:
        curr += 1
    top_right = b[curr]
    curr = len(b) - 1
    while b[curr][1] == b[curr - 1][1]:
        curr -= 1
    bottom_left = b[curr]

    rectangle.append([
        [top_left, top_right, bottom_right, bottom_left], centroid])

result = orig.convert('RGB')
draw = ImageDraw.Draw(result)
for corner, centroid in rectangle:
    draw.line(corner + [corner[0]], fill='red', width=2)
    cx, cy = centroid
    draw.ellipse((cx - 2, cy - 2, cx + 2, cy + 2), fill='red')
    rotation = math.atan2(corner[0][1] - corner[1][1],
            corner[1][0] - corner[0][0])
    rdeg = math.degrees(rotation)
    draw.text((cx + 10, cy), text='%.2f' % rdeg)

result.save(sys.argv[2])

rawDescription: Segment an image using python and PIL to calculate centroid and rotations of multiple rectangular objects


code:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

class User(db.Model):
    pass

rawDescription: How many Base or MetaData instances do you need in SQLAlchemy?


rawDescription: Boolean sum with numpy finding matching pairs


code: hotels = [d['money'] for d in data if d['type'] == 'hotel']

rawDescription: How to simplify array extraction values

description: Simplify array extraction values


code:
import socket, sys, itertools

host = sys.argv[1] #Server IP Address
textport = sys.argv[2] #Server Binding Port

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

try:
    port = int(textport)
except ValueError:
    port = socket.getservbyname(textport, 'udp')

# preprocess file data
with open('auth3.log') as data:
    roles = [role for (role, line_spoken) in line.split(': ', 1) for line in data]

# preprocess everything we can
hp = (host, port)
send = s.sendto

for role in itertools.cycle(roles):
    try:
        send(role, hp)
    except:
        pass

rawDescription: sendto() python

description: Sendto() python


code:
from lxml import etree
from cStringIO import StringIO

xml = """<foo><bar/> baz!</foo>"""

# parse from string
etree.fromstring(xml)

# parse from file-like; in this case, StringIO
s = StringIO(xml)
etree.parse(s)

# parse from URL
etree.parse("http://example.com/somefile.xml")

rawDescription: Parsing XML of different formats using Python


code:
initial = input("Enter code: ")

splitter = (initial.strip()).split(" ")

coder1 = []
for i in splitter:
    if (int(i) == 0):
        coder1.append("*")
    else:
        coder1.append(int(i)%26)

coder2 = [str(i) for i in coder1]

cipher = ' '.join(coder2)

cipher = cipher.replace("10", "j")
cipher = cipher.replace("11", "k")
cipher = cipher.replace("12", "l")
cipher = cipher.replace("13", "m")
cipher = cipher.replace("14", "n")
cipher = cipher.replace("15", "o")
cipher = cipher.replace("16", "p")
cipher = cipher.replace("17", "q")
cipher = cipher.replace("18", "r")
cipher = cipher.replace("19", "s")
cipher = cipher.replace("20", "t")
cipher = cipher.replace("21", "u")
cipher = cipher.replace("22", "v")
cipher = cipher.replace("23", "w")
cipher = cipher.replace("24", "x")
cipher = cipher.replace("25", "y")
cipher = cipher.replace("1", "a")
cipher = cipher.replace("2", "b")
cipher = cipher.replace("3", "c")
cipher = cipher.replace("4", "d")
cipher = cipher.replace("5", "e")
cipher = cipher.replace("6", "f")
cipher = cipher.replace("7", "g")
cipher = cipher.replace("8", "h")
cipher = cipher.replace("9", "i")
cipher = cipher.replace("0", "z")

lister = list(cipher)
if (len(lister) == 0):
    print ("invalid input")
elif (len(lister) == 1):
    final = ''.join(lister)
    final = final.replace("*", " ")
    print(final)
else:
    while " " in lister:
        final = lister.remove(" ")
        final = ''.join(lister)
        final = final.replace("*", " ")
    print(final)

rawDescription: Need help fixing my code to fit requirements


code: found = any(word in item for item in wordlist)

rawDescription: Check substring match of a word in a list of words


code:
df = pd.DataFrame([1,20,3],[2,30,4],[3,40,5],columns=['mean','size','stat'])

fig,[ax1,ax2,ax3] = plt.subplots(1, 3, sharey=True)

plt.subplot(1,3,1)
barh(np.arange(len(df)),df['mean'].values, align='center')
locs, labels = xticks()
xticks(locs, labels, rotation="90")
plt.subplot(1,3,2)
barh(np.arange(len(df)),df['size'].values, align='center')
locs, labels = xticks()
xticks(locs, labels, rotation="90")
plt.subplot(1,3,3)
barh(np.arange(len(df)),df['stat'].values, align='center')
locs, labels = xticks()
xticks(locs, labels, rotation="90")

rawDescription: Rotate existing axis labels in Matplotlib


code:
from ctypes import *

d2xx = WinDLL('ftd2xx')

OK = 0
INVALID_HANDLE = 1
DEVICE_NOT_FOUND = 2
DEVICE_NOT_OPENED = 3

...

def openEx(serial):
    serial = create_string_buffer(serial)
    handle = c_int()
    if d2xx.FT_OpenEx(serial, OPEN_BY_SERIAL_NUMBER, byref(handle)) == OK:
        return Handle(handle.value)
    raise D2XXException

class Handle(object):
    def __init__(self, handle):
        self.handle = handle
    ...
    def read(self, bytes):
        buffer = create_string_buffer(bytes)
        count = c_int()
        if d2xx.FT_Read(self.handle, buffer, bytes, byref(count)) == OK:
            return buffer.raw[:count.value]
        raise D2XXException
    def write(self, data):
        buffer = create_string_buffer(data)
        count = c_int()
        bytes = len(data)
        if d2xx.FT_Write(self.handle, buffer, bytes, byref(count)) == OK:
            return count.value
        raise D2XXException

rawDescription: Wrapping a C library in Python: C, Cython or ctypes?


code:
def primes(n):
    # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    """ Returns  a list of primes < n """
    sieve = [True] * n
    for i in xrange(3,int(n**0.5)+1,2):
        if sieve[i]:
            sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
    return [2] + [i for i in xrange(3,n,2) if sieve[i]]

rawDescription: Finding the nth prime number using Python


code:
def fetch_data(filename1, filename2):
    lines = []
    data = {}
    with open (filename1) as f:
        lines = f.readlines()

    for line in lines:
        if not line.strip():
            continue
        data[' '.join(line.split())] = 0

    with open (filename2) as f:
        lines = f.readlines()

    for line in lines:
        if not line.strip():
            continue
        arr = line.split()
        data[' '.join(arr[:-1])] += int(arr[3])

    return data

with open ('output.txt', 'w') as f:
    for key,value in fetch_data('original.txt','data.txt').iteritems():
        f.write('{0}    {1} \n\n'.format('    '.join(key.split()), str(value)))

rawDescription: Python script to use coordinates from one file and add values from matching coordinates in another file


code:
import unittest

class MyClass(object):
    def __init__(self, day_name, day_num):
        self.day_name = day_name
        self.day_num = day_num

    def __eq__(self, other):
        return other.day_name == self.day_name and other.day_num == self.day_num

class ATestCase(unittest.TestCase):
    def test_foo(self):
        actual_sorted = [MyClass("wed", 20),
                           MyClass("wed", 19),
                           MyClass("thu", 18),
                           MyClass("wed", 17)]

        expected_sorted = [MyClass("wed", 20),
                           MyClass("wed", 19),
                           MyClass("thu", 18),
                           MyClass("wed", 17)]
        self.assertEqual(actual_sorted, expected_sorted)

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

rawDescription: Python Unit Test - compare content of iterables in Python < 2.7


code: tags = models.ManyToManyField('tags.Tag', ...)

rawDescription: Avoid Circular Model Imports in Django Apps


code:
if o.m.__func__ == C.m:
      print("Equality")

rawDescription: Comparing a function to a bound method in python 3


code: raw_html2 = raw_html.replace('\\n', '')

rawDescription: Remove newline in python with urllib

description: Remove newline in python with urllib


code:
from tkinter import *

def sunken(event):
    button = event.widget # detecte le bouton sur lequel on clique
    button['relief'] = 'sunken' # changement de relief

root = Tk()

for i in range(8):
    for j in range(8):
        myButton = Button(root, text='', state='disabled')
        myButton.grid(row=i, column=j)
        myButton.bind("<Button-1>", sunken)

root.mainloop()

rawDescription: Why do I have to double click to change the relief of my button object ? (tkinter)


code: [x for x in itertools.product(*variables) if sum(x)==5]

rawDescription: List comprehensions with arbitrary numbers of variables in Python?


rawDescription: Numpy: How to query multiple multidimensional arrays?


code:
from PyQt4 import QtGui

class Wiz(QtGui.QWizard):

    def __init__(self):
        QtGui.QWizard.__init__(self)
        self.noback = []
        self.currentIdChanged.connect(self.disable_back)

    def disable_back(self, ind):
        if ind in self.noback:
            self.button(QtGui.QWizard.BackButton).setEnabled(False)

wiz = Wiz()
wiz.noback = [2]
wiz1 = QtGui.QWizardPage(wiz)
wiz2 = QtGui.QWizardPage(wiz)
wiz3 = QtGui.QWizardPage(wiz)

wiz.addPage(wiz1)
wiz.addPage(wiz2)
wiz.addPage(wiz3)

wiz.show()

rawDescription: PyQt4 QWizard: How to disable the back button on a single page?


code:
def run(self):
    self.runButton.setEnabled(False) # call it first because
                                     # processes are not started instantly
    self.process = QtCore.QProcess(self)
    self.process.started.connect(self.onstart) # connect "start" signal
    self.process.finished.connect(self.onfinish)
    self.process.start(exe_path, args) # then start

rawDescription: How to do stuff during and after a child process

description: Do stuff during and after a child process


code:
df.groupby(['A', 'B'])\
  .agg(tuple)\
  .reset_index()\
  .to_json(orient='records')

rawDescription: Dataframe implicitly holding a hierarchy to JSON


code:
import imp
fp, pathname, description = imp.find_module('cv2', ['/path/to/opencv/'])
cv2 = imp.load_module('cv2', fp, pathname, description)

rawDescription: python wont load module unless started in a specific directory

description: Python wont load module unless started in a specific directory


code:
import sys
import django
django.setup()

from django.apps import apps

for _class in apps.get_models():
    globals()[_class.__name__] = _class

rawDescription: Pycharm - autoload models in Django console


code:
class DietPizza(BasePizza):
    def __init__(self):
        super().__init__()
        self.lastname = "Last Name"

rawDescription: Python Abstract Method With It's own __init__ function


code:
def parse(self, response):
    b_pages_links = getlinks(A)
    for link in b_pages_links:
        yield Request(link, callback = self.visit_b_page)

def visit_b_page(self, response):
    url_of_c_page = ...
    yield Request(url_of_c_page, callback = self.visit_c_page)

def visit_c_page(self, response):
    url_of_image = ...
    yield Request(url_of_image, callback = self.get_image)

def get_image(self, response):
    item = CustomItem()
    item['name'] = ... # get image name
    item['image'] = ... # get image data
    yield item

rawDescription: How do I use Scrapy to crawl within pages?

description: Use Scrapy to crawl within pages


code:
import numpy as np

# Make an example image
image = np.random.randint(0, 255, (10, 10, 3))
image[2, 2, :] = [255, 0, 0]

# Define the color you're looking for
pattern = np.array([255, 0, 0])

# Make a mask to use with where
mask = (image == pattern).all(axis=2)
newshape = mask.shape + (1,)
mask = mask.reshape(newshape)

# Finish it off
image = np.where(mask, [0, 0, 0], [255, 255, 255])

rawDescription: Numpy change all elements on condition on multidimensional array


code:
u'''def foo():
\xa0\xa0return 42'''

rawDescription: Outputting Tabs with Django

description: Outputting Tabs with Django


code:
def integers_mod_p(p):
    class IntegerModP(object):
        def __init__(self, n):
            self.n = n % IntegerModP.p
        def typecheck(self, other):
            try:
                if self.p != other.p:
                    raise TypeError
            except AttributeError:
                raise TypeError
        def __add__(self, other):
            self.typecheck(other)
            return IntegerModP(self.n + other.n)
        def __sub__(self, other):
            ...
    IntegerModP.p = p
    IntegerModP.__name__ = 'IntegerMod{}'.format(p)
    return IntegerModP

rawDescription: What is the "metaclass" way to do this?

description: What is the "metaclass" way to do this


code:
from flask import g

@app.route('/api/me')
@oauth.require_oauth()
def me(req):
    user = req.user
    g.oauth_request = req
    return jsonify(username=user.username)

@app.after_request
def record_ip(response):
   req = g.get('oauth_request')
   if req is not None:
       client = req.client # needs access to "req"
       # .... log stuff in my database ...

   return response

rawDescription: How do I pass arguments to after_request?

description: Pass arguments to after_request


code:
import lxml.sax
import lxml.etree

lsh = pyxb.binding.saxer.PyXBSAXHandler()
lst1 = time.time()
tree = lxml.etree.fromstring(xmld)
lst2 = time.time()
lxml.sax.saxify(tree, lsh)
lst3 = time.time()
lxml_instance = handler.rootObject()
print('LXML-based read %f, parse and bind %f, total %f' % (lst2-lst1, lst3-lst2, lst3-lst1))
print("Equality test on DOM vs LXML: %s" % (dom_instance.equal(lxml_instance),))

rawDescription: How to make a binding instance in lxml?

description: Make a binding instance in lxml


code:
from flask import Flask, render_template, request
from forms import *
from models import Bin, Shelf, BinItem
from sqlalchemy.orm import sessionmaker
from flask.ext.sqlalchemy import SQLAlchemy
import os
import logging
import sys

logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
app.secret_key = 'secret_shhhhh!@#$1234'

db = SQLAlchemy(app)

class Item(db.Model):
    __tablename__ = 'item'
    item_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    sku = db.Column(db.String(50), nullable=False, unique=True)
    title = db.Column(db.String(100), nullable=False)

    def __init__(self, sku, title):
        self.sku = sku
        self.title = title

@app.route('/items', methods=['GET', 'POST'])
def items():
    try:
        log.info('Start reading form DB')
        form = ItemForm()
        item_list = db.session.query(Item).all()
        if request.method == 'GET':
            return render_template('items.html', form=form, item_list=item_list)
        else:
            if form.validate():
                new_item = Item(form.sku.data, form.title.data)
                db.session.add(new_item)
                db.session.commit()
                form.sku.data = ''
                form.title.data = ''
                item_list = db.session.query(Item).all()
                return render_template('items.html', form=form, item_list=item_list, item_added=True)
            else:
                return render_template('items.html', form=form, item_list=item_list, item_added=False)
    except:
        _, ex, _ = sys.exc_info()
        log.error(ex.message)

rawDescription: 500 Response From Heroku App

description: 500 Response From Heroku App


code: any(a == 'Mary' for a, b in tuples) # check if any tuple has a name equal to Mary

rawDescription: Check is a tuple with a value is in a list in python


code:
def recursive_len(item):
    if type(item) == list:
        return sum(recursive_len(subitem) for subitem in item)
    else:
        return 1

rawDescription: How can I get the total number of elements in my arbitrarily nested list of lists?

description: Get the total number of elements in my arbitrarily nested list of lists


rawDescription: Python: Appending API Calls to Spreadsheet


code:
import Tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Hello, world")
label.winfo_exists()
root.winfo_children()
label.destroy()
label.winfo_exists()
root.winfo_children()

rawDescription: How to see if a widget exists in Tkinter?

description: See if a widget exists in Tkinter


rawDescription: How to delete multiple substrings in Python?

description: Delete multiple substrings in Python


code:
def myfunc(arg1, arg2):
  arg1 = (arg1 == 'True')

rawDescription: How to pass bool argument to fabric command

description: Pass bool argument to fabric command


code:
import hashlib
plaintext = u"MyPassword"
utf_text = plaintext.encode('UTF-16LE')
hashlib.sha1(utf_text).digest().encode('base64')

rawDescription: Convert PHP to Python

description: Convert PHP to Python


code:
class SomeObject:
    def __init__(self, values):
        self.values = values
    ...

SomeObject.columns = [
    (lambda x: x['type'], 'Type'),
    (lambda x: 'http://localhost/view?id=%s' % x['id'], 'Link'),
    (SomeObject.helper_function, 'Data'),
]

rawDescription: In python, any elegant way to refer to class method within the classes declaration scope?


code:
import xml.etree.ElementTree as ET
tree = ET.parse('in.xml')
root = tree.getroot()

items_to_delete = root.findall("./video[title='name2']")
for item in items_to_delete:
    root.remove(item)

tree.write('out.xml')

rawDescription: Python Elementtree delete/edit a node

description: Python Elementtree delete/edit a node


code:
name = ['Jem', 'Sam', 'Sam', 'Jem', 'Jem']
nums = [10, 10, 2, 9, 10]

sort = sorted(zip(name, nums), key = lambda i:i[0])

name = [i[0] for i in sort] # split name again
nums = [i[1] for i in sort] # split nums again

rawDescription: How can I have changes made to one list affect another, different list?

description: Have changes made to one list affect another, different list


code:
a = np.round(np.random.normal(size=(5, 3)), 1)
a[1, 2] = np.nan
a[2] = np.nan

print(a)
print(a[np.all(np.isfinite(a), axis=1)])  # Removes rows with any non-finite values.
print(a[np.any(np.isfinite(a), axis=1)])  # Removes rows that are all non-finite.

rawDescription: Removing a Row with Missing Values in Numpy Array


code:
@user_registered.connect_via(app)
def user_registered_sighandler(app, user, confirm_token):
    default_role = user_datastore.find_role("User")
    user_datastore.add_role_to_user(user, default_role)
    db.session.commit()

rawDescription: Setting a default role in flask-security


code:
from django.forms.formsets import INITIAL_FORM_COUNT
if formset.initial_form_count() < formset.total_form_count():
    manform = formset.management_form
    prefixed_name = manform.add_prefix(INITIAL_FORM_COUNT)
    manform.data[prefixed_name] = formset.total_form_count()

rawDescription: Increasing number of initial forms in a Django formset based on data in POST?


code:
import grequests

urls = ['http://localhost/test', 'http://localhost/test']

params = {'a':'b', 'c':'d'}
rs = (grequests.post(u, data=params) for u in urls)
grequests.map(rs)

rawDescription: How do I make HTTP POST requests with grequests

description: Make HTTP POST requests with grequests


Django-dajaxice overriding XMLHttpRequest


code:
content = urllib2.urlopen(
    "https://indivinet.ca/api/v1/login",
    "api_key=5f1d5cb35ca1953ecd8f63ac0ac44d3b&location_id=location&username=username&password=password"
).read()

rawDescription: Python POST login request

description: Python POST login request


code:
with open("lst.txt","r") as guestFile :
    lines=guestFile.readlines()
    newlines=[line.capitalize() for line in lines]
with open("lst.txt","w") as guestFile :
    guestFile.writelines(newlines)

rawDescription: Python: How to capitalize the first column of a .txt file.


code:
dic = {'voornaam': 'John', 'Achternaam': 'Davis', 'telephone': '123456', 'Mobielnummer': '234567'}
tr = {'voornaam':'first_name', 'Achternaam':'last_name', 'telephone':'phone', 'Mobielnummer':'mobile'}
dic = {tr[k]: v for k, v in dic.items()}

rawDescription: replace dictionary keys (strings) in Python

description: Replace dictionary keys (strings) in Python


code:
pylab.contourf(-pac[:,100,:], extent=[-4, 4, 0, 1000])  #pac is a 3D data distribution
pylab.colorbar()
savefig("PAC Concentration.png")
pylab.close()

rawDescription: How to change x-axis label values for (contourf) in pylab

description: Change x-axis label values for (contourf) in pylab


code:
def get_queryset(self):
    # filters_map keys must match your queries
    filters_map = {
        'id': self.request.GET.get('id'),
        'first_name__icontains': self.request.GET.get('f_name'),
        'middle_name__icontains': self.request.GET.get('m_name'),
        'last_name__icontains': self.request.GET.get('l_name'),
        'relative_name__icontains': self.request.GET.get('r_name'),
        'phone_no_1__contains': self.request.GET.get('p_no'),
        'phone_no_2__contains': self.request.GET.get('p_no'),
        'gender': self.request.GET.get('gender')
    }
    # leave out empty strings
    query = dict((key, value) for key, value in filters_map.iteritems() if value)

    return Customer.objects.filter(**query)

rawDescription: How to do complex query like this

description: Do complex query like this


code:
with open('in') as inf, open('out', 'w') as outf:
    while True:
        line = inf.readline()
        if '<table border' in line:
            while True:
                line = inf.readline()
                if not line or '/table>' in line:
                    line = inf.readline()
                    break
        if not line:
            break
        outf.write(line)

rawDescription: How to convert this sed command to Python script?

description: Convert this sed command to Python script


code: NotInFile = object()

rawDescription: Defining my own None-like Python constant


code:
import re

i = 96
def replace(matches):
    global i
    i += 1
    return " " + chr(i) + matches.group(0)

re.sub(',|\)', replace, "void some_function(int,  int *, float);")

rawDescription: Insert characters in a string using python


code: Px, Py, m = symbols("Px Py m")

rawDescription: Unpacking Sympy variables from dictionary


code: without_newlines = my_string.replace("\n", "")

rawDescription: python 2.7's logging.info(string) and newline characters

description: Python 2.7's logging.info(string) and newline characters


code:
import datetime, time
from sqlalchemy.types import TypeDecorator, DateTime, Integer

class IntegerDateTime(TypeDecorator):
    """a type that decorates DateTime, converts to unix time on
    the way in and to datetime.datetime objects on the way out."""
    impl = Integer # In schema, you want these datetimes to
                   # be stored as integers.
    def process_bind_param(self, value, _):
        """Assumes a datetime.datetime"""
        if value is None:
            return None # support nullability
        elif isinstance(value, datetime.datetime):
            return int(time.mktime(value.timetuple()))
        raise ValueError("Can operate only on datetime values. "
                         "Offending value type: {0}".format(type(value).__name__))
    def process_result_value(self, value, _):
        if value is not None: # support nullability
            return datetime.datetime.fromtimestamp(float(value))

rawDescription: Defining a table with sqlalchemy with a mysql unix timestamp


code: result = df.groupby(pd.TimeGrouper('15Min')['col1'].apply(lambda x: x.value_counts()))

rawDescription: Get count of value for 15 min periods

description: Get count of value for 15 min periods


code:
delete_set = set(I for I in my_list if meet_requirement(I))
another_list.extend(transform(I) for I in delete_set)
# or extend(transform(I) for I in my_list if I in delete_set), if duplicates/order matter
my_list = [I for I in my_list if I not in delete_set]

rawDescription: What should be the pythonic way to implement following logic?


code:
ymdhms, usec = rows['TStamp'].split('.')
time.mktime((datetime.datetime.strptime(ymdhms, "%Y%m%d%H%M%S" ) ).timetuple()) + int(usec) / 1000000.

rawDescription: Convert timestamp to datenum

description: Convert timestamp to datenum


code:
import sys
import subprocess
import os

from ansi2html.converter import Ansi2HTMLConverter

ansiText =  os.path.expanduser('~/Desktop/colorDiff')

proc = subprocess.Popen('git diff HEAD^ HEAD --color',  shell=True, stdout=subprocess.PIPE, stderr = subprocess.PIPE )
diffData = proc.stdout.read()
conv = Ansi2HTMLConverter()

html = conv.convert(diffData)

with open("%s.html" % ansiText, 'w') as wf:
    wf.write(html)

rawDescription: How to generate HTML color diff from git using python

description: Generate HTML color diff from git using python


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

mean = 7.0
std = 19.0

def investment_return():
    return (np.random.normal(mean, std)) / 100

def investor(index, period):
    wT = []
    vY = []

    for t in range(1, period + 1):
        new_index = index + index * investment_return()
        if new_index > index * 1.4:
            index = new_index * 0.1
        else:
            index = new_index
        wT.append(t)
        vY.append(index)
    return wT, vY

for i in range(0, 10):
    wT, vY = investor(100, 20)

    # do something with your data

    plt.plot(wT, vY)

plt.ylabel('Investment_value')
plt.xlabel('Investment_period')
plt.show()

rawDescription: Previous value in while loop in Python

description: Previous value in while loop in Python


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib import animation

x = [0, 1, 2]
y = [0, 1, 2]
yaw = [0.0, 0.5, 1.3]
fig = plt.figure()
plt.axis('equal')
plt.grid()
ax = fig.add_subplot(111)
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)

patch = patches.Rectangle((0, 0), 0, 0, fc='y')

def init():
    ax.add_patch(patch)
    return patch,

def animate(i):
    patch.set_width(1.2)
    patch.set_height(1.0)
    patch.set_xy([x[i], y[i]])
    patch._angle = -np.rad2deg(yaw[i])
    return patch,

anim = animation.FuncAnimation(fig, animate,
                               init_func=init,
                               frames=len(x),
                               interval=500,
                               blit=True)
plt.show()

rawDescription: Matplotlib animation, moving square

description: Matplotlib animation, moving square


code:
try:
    import json
except ImportError:
    import simplejson as json

rawDescription: Which JSON module can I use in Python 2.5?


code:
r, c = np.array(D.shape)-1
for a in range(1, r+c):
    # We have I>=0, I<r, J>0, J<c and J-I+1=a
    I = np.arange(max(0, a-c), min(r, a))
    J = I[::-1] + a - min(r, a) - max(0, a-c)
    # We have to use two np.minimum because np.minimum takes only two args.
    D[I+1, J+1] += np.minimum(np.minimum(D[I, J], D[I, J+1]), D[I+1, J])

rawDescription: Vectorized loop for dynamic time wrapping


code:
def frob(l):
    downcount = 0
    for ele in l:
        if downcount >= 2 and ele[0] == 'up' and ele[1] < 0.0095:
                return True
        downcount = (downcount + 1) if ele[0] == 'down' else 0
    return False

rawDescription: Counting backwards

description: Counting backwards


code:
def transFile():
    num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])
    previous =num_files                    # Count Number of Files before Transferred New Files
ip ="192.168.2.34"
os.system("rsync -rav pi@"+ip+":python ~/") # Command To transfer Files
num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])
present = num_files-previous
tkMessageBox.showinfo (" File Transfer", 'Number of Files Transfer is '+ str(present)+ '!')
a=0
for file in os.listdir('.'):
    if fnmatch(file, '*.*'):
        a +=1
        ttk.Label(mainframe, text=file).grid(row=4+a, column=10)

rawDescription: Retaining/Show the name of transferred files in Python GUI on Ubuntu


code:
class EnemyBox:
    def __init__(self):
        self.rect = Rect(0,0,50,50)
    def update(self):
        self.rect.move_ip(5,0)

rawDescription: How to make a completely invisible sprite in Pygame?

description: Make a completely invisible sprite in Pygame


code:
#! /usr/bin/env python

from collections import namedtuple
import time

A = namedtuple("A", "a b c")

def validate_until_true(f, condition, timeout):
    t = time.time() + timeout
    while time.time() < t:
        v = f()
        if condition(v): return True, v
        #print('.')
        time.sleep(1)
    return False, v

class Test:
    def __init__(self, param):
        self.param=param

    def test(self):
        f = lambda: A(1,2,3)
        condition = lambda v: v.a!=self.param and v.b==2
        result, v = validate_until_true(f, condition, 3)
        if result:
            print('True')
        else:
            msg = 'The condition "v.a!={0} and v.b==2" has not been met, v has the values: {1}'
            print(msg.format(self.param, str(v)[2:-1]))

t = Test(1)
t.test()

p = 7
print('Setting param to {0}'.format(p))
t.param = p
t.test()

rawDescription: String representation of lambda

description: String representation of lambda


code:
from rest_framework.response import Response

def view(request):
    ...
    serializer = TrgJobSerializer(DEV, many=True)
    response = {'trgjob': serializer.data}
    return Response(response)

rawDescription: Including model name in response

description: Including model name in response


code: mylist += [heights[iso+YEAR] for iso in set(BAR_Items) if iso+YEAR in heights]

rawDescription: Suggestions for improving this little piece of code?


code:
import socket
host_map = client[:].apply_async(socket.gethostname).get_dict()
r = { v:k for k,v in host_map.items() }
one_id_per_machine = list(r.values())
one_per_machine = client[one_id_per_machine]
lb_per_machine = client.load_balanced_view(one_id_per_machine)

rawDescription: Ipython parallel and multicore processes


code:
from sqlalchemy.sql import func

q = select([s.c.id]).\
    group_by(func.date(s.c.created_datetime)).\
    count()

rawDescription: sqlalchemy: applying an SQL-like date() function on a datetime column

description: Sqlalchemy: applying an SQL-like date() function on a datetime column


code:
from django.db.models.signals import m2m_changed

def fingers_changed(sender, **kwargs):
    #sender     Hand.fingers.through (the intermediate m2m class)
    #instance   hand (the Hand instance being modified)
    #action     "pre_add" (followed by a separate signal with "post_add")
    #reverse    False (Hand contains the ManyToManyField, so this call modifies the forward relation)
    #model      Finger (the class of the objects added to the Hand)
    #pk_set     finger_ids beign added (when post_add its a set of all,  not the new ones only, but all)
    #using      "default" (since the default router sends writes here)
    if kwargs['action'] == 'post_add':
        hand = kwargs['instance']
        hand.num_fingers = hand.fingers.count() #or len(kwargs['pk_set'])
        hand.has_thumb = hand.fingers.filter(is_a_thumb=True).exists()
        hand.save()

m2m_changed.connect(fingers_changed, sender=Hand.fingers.through)

rawDescription: How to check whether ManytoMany has values before saving Model?

description: Check whether ManytoMany has values before saving Model


rawDescription: Regex for replacing times with comma to a dot in Python


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

class DownloadSpider(CrawlSpider):
    name = 'downloader'
    allowed_domains = ['bnt-chemicals.de']
    start_urls = [
        "http://www.bnt-chemicals.de",
    ]
    rules = (
        Rule(SgmlLinkExtractor(allow='prod'), callback='parse_start_url', follow=True),
    )
    fname = 0

    def parse_start_url(self, response):
        self.fname += 1
        fname = '%s.txt' % self.fname

        with open(fname, 'w') as f:
            f.write('%s, %s\n' % (response.url, response.meta.get('depth', 0)))
            f.write('%s\n' % response.body)

rawDescription: Scrapy CrawlSpider doesn't crawl the first landing page


code:
a = array.array(a.typecode, sorted(a))
b = bytearray(sorted(b))

rawDescription: API: why don't Python arrays have a sort method?


code:
from mockito import mock, verify

# Setup ---------------------------------------------
my_mock = mock(ISightRequestingEngine)

system_under_test = ISightRequestingEngine()

system_under_test.testFunc = my_mock.testfunc # Mock out only testFunc()

# Exercise ------------------------------------------
system_under_test.startEngine()

# Verify --------------------------------------------
verify(my_mock).testFunc()

rawDescription: Testing a function call inside the function using python unittest framework


code: Shell ("cmd /C ""start pybot NameOfFile.txt""")

rawDescription: Execute Command prompt command from Excel Spread Sheet


code:
from heapq import nlargest
from random import random
nlargest(5, (random() for i in xrange(1000000)))

rawDescription: What would you use the heapq Python module for in real life?


code:
def find_str (string, substring):
    index = 0
    length = len (substring)
    for j in range(len(string)):
        if is_next_sub(string, substring, j):
            return j
    return "-1"

def is_next_sub(string, substring, index):
    for i in range(len(substring)):
        if substring[i] != string[index + i]:
            return False
    return True

rawDescription: Create Your Own Find String Function

description: Create Your Own Find String Function


rawDescription: Python string format, drop characters if too long


rawDescription: Generating all possible combinations of a zeros and b ones


rawDescription: grep with python to match string inside quotes in html files

description: Grep with python to match string inside quotes in html files


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

# Some random data
dfWIM = pd.DataFrame({'AXLES': np.random.randint(3, 13, 5000)})
ncount = len(dfWIM)

plt.figure(figsize=(12,8))
ax = sns.countplot(x="AXLES", data=dfWIM, order=[3,4,5,6,7,8,9,10,11,12])
plt.title('Distribution of Truck Configurations')
plt.xlabel('Number of Axles')

# Make twin axis
ax2=ax.twinx()

# Switch so count axis is on right, frequency on left
ax2.yaxis.tick_left()
ax.yaxis.tick_right()

# Also switch the labels over
ax.yaxis.set_label_position('right')
ax2.yaxis.set_label_position('left')

ax2.set_ylabel('Frequency [%]')

for p in ax.patches:
    x=p.get_bbox().get_points()[:,0]
    y=p.get_bbox().get_points()[1,1]
    ax.annotate('{:.1f}%'.format(100.*y/ncount), (x.mean(), y),
            ha='center', va='bottom') # set the alignment of the text

# Use a LinearLocator to ensure the correct number of ticks
ax.yaxis.set_major_locator(ticker.LinearLocator(11))

# Fix the frequency range to 0-100
ax2.set_ylim(0,100)
ax.set_ylim(0,ncount)

# And use a MultipleLocator to ensure a tick spacing of 10
ax2.yaxis.set_major_locator(ticker.MultipleLocator(10))

# Need to turn the grid on ax2 off, otherwise the gridlines end up on top of the bars
ax2.grid(None)

plt.savefig('snscounter.pdf')

rawDescription: Seaborn: countplot() with frequencies

description: Seaborn: countplot() with frequencies


code:
from cgi import escape
from json import dumps

ajax_response = dumps(escape(''
                             'FooBar & Friends'))

rawDescription: character escaping: from Python string literal to JSON and then to HTML

description: Character escaping: from Python string literal to JSON and then to HTML


code:
def f_openUsers(self):
    top = Toplevel()
    top.title("Users")
    top.focus_set()  # <- add this line

rawDescription: Python Tkinter Toplevel not the active window


rawDescription: Convert freq string to DateOffset in pandas


code:
class Colors(Enum):
    white = (255, 255, 255)
    black = (0, 0, 0)
    red = (255, 0, 0)
    green = (0, 255, 0)
    blue = (0, 0, 255)
    yellow = (255, 255, 0)

class Items(Enum):
    empty = 0
    food = 1
    poison = 2
    agent = 3

item_colors = {
    Items.empty: Colors.white,
    Items.food: Colors.green,
    Items.poison: Colors.red,
    Items.agent: Colors.blue
}

items = [0, 0, 3, 2]

def get_item_color(item):
    color = item_colors[Items(item)].value
    return color

for item in items:
    print(get_item_color(item))

rawDescription: Linking python enums

description: Linking python enums


code:
...
self.tree = ttk.Treeview(...)
self.tree.bind("<Double-1>", self.on_double_click)
...
def on_double_click(self, event):
    region = self.tree.identify("region", event.x, event.y)
    if region == "heading":
        ...

rawDescription: How to bind an action to the heading of a tkinter treeview in python?

description: Bind an action to the heading of a tkinter treeview in python


code:
CARD_VALUES=["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
SUIT_COLOR={"clubs": "black", "spades":"black", "hearts":"red", "diamonds":"red"}

class Card:
    def __init__(self, value, suit):
        if value not in CARD_VALUES:
            raise Exception("Invalid card value {}".format(value))

        if suit not in SUIT_COLOR:
            raise Exception("Invalid suit {}".format(suit))

        self.value = value
        self.suit = suit

    def suit_color(self):
        return SUIT_COLOR[self.suit]

    def card_value(self):
        return CARD_VALUES.index(self.value)

    def __repr__(self):
        return "({} of {})".format(self.value, self.suit)

class Row:
    def __init__(self):
        self.cards=[]

    def valid_add_card(self, card):
        if not self.cards:
            return True # true for empty deck

        last_card=self.cards[-1]
        return last_card.card_value()==card.card_value()+1 and last_card.suit_color()!=card.suit_color()

    def add_card(self, card):
        if self.valid_add_card(card):
            self.cards.append(card)
        else:
            raise Exception("Cannot add card {} to {}".format(card, self.cards[-1]))

    def __repr__(self):
        return " - ".join(str(c) for c in self.cards)

r=Row()
r.add_card(Card("J", "spades"))
r.add_card(Card("10", "hearts"))
r.add_card(Card("9", "clubs"))
print(r)
print("Last card won't work:")
r.add_card(Card("8", "spades"))

rawDescription: How could i add restrictions or rules to a list in Python


code:
def line_plot():
    x=np.linspace(-np.pi,np.pi,30)
    cosx=np.cos(x)
    sinx=np.sin(x)
    fig1, ax1 = plt.subplots()
    ax1.plot(x,np.sin(x), c='r', lw=3,label='cos') #added label here
    ax1.plot(x,np.cos(x), c='b', lw=3,label='sin') #added label here
    ax1.set_xlabel('x')
    ax1.set_ylabel('y')
    #ax1.legend(["cos","sin"]) #don't need this as the plots are already labelled now
    ax1.legend(loc=0);
    ax1.set_xlim([-3.14, 3.14])
    ax1.set_xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
    ax1.grid(True)
    ax1.set_xticklabels(['-'+r'$\pi$', '-'+r'$\pi$'+'/2',0, r'$\pi$'+'/2', r'$\pi$'])
    plt.show()

    return

if __name__ == "__main__":
    line_plot()

rawDescription: Why will my legend not move in Python

description: Why will my legend not move in Python


code:
df.groupby(level=0).filter(
    lambda df:np.in1d([2001, 2002], df.index.get_level_values(1)).all()
)

rawDescription: pandas remove observations depending on multi-index level value

description: Pandas remove observations depending on multi-index level value


code: set(i[3] for i in first).intersection(i[2] for i in second)

rawDescription: Getting identical values from two arrays with different structures and indexes in Python


code:
if '*' in needle or '_' in needle:
    looking_for = needle.replace('_', '__')\
                        .replace('*', '%')\
                        .replace('?', '_')
else:
    looking_for = '%{0}%'.format(needle)

result = db.table.filter(db.table.column.ilike(looking_for))

rawDescription: SQLAlchemy query where a column contains a substring


code:
class StripWhitespaceMiddleware(object):
    """
    Strips leading and trailing whitespace from response content.
    """

    def __init__(self):
        self.whitespace = re.compile('^\s*\n', re.MULTILINE)
        self.whitespace_lead = re.compile('^\s+', re.MULTILINE)
        self.whitespace_trail = re.compile('\s+$', re.MULTILINE)

    def process_response(self, request, response):
        if "text" in response.get('Content-Type', ''):
            response_content = response.content.decode('utf-8')
            if hasattr(self, 'whitespace_lead'):
                response_content = self.whitespace_lead.sub('', response_content)
            if hasattr(self, 'whitespace_trail'):
                response_content = self.whitespace_trail.sub('\n', response_content)

            # Uncomment the next line to remove empty lines
            if hasattr(self, 'whitespace'):
                response_content = self.whitespace.sub('', response_content)
            response.content = response_content.encode('utf-8')

        return response

rawDescription: Django form textarea strips newlines

description: Django form textarea strips newlines


code:
import numpy
import scipy.interpolate
import random
import matplotlib.pyplot as pyplot

# create some normally distributed values and make a histogram
a = numpy.random.normal(size=10000)
counts, bins = numpy.histogram(a, bins=100, density=True)
cum_counts = numpy.cumsum(counts)
bin_widths = (bins[1:] - bins[:-1])

# generate more values with same distribution
x = cum_counts*bin_widths
y = bins[1:]
inverse_density_function = scipy.interpolate.interp1d(x, y)
b = numpy.zeros(10000)
for i in range(len( b )):
    u = random.uniform( x[0], x[-1] )
    b[i] = inverse_density_function( u )

# plot both
pyplot.hist(a, 100)
pyplot.hist(b, 100)
pyplot.show()

rawDescription: probability density function from histogram in python to fit another histrogram

description: Probability density function from histogram in python to fit another histrogram


code:
cols = ['col1', 'col2']
df[cols]

rawDescription: Selecting Columns from Dataframe

description: Selecting Columns from Dataframe


code:
cost = input("Enter the price: ")
if len(cost.rsplit('.')[-1]) == 2:
   print('2 digits after decimal point')

rawDescription: Checking if input is a float and has exactly 2 numbers after the decimal point


code:
a = 15
for x in range(2,6):
    if a % x == 0:
        return False
return True

rawDescription: How do I get a for loop to iterate through an entire range?

description: Get a for loop to iterate through an entire range


code:
from django.contrib.auth.models import update_last_login

def notify_user_on_login(user):
    items = Item.objects.filter(status=Item.HISTORY_STATUS, seller=user, when_trading__gte=user.last_login)

@receiver(user_logged_in)
def after_user_logged_in(sender, user, **kwargs):
    notify_user_on_login(user)
    update_last_login(sender, user, **kwargs)

user_logged_in.disconnect(update_last_login)

rawDescription: Custom user_logged_in signal BEFORE django updates last_login


code:
import datetime
dt=datetime.datetime.strptime(data[4]+data[5],'%Y%m%d%H%M%S')
print(dt)
# 2010-03-04 08:28:35

rawDescription: Converting date/time in YYYYMMDD/HHMMSS format to Python datetime


code:
x = np.arange(10)
y = np.sin(x)
x_name = 'foo'
y_name = 'bar'
outfile = TemporaryFile()
np.savez(outfile, **{x_name: x, y_name: y})
outfile.seek(0)
npzfile = np.load(outfile)
npzfile.files

rawDescription: Use value of variable rather than keyword in python numpy.savez


code:
class TalkAdmin(admin.ModelAdmin):

    list_display = ['title', 'get_speakers', 'date']

    def get_speakers(self, obj):
        speakers = obj.speakers.all().order_by('name').values_list('name', flat=True)
        return ', '.join(speakers)

rawDescription: Alphabetically order values in a Many-to-Many relation, then list_display the first item


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

LL = -0.5
UL = 0.5

x=np.linspace(-20,20,100)
y=np.sin(x)

# plot original sine
plt.plot(x,y)

# zero output value for the dead zone
y[(y>=LL) & (y<=UL)] = 0

y[y>UL] -= UL
y[y<LL] -= LL

# plot "simulinked" ....
plt.plot(x,y)

plt.grid()
plt.show()

rawDescription: How to plot a deadband for a simple sine wave using python

description: Plot a deadband for a simple sine wave using python


code: entry = Entry(parent, width=20)

rawDescription: How to stop python Tkinter Entry Widget stretching in grid

description: Stop python Tkinter Entry Widget stretching in grid


code:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm

img = mpimg.imread("stewie.jpg")

f, axarr = plt.subplots(2, 2)
axarr[0,0].imshow(img, cmap = cm.Greys_r)
axarr[0,0].set_title("Rank = 512")
axarr[0,0].axis('off')

axarr[0,1].imshow(img, cmap = cm.Greys_r)
axarr[0,1].set_title("Rank = %s" % 128)
axarr[0,1].axis('off')

axarr[1,0].imshow(img, cmap = cm.Greys_r)
axarr[1,0].set_title("Rank = %s" % 32)
axarr[1,0].axis('off')

axarr[1,1].imshow(img, cmap = cm.Greys_r)
axarr[1,1].set_title("Rank = %s" % 16)
axarr[1,1].axis('off')

plt.show()

rawDescription: Turn off axes in subplots

description: Turn off axes in subplots


code:
env = dict(os.environ)
env['LC_ALL'] = 'en_US.UTF-8'
p = subprocess.Popen(['grep', '-E', mainconf["MSG_FORMAT"][msgtype,fieldname]], stdin=subprocess.PIPE, env=env)
p.communicate(datarecord[fieldname])
if p.returncode:
     return fieldname

rawDescription: subprocess call failing with unicode data from web form input - works with same input from elsewhere

description: Subprocess call failing with unicode data from web form input - works with same input from elsewhere


code:
objects1 = [1, 2, 3]
objects2 = ['1', '2', '3', '4']

mylist = [objects1, objects2]
max(mylist, key=len)
sorted(mylist, key=len, reverse=True)

rawDescription: How can i sort the list with keys in python

description: Sort the list with keys in python


code:
class MyDoc(Document):
    name = StringField()
    updated_at = DateTimeField(default=datetime.datetime.now)

    @classmethod
    def pre_save(cls, sender, document, **kwargs):
        document.updated_at = datetime.datetime.now()

signals.pre_save.connect(MyDoc.pre_save, sender=MyDoc)

rawDescription: Update DateTime field in mongoengine with auto_now_add


code:
try:
    from bs4 import BeautifulSoup as bs
except:
    from BeautifulSoup import BeautifulSoup as bs

bs.find_all = getattr(bs, 'find_all', False) or getattr(bs, 'findAll')

rawDescription: How to resolve the hardcoding when a newer version of the library i use uses a different function name? - python

description: Resolve the hardcoding when a newer version of the library i use uses a different function name? - python


code:
fname = "stuff.txt"
fhand = open(fname)
AllWords = list()      #create new list
ResultList = list()    #create new results list I want to append words to

for line in fhand:
    line.rstrip()   #strip white space
    words = line.split()    #split lines of words and make list
    AllWords.extend(words)   #make the list from 4 lists to 1 list

AllWords.sort()  #sort list

for word in AllWords:   #for each word in line.split()
    if word not in ResultList:    #if a word isn't in line.split
        ResultList.append(word)   #append it.

print(ResultList)

rawDescription: How do I remove duplicate words from a list in python without using sets?

description: Remove duplicate words from a list in python without using sets


code:
def find_parens(s):
    toret = {}
    pstack = []

    for i, c in enumerate(s):
        if c == '(':
            pstack.append(i)
        elif c == ')':
            if len(pstack) == 0:
                raise IndexError("No matching closing parens at: " + str(i))
            toret[pstack.pop()] = i

    if len(pstack) > 0:
        raise IndexError("No matching opening parens at: " + str(pstack.pop()))

    return toret

rawDescription: Indices of matching parentheses in Python


rawDescription: Python , check if a list follows a distribution


code:
import re
text = '[SOME-WORD "Quoted string"]'
pat = r'\[(?P<capitalitem>SOME-WORD)(\ ?)\"(?P<quotedstring>[\w\s]+)\"(\ ?)\]'
re.search(pat, text).groupdict()

rawDescription: Regexp problems, python

description: Regexp problems, python


code:
def bear_room():
    print("There is a bear here\n"
          "The bear has a bunch of honey\n"
          "The fat bear is in front of another door\n"
          "How are you going to move the bear?"
    )

rawDescription: Python triple quote returning indented string


code:
import re

s = '[attribute1=value1, attribute2=, attribute3=value3, attribute4=]'
re.sub(r'=(,|])', r'=None\1', s)

rawDescription: Python replace regex

description: Python replace regex


code:
from collections import defaultdict
d = defaultdict(set)
for index,city in loc_list:
  d[index].add(city)

for k,v in d.items():
  print(k,v)

rawDescription: merging sublists within a list sharing common index element

description: Merging sublists within a list sharing common index element


code:
journal_id = 10
query = 'SELECT COUNT(*) FROM data_journal_articles as data WHERE data.journal_id = %s AND data.article_id = data_article.id' % journal_id
articles = Article.objects.filter(
    date__gte = request_data['start_date'],
    date__lte = request_data['end_date'],
    ).extra(select={'is_checked': query})

rawDescription: Adding extra field to find whether the object is related to another one


code:
floor = -323

if turtle.ycor() > floor:
     turtle.sety(floor)

rawDescription: Python Turtle - Turtle Location

description: Python Turtle - Turtle Location


code:
class A:
    def __init__(self):
        self.x = [p for p in range(10)]

    def __getitem__(self, key):
        return self.x[key]

    def __setitem__(self, key, value):
        self.x[key] = value

rawDescription: On defining a setter in Python

description: On defining a setter in Python


code:
from paraview import simple
reader = simple.OpenDataFile("..../foo.pvd")
writer = simple.CreateWriter("..../foo.csv", reader)
writer.WriteAllTimeSteps = 1
writer.FieldAssociation = "Points"
writer.UpdatePipeline()

rawDescription: paraview python scripting equivalent of File->save Data

description: Paraview python scripting equivalent of File->save Data


code:
import numpy as np
my_array = np.random.randint(1,10, (4, 5))
pos = np.where(my_array > 5)
my_array[pos]

rawDescription: Conditional search returning tuples of arrays for 1D arrays?


code:
with open('input') as in_file, open('output', 'w') as out_file:
    for line in in_file:
        out_file.write(line.replace('\"', ''))

rawDescription: Python: CSV module. EscapeChar is messing up the output


code:
from collections import Counter
with open('path/to/file') as infile:
    counts = Counter(line.split('-', 1)[0].strip() for line in infile)
IPs = counts.most_common() # thanks @Jon Clements
# equivalent to IPs = sorted(counts, key=counts.__getitem__, reverse=True)

rawDescription: How do I open up a text file and use it in this code to sort ip adresses python

description: Open up a text file and use it in this code to sort ip adresses python


code:
from Tkinter import *

def delete_entries():
  for field in fields:
    field.delete(0,END)

def UserInput(status,name):
  optionFrame = Frame(root)
  optionLabel = Label(optionFrame)
  optionLabel["text"] = name
  optionLabel.pack(side=LEFT)
  var = StringVar(root)
  var.set(status)
  w = Entry(optionFrame, textvariable= var)
  w.pack(side = LEFT)
  optionFrame.pack()
  return w
  #this return is crucial because if you don't return your widget's identity,
  #you can not use them in another function

if __name__ == '__main__':
  root = Tk()
  ExperimentNumber = UserInput("1", "Experiment number")
  OutputFileName = UserInput("output.txt", "Output file name")
  npts1 = UserInput("1000", "Number of points")
  block1 = UserInput("8", "Block size")
  #you are saying it does not work because of they are strings.
  #then don't assign strings to fields. assign variables.
  fields = ExperimentNumber, OutputFileName, npts1, block1
  #since fields is defined in global scope, you don't need to use it as parameter

  Delete_button = Button(root, text = 'Clear all', command = delete_entries)
  Delete_button.pack()

rawDescription: Clear text from tkinter entry widget

description: Clear text from tkinter entry widget


code:
with open ('file.xml', 'w') as fd:
  buf.seek (0)
  shutil.copyfileobj (buf, fd)

rawDescription: What is the best way to write the contents of a StringIO to a file?


code:
sorts = [IntSort(), IntSort(), IntSort()]
return Function(fname, *sorts)

rawDescription: Declaring uninterpreted polyadic functions with Z3Py


rawDescription: DataFrame of DataFrames with pandas

description: DataFrame of DataFrames with pandas


code:
lst = [columns_to_add[x][j] for x in columns_to_add.keys()]
imported_feature.function_print(*lst[1:-1])

rawDescription: python send a list to an function( *arg)

description: Python send a list to an function( *arg)


rawDescription: xor with leading zero issue in python

description: Xor with leading zero issue in python


code:
urlpatterns = patterns('django.contrib.sitemaps.views',
    (r'^sitemap\.xml$', 'index', {'sitemaps': sitemaps}),
    (r'^sitemap-(?P<section>.+)\.xml$', 'sitemap', {'sitemaps': sitemaps}),
)

rawDescription: Creating sitemap for more than 50000 urls in Django


rawDescription: What's the most efficient way to search a list millions of times?


code:
from itertools import takewhile

if K is None:
    illuminacond = lambda x: x.split(',')[0] != '[Controls]'
    def action(cf, line): cf.write(line)
else:
    illuminacond = lambda x: x.split(',')[0] != '[Controls]' and i < K
    def action(cf, line): pass

af=open('a')
bf=open('b', 'w')
cf=open('c', 'w')

i = 0
for line in takewhile(illuminacond, af):
    line_split=line.split(',')
    pid=line_split[1][0:3]
    out = line_split[1] + ',' + line_split[2] + ',' + line_split[3][1] + line_split[3][3] + ',' \
                              + line_split[15] + ',' + line_split[9] + ',' + line_split[10]
    if pid!='cnv' and pid!='hCV' and pid!='cnv':
        i = i+1
        bf.write(out.strip('"')+'\n')
        action(cf, line)

rawDescription: avoiding code duplication in Python code redux

description: Avoiding code duplication in Python code redux


code:
my_list = ['a', 'b', 'c']
for other_list in (some_iterable, some_other_iterable, another_iterable):
    my_list.extend(other_list)

rawDescription: Extend: merge strings on a list from other lists (or variables) at the same time


code:
if (m, l, k) in xDict:
    om, ol, ok = xDict[m, l, k]

rawDescription: improve iteritems performance or a better way to loop through python dictionary

description: Improve iteritems performance or a better way to loop through python dictionary


rawDescription: wxPython wx.Frame with wx.Dialog effect

description: WxPython wx.Frame with wx.Dialog effect


code:
row = cur.fetchone()
while row:
   # do something with row
   row = cur.fetchone()

rawDescription: python postgres can I fetchall() 1 million rows?

description: Python postgres can I fetchall() 1 million rows


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

rawDescription: Looping functions python

description: Looping functions python


code:
# Goal: make a list of urls
url_list = []

# use a try-finally to make sure you close your file.
try:
    f = open('pathtofile.txt','rb')
    for line in f:
        url_list.append('http://youtube.com/user/%s' % line)
    # do something with url list (like call a scraper, or use urllib2
finally:
    f.close()

rawDescription: Iterating through multiple URLs from .txt file with Python/BeautifulSoup


code:
import numpy as np
X, Y, Z = np.genfromtxt('targets.csv', delimiter=',', unpack=True)

rawDescription: Python, load .csv in numpy arrays, return a list


code:
c = [item for item in a
     if any(name in item for name in b)]

rawDescription: Common characters within strings in 2 lists in Python


code:
a = list()
b = list()
a == b  # equal value
a is b
c = list()
c.append(a)
a in c
b in c
a.append("a value")
a == b  # now the values differ
a in c  # The value of 'a' changed, and 'a' is still in 'c'
b in c  # 'b' is still empty, and there's no empty list in 'c'

rawDescription: When Class Inherits from built-in List

description: When Class Inherits from built-in List


code:
title = 'I_hate_subscripts'
title = title.replace('_', '\_')
plt.title(title)

rawDescription: Prevent matplotlib from interpreting underscore as subscript in plot title


code:
with open('out.csv', 'r') as istr:
    with open('zhoutput.txt', 'w') as ostr:
        for line in istr:
            line = line.rstrip('\n') + ',1'
            print(line, file=ostr)

rawDescription: python script to output data as csv and not JSON object

description: Python script to output data as csv and not JSON object


code:
def OnClick():
     if not set_els: return

     # swap this with the line above if viz.pick has side effects that should occur
     A = viz.pick(0, viz.WORLD, all=False)
     if touch != A: return

     keys = (key for key in BAR_Items
             if BAR_Items[key] == A or SHAPES[key+"_SHP"] == A)

     for key in keys:
         if key in Selection:
             Selection.remove(key)
             BAR_Items[key].clearActions()
             VFrame.SetStatusText(frame, key + " has been deselected")
             viz.director(do_chart)
         else:
             Selection.append(key)

rawDescription: What abut this crazy sequence of loops and ifs? Ideas to improve this code?


code:
import re
arr = ["five", "+", "two", "*", "zero", "=", "five"]
map(re.escape, arr)
[re.escape(x) for x in arr]

rawDescription: adding backslash to symbols in python while using the regex library

description: Adding backslash to symbols in python while using the regex library


code:
class Data(db.Model):
  property = db.StringProperty()

data = Data(property = 'value')
data.put()

query = db.GqlQuery("SELECT * FROM Data")

myvar = 'property'

for line in query:
  getattr(line, myvar)

rawDescription: Use variable to get property value

description: Use variable to get property value


code:
cursor.execute("SELECT MIN(id) FROM title WHERE provider=%s"
               "AND vendor_id LIKE '%s%%'", (provider, vendor_id_stem))

rawDescription: Trouble escaping mysql statement in python


code:
plot([23, 456, 676, 89, 906, 34, 2345])
yscale('log')
grid(b=True, which='major', color='b', linestyle='-')
grid(b=True, which='minor', color='r', linestyle='--')

rawDescription: How to create Major and Minor gridlines with different Linestyles in Python

description: Create Major and Minor gridlines with different Linestyles in Python


code:
cursor.execute("SELECT * FROM table ORDER BY id DESC LIMIT 1")
result = cursor.fetchone()

rawDescription: Fetch the last row of a cursor with SQLite


code:
def get_queryset(self):
    if self.request.user.is_superuser:
        return User.objects.all()
    else:
        return User.objects.filter(id=self.request.user.id)

rawDescription: Django-rest-framework permissions for create in viewset


code:
N = 100000
s = ''.join([ chr(c % 26 + ord('a')) for c in range(N) ])

l = [ (26*i,26*i+3) for i in range(N//26) ]

l.sort(lambda x, y : cmp(x[0], y[0]))

ns = []
i = 0
for (start,end) in l:
    ns.append(s[i:start])
    i = end
ns.append(s[end:])
s = ''.join(ns)

rawDescription: Deleting parts of a big string given a list of indexes


code:
import dill
from collections import defaultdict
pos = defaultdict(lambda: 0)
neg = defaultdict(lambda: 0)
countdata = (pos,neg)
_countdata = dill.loads(dill.dumps(countdata))
_countdata
# now dump countdata to a file
with open('data.pkl', 'wb') as f:
    dill.dump(countdata, f)

rawDescription: pickling defaultdict with lambda

description: Pickling defaultdict with lambda


code: from gevent import monkey; monkey.patch_all()

rawDescription: Making Django go green

description: Making Django go green


code:
left_sorted_list = [1, 2, 3, 4, 5]
right_sorted_list = [[2, 21], [4, 45]]

right_dict = dict(right_sorted_list)
left_outer_join = [[l, right_dict.get(l)] for l in left_sorted_list]

rawDescription: How to efficiently left outer join two sorted lists

description: Efficiently left outer join two sorted lists


code:
import struct
def make_address(addr):
    return struct.pack(">H", addr)
make_address(1)

rawDescription: Python String to Bytes

description: Python String to Bytes


code:
from mm import multimethod

@multimethod(list, dict)
def itersources(sources, samples):
    for key, value in sources.iteritems():
        yield value, samples[key]

@multimethod(list, list)
def itersources(sources, samples):
    for key, value in sources.iteritems():
        yield value, samples

def fn(sources, samples):
    for value1, value2 in itersources(sources, samples):
        do_something_with(value1, value2)

rawDescription: design recommendation: control flow based on argument type in Python?

description: Design recommendation: control flow based on argument type in Python


code: dstk['dropflag'] = np.where(dstk.col <= criteria, 1, 0)

rawDescription: Pandas Optimized Way to Create Dummy-Variable?


rawDescription: generate a patterned numpy matrix

description: Generate a patterned numpy matrix


code:
frames = []
while verify:
    # download data
    # temp = pd.DataFrame(data)
    frames.append(temp)
    if condition_met:
        verify = False

pd.concat(frames)

rawDescription: Python Pandas - Using list comprehension to concat data frames


code:
time.strftime("%Y/%m/%d %H:%M")
time.replace(minute=last_quarter_minute).strftime("%Y/%m/%d %H:%M")

rawDescription: Python - Calculate last quarter hour of current time


code:
def half_hour_from_utc(time_utc = None):
    tz = pytz.timezone('Pacific/Auckland')
    time_nz = tz.normalize(time_utc)
    time_start_of_day = tz.localize(datetime.datetime(time_nz.year, time_nz.month, time_nz.day))
    total_secs = int((time_nz - time_start_of_day).total_seconds())
    half_hour = 1 + total_secs // 1800
    print('%s %s %s %s\n' % (time_nz, time_start_of_day, total_secs, half_hour))

rawDescription: Getting number of seconds elapsed in `Wall Clock' time


code:
import sys

def win_getpass(prompt='Password: ', stream=None):
    """Prompt for password with echo off, using Windows getch()."""
    import msvcrt
    for c in prompt:
        msvcrt.putch(c)
    pw = ""
    while 1:
        c = msvcrt.getch()
        if c == '\r' or c == '\n':
            break
        if c == '\003':
            raise KeyboardInterrupt
        if c == '\b':
            pw = pw[:-1]
            msvcrt.putch('\b')
        else:
            pw = pw + c
            msvcrt.putch("*")
    msvcrt.putch('\r')
    msvcrt.putch('\n')
    return pw

rawDescription: How to read password with echo "*" in Python console program?

description: Read password with echo "*" in Python console program


code:
def strtr(strng, replace):
    buffer = []
    i, n = 0, len(strng)
    while i < n:
        match = False
        for s, r in replace.items():
            if strng[i:len(s)+i] == s:
                buffer.append(r)
                i = i + len(s)
                match = True
                break
        if not match:
            buffer.append(strng[i])
            i = i + 1
    return ''.join(buffer)

rawDescription: php's strtr for python

description: Php's strtr for python


code: string_str = re.sub(r'[^-\d]', "", string_str)

rawDescription: Python regex issue with negative numbers


rawDescription: view does not work with transposed array

description: View does not work with transposed array


code:
#!/usr/bin/env python
# -.- coding: utf-8 -.-
import sys
from PySide import QtGui, QtCore

class Tab(QtGui.QWidget):
    popOut = QtCore.Signal(QtGui.QWidget)
    popIn = QtCore.Signal(QtGui.QWidget)

    def __init__(self, parent=None):
        super(Tab, self).__init__(parent)

        popOutButton = QtGui.QPushButton('Pop Out')
        popOutButton.clicked.connect(lambda: self.popOut.emit(self))
        popInButton = QtGui.QPushButton('Pop In')
        popInButton.clicked.connect(lambda: self.popIn.emit(self))

        layout = QtGui.QHBoxLayout(self)
        layout.addWidget(popOutButton)
        layout.addWidget(popInButton)

class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__()

        self.button = QtGui.QPushButton('Add Tab')
        self.button.clicked.connect(self.createTab)
        self._count = 0
        self.tab = QtGui.QTabWidget()
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)
        layout.addWidget(self.tab)

    def createTab(self):
        tab = Tab()
        tab.setWindowTitle('%d' % self._count)
        tab.popIn.connect(self.addTab)
        tab.popOut.connect(self.removeTab)
        self.tab.addTab(tab, '%d' % self._count)
        self._count += 1

    def addTab(self, widget):
        if self.tab.indexOf(widget) == -1:
            widget.setWindowFlags(QtCore.Qt.Widget)
            self.tab.addTab(widget, widget.windowTitle())

    def removeTab(self, widget):
        index = self.tab.indexOf(widget)
        if index != -1:
            self.tab.removeTab(index)
            widget.setWindowFlags(QtCore.Qt.Window)
            widget.show()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    w = Window()
    w.show()

    sys.exit(app.exec_())

rawDescription: How to pop out a separate window from a tabWidget in PySide Qt

description: Pop out a separate window from a tabWidget in PySide Qt


code:
from xlsxwriter.workbook import Workbook

# Create an new Excel file and add a worksheet.
workbook = Workbook('images.xlsx')
worksheet = workbook.add_worksheet()

# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 30)

# Insert an image.
worksheet.write('A2', 'Insert an image in a cell:')
worksheet.insert_image('B2', 'python.png')

workbook.close()

rawDescription: how to insert jpeg image into excel sheet in unix

description: Insert jpeg image into excel sheet in unix


code:
class InstancesList(object):
    def __new__(cls, *args, **kw):
        if not hasattr(cls, 'instances'):
            cls.instances = []
        return super(InstancesList, cls).__new__(cls, *args, **kw)

    def __init__(self):
        self.index = len(type(self).instances)
        type(self).instances.append(self)

class Foo(InstancesList):
    def __init__(self, arg1, arg2):
        super(Foo, self).__init__()
        # Foo-specific initialization

rawDescription: How do I create a simple metaclass?

description: Create a simple metaclass


code:
import Tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

def main():
    fig = plot(range(10), range(10))
    root = tk.Tk()
    canvas = FigureCanvasTkAgg(fig, master=root)
    canvas.get_tk_widget().pack()

    root.bind_all('<Button-1>', lambda event: remove_plot(canvas))

    root.mainloop()

def plot(x, y):
    fig = Figure()
    ax1 = fig.add_subplot(1,1,1)
    ax1.plot(x,y)
    return fig

def remove_plot(canvas):
    canvas.get_tk_widget().destroy()

main()

description: Close/Unpack Object "matplotlib.backends.backend_tkagg.FigureCanvasTkAgg"


rawDescription: python pandas flatten a dataframe to a list

description: Python pandas flatten a dataframe to a list


code: dosomething("This says 'hello fail!'", thing3='fail!')

rawDescription: How to supply not all default arguments in python?

description: Supply not all default arguments in python


code:
import wx

class SelectableFrame(wx.Frame):

    c1 = None
    c2 = None

    def __init__(self, parent=None, id=-1, title=""):
        wx.Frame.__init__(self, parent, id, title, size=wx.DisplaySize())

        self.panel = wx.Panel(self, size=self.GetSize())

        self.panel.Bind(wx.EVT_MOTION, self.OnMouseMove)
        self.panel.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
        self.panel.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
        self.panel.Bind(wx.EVT_PAINT, self.OnPaint)

        self.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))

        self.SetTransparent(50)

    def OnMouseMove(self, event):
        if event.Dragging() and event.LeftIsDown():
            self.c2 = event.GetPosition()
            self.Refresh()

    def OnMouseDown(self, event):
        self.c1 = event.GetPosition()

    def OnMouseUp(self, event):
        self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))

    def OnPaint(self, event):
        if self.c1 is None or self.c2 is None: return

        dc = wx.PaintDC(self.panel)
        dc.SetPen(wx.Pen('red', 1))
        dc.SetBrush(wx.Brush(wx.Color(0, 0, 0), wx.TRANSPARENT))

        dc.DrawRectangle(self.c1.x, self.c1.y, self.c2.x - self.c1.x, self.c2.y - self.c1.y)

    def PrintPosition(self, pos):
        return str(pos.x) + " " + str(pos.y)

class MyApp(wx.App):

    def OnInit(self):
        frame = SelectableFrame()
        frame.Show(True)
        self.SetTopWindow(frame)

        return True

app = MyApp(0)
app.MainLoop()

rawDescription: Python drawing on screen

description: Python drawing on screen


code:
from Tkinter import *

def createBox(window):
    list_ = ['CARGA', 'MAQUINA', 'SOLTAR']
    for i in xrange(3):
        mybox = LabelFrame(window, padx=5, pady=4)
        mybox.grid(row=i, column=0)
        createWindow(mybox, list_[i], i)

def createWindow(box, lt_actual, i):
    canvas = Canvas(box, borderwidth=0)
    frame = Frame(canvas)
    vsb = Scrollbar(box, orient="vertical", command=canvas.yview)
    canvas.configure(yscrollcommand=vsb.set, width=1200, heigh=80)

    vsb.pack(side="right", fill="y")
    canvas.pack(side="left", fill="both", expand=True)
    canvas.create_window((4,4), window=frame, anchor="nw", tags="frame")

    # be sure that we call OnFrameConfigure on the right canvas
    frame.bind("<Configure>", lambda event, canvas=canvas: OnFrameConfigure(canvas))

    fillWindow(lt_actual, frame)

def fillWindow(lt_ver, frame):
    piezas = ['time: 39.41597 BT: 3025.5923', 'time: 21.637377 BT: 3025.5923', 'time: 52.185192 BT: 3025.5923', 'time: 57.804752 BT: 3025.5923', 'time: 47.700306 BT: 3025.5923', 'time: 21.1827 BT: 3025.5923', 'time: 35.244156 BT: 3025.5923', 'time: 47.26321 BT: 3025.5923']
    fechaentrada = ['26-02-2014', '26-02-2014', '26-02-2014', '26-02-2014', '26-02-2014', '26-02-2014', '26-02-2014', '21-02-2014']
    fechasalida = ['26-02-2014', '26-02-2014', '26-02-2014', '26-02-2014', '26-02-2014', '26-02-2014', '26-02-2014', '21-02-2014']
    horacomienzo = ['12:00', '12:39', '01:00', '01:52', '02:49', '03:36', '03:57', '12:00']
    horafinal = ['12:39', '01:00', '01:52', '02:49', '03:36', '03:57', '04:32', '12:47']
    ide = [0, 1, 2, 3, 4, 5, 6, 7]

    idpieza_w1 = Label(frame, text = "Id", width=20, font="bold")
    idpieza_w1.grid(row=0, column=0)
    pieza_w1 = Label(frame, text = "Pieza", width=20, font="bold")
    pieza_w1.grid(row=0, column=1)
    fechainiciopromo_w1 = Label(frame, text = "Dia inicio " + str(lt_ver), width=20, font="bold")
    fechainiciopromo_w1.grid(row=0, column=2)
    horainiciopromo_w1 = Label(frame, text = "Hora inicio "  + str(lt_ver), width=20, font="bold")
    horainiciopromo_w1.grid(row=0, column=3)
    fechafinalpromo_w1 = Label(frame, text = "Dia fin carga "  + str(lt_ver), width=20, font="bold")
    fechafinalpromo_w1.grid(row=0, column=4)
    horafinalpromo_w1 = Label(frame, text = "Hora final carga "  + str(lt_ver), width=20, font="bold")
    horafinalpromo_w1.grid(row=0, column=5)

    for i in xrange(len(piezas)):
        idtextos_w1 = Label(frame, text=str(ide[i]))
        idtextos_w1.grid(row=i+1, column=0)
        textos_w1 = Label(frame, text=str(piezas[i]))
        textos_w1.grid(row=i+1, column=1)
        fechainiciogrid_w1 = Label(frame, text=str(fechaentrada[i]))
        fechainiciogrid_w1.grid(row=i+1, column=2)
        horainiciogrid_w1 = Label(frame, text=str(horacomienzo[i]))
        horainiciogrid_w1.grid(row=i+1, column=3)
        fechafinalgrid_w1 = Label(frame, text=str(fechasalida[i]))
        fechafinalgrid_w1.grid(row=i+1, column=4)
        horafinalgrid_w1 = Label(frame, text=str(horafinal[i]))
        horafinalgrid_w1.grid(row=i+1, column=5)

def OnFrameConfigure(canvas):
    canvas.configure(scrollregion=canvas.bbox("all"))

tk = Tk()

createBox(tk)

tk.mainloop()

rawDescription: Tkinter - Add scrollbar for each LabelFrame


code:
def listpage(self, response):
    # Parses the entries on the page, and stores them
    sel = Selector(response)
    entries = sel.xpath("//table[@id='gv_Subsribers']").css("tr")
    items = []
    for entry in entries:
        item = Contact()
        item['name'] = entry.xpath('/td[0]/text()')
        yield item

    # remember get next has to return Request with callback=self.listpage
    yield self.getNext10()

rawDescription: Scrapy: Use Feed Exporter to store Items without using return


code:
datei = ET.parse(settings.MEDIA_ROOT+'\\table.xml')
datas = datei.getroot()

for info in datas.findall('info'):
    if info.find('Country').text == 'GERMANY':
        # do whatever
        pass

rawDescription: how do i check for specific element value before reading this xml - django python

description: Check for specific element value before reading this xml - django python


code:
import re
pat="(.+)\.(avi|rar|zip|txt)"
re.search(pat, "abcdefg.zip", re.IGNORECASE).groups()
re.search(pat, "abcdefg.ZIP", re.IGNORECASE).groups()

rawDescription: python regex question

description: Python regex question


code:
author = request.user
Review.objects.filter(chapter__work__user=author)

rawDescription: Django: Most efficient way to link two elements in different tables


code:
import ast
from nltk.parse.stanford import StanfordDependencyParser
dependency_parser = StanfordDependencyParser(  model_path="edu\stanford\lp\models\lexparser\englishPCFG.ser.gz")

with open('sample.txt',encoding="latin-1") as f:
    lines = [ast.litral_eval(line) for line in f.readlines()]

for line in lines:
    parsed_lines = dependency_parser.raw_parse(line)

# now parsed_lines should contain the parsed lines from the file

rawDescription: How to parse more than one sentence from text file using Stanford dependency parse?

description: Parse more than one sentence from text file using Stanford dependency parse


code:
import numpy as np
pred = np.array(mod_fit.predict(test) > threshold, dtype=float)
table = np.histogram2d(test.Y, pred, bins=2)[0]

rawDescription: Getting 'pred_table' information for predicted values of a model in 'statsmodels'


code:
class MyClass(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def __repr__(self):
        return "%s(%r, %r)" % (type(self).__name__, self.a, self.b)

rawDescription: Allowing the repr() of my class's instances to be parsed by eval()


code: a[:, np.newaxis] - b

rawDescription: Element-wise subtraction of two numpy arrays


rawDescription: Django URL: Multiple URL, same views. Then use {% url %} in template


code: return (seed + (n - 1) * incrementor) % modulo

rawDescription: More efficient way to write this simple Python non-sequential number generator?


code:
class a:
    def __init__(self):
        self.list = []

rawDescription: How do I avoid having Python class data shared among instances?

description: Avoid having Python class data shared among instances


code:
import boto.utils
md = boto.utils.get_instance_metadata(timeout=.1, num_retries=0)

rawDescription: Find out if the current machine is on aws in python


code:
from django.utils.encoding import smart_str

response = HttpResponse(mimetype='application/force-download') # mimetype is replaced by content_type for django 1.7
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
response['X-Sendfile'] = smart_str(path_to_file)
# It's usually a good idea to set the 'Content-Length' header too.
# You can also set any other required headers: Cache-Control, etc.
return response

rawDescription: Having Django serve downloadable files

description: Having Django serve downloadable files


code:
import os
import sys
import json
from IPy import IP
filepath="E:/Work/"
filename="data.txt"
result = list()
with open(os.path.join(filepath+filename)) as file:
  for line in file:
     ip = line.strip()
     if ip.startswith("0"):
        result.append({"ip": line.strip(), "status": "invalid"})
     else:
        try:
            ip_add=IP(ip)
            result.append({"ip": line.strip(), "status": "Valid"})
        except ValueError:
            result.append({"ip": line.strip(), "status": "invalid"})
print(json.dumps(result))

rawDescription: Read text file and dump to json object

description: Read text file and dump to json object


rawDescription: python - convert string '2015-04-11 21:23:39+0530' to datetime

description: Python - convert string '2015-04-11 21:23:39+0530' to datetime


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

df = pd.DataFrame(data={'x':[0,1,2,3,4], 'y':[0,0.5,1,1.5,2]})

ax = df.plot(ylim=(0,5), marker='x')

plt.show()

rawDescription: How can I define scope for plotting graph in Pandas?

description: Define scope for plotting graph in Pandas


code:
from itertools import chain

l = [[1,2,3],[4,5]]
list(chain.from_iterable(l))

rawDescription: unpack lists of list into list with individual items

description: Unpack lists of list into list with individual items


code:
from chameleon import PageTemplate

t = PageTemplate('some string template')
rendered_content = t.render(encoding='utf-8')

rawDescription: Python, Pyramid, Chameleon : parse Chameleon template in string


code:
import requests
from bs4 import BeautifulSoup

# Get login form
URL = 'https://www.linkedin.com/uas/login'
session = requests.session()
login_response = session.get('https://www.linkedin.com/uas/login')
login = BeautifulSoup(login_response.text)

# Get hidden form inputs
inputs = login.find('form', {'name': 'login'}).findAll('input', {'type': ['hidden', 'submit']})

# Create POST data
post = {input.get('name'): input.get('value') for input in inputs}
post['session_key'] = 'username'
post['session_password'] = 'password'

# Post login
post_response = session.post('https://www.linkedin.com/uas/login-submit', data=post)

# Get home page
home_response = session.get('http://www.linkedin.com/nhome')
home = BeautifulSoup(home_response.text)

rawDescription: How could I use python-request to grab a linkedin page?


code:
def __dir__(self):
    return self.keys()

rawDescription: ipython tab completion for custom dict class

description: Ipython tab completion for custom dict class


rawDescription: Finding roots with scipy.optimize.root

description: Finding roots with scipy.optimize.root


code:
import tkinter as tk

root = tk.Tk()
root.iconbitmap("myIcon.ico")

rawDescription: how to replace the icon in a Tkinter app

description: Replace the icon in a Tkinter app


fileLocation: relative ${workspaceRoot}

rawDescription: How to execute Python code from within Visual Studio Code

description: Execute Python code from within Visual Studio Code


code:
class Alien():
    # pass the Surface to the instance instead of the filename
    # this way, you only load the image once, not once for each alien
    def __init__(self, image):
        self.speed = random.randint(1, 5)
        self.image = image
        # since we're going to use a Rect of drawing, let's use the
        # same Rect to store the correct position of the alien
        self.rect = self.image.get_rect(top=random.randrange(-200, -20), left=random.randrange(20,width - 20))

    def move_down(self):
        # the Rect class has a lot of handy functions like move_ip
        self.rect.move_ip(0, self.speed)

    def draw(self, screen):
        screen.blit(self.image, self.rect)

# load the image once. In more complex games, you usually
# want to abstract the loading/storing of images
alienimage = pygame.image.load(os.path.join("../images", 'alien.png')).convert_alpha()
for _ in range (20):
    aliens = Alien(alienimage)
    enemies.append(aliens)

done = False
while done == False:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    screen.fill(white)

    # just use a "regular" for loop to loop through all enemies
    for enemy in enemies:
        enemy.move_down()
        enemy.draw(screen)
        enemy.check_landed()

    pygame.display.flip()
    clock.tick(30)

rawDescription: pygame sprite and draw method not working as expected

description: Pygame sprite and draw method not working as expected


code:
def mari(x):
    s = 0.0 # current sum
    cnt = 0 # current count
    m = [] # list to return
    for i in x:
        s += i
        cnt += 1
        m.append(s / cnt)
    return m

rawDescription: Arithmetic mean for 'i' elements

description: Arithmetic mean for 'i' elements


code:
p = high_low_teams_in_profile
{ prof:sum(p[prof][team][hl]
           for team in p[prof]
           for hl in p[prof][team])
  for prof in p}

rawDescription: Python: Summing values nested inside different dictionaries in a nested dictionary


code:
class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(MyForm, self).__init__(*args, **kwargs)

# in you view
form = MyForm(user=request.user)

rawDescription: Reverse looking up a table linked to the profile model linked to the User model


code:
a = 2
b = lambda: a + 2
b()
a = 3
b()

rawDescription: How to create recalculating variables in Python

description: Create recalculating variables in Python


code:
tag1 = rally.create('Tag', dict(Name=info['test_id']))
tag2 = rally.create('Tag', dict(Name=info['platform']))

tags = [ dict(_ref=tag1.ref), dict(_ref=tag2.ref)]

defect = { "Tags" : tags }

rawDescription: Rally python api - Adding a Tag to an entity?


code:
from flask import Flask
from Cheetah.Template import Template

mainTemplate = """

    <title>$title</title>

$title

"""

app = Flask(__name__)

@app.route('/')
def main_route():
    return render(mainTemplate, {'title': 'Welcome to "/"!'})

def render(template, context):
    """Helper function to make template rendering less painful."""
    return str(Template(template, namespaces=[context]))

if __name__ == "__main__":
    app.run()

rawDescription: cheetah templating with flask

description: Cheetah templating with flask


code:
def __copy__(self):
    clone = copy.deepcopy(self)
    clone._b = some_op(clone._b)
    return clone

rawDescription: Python copy : How to inherit the default copying behaviour?


code:
import concurrent.futures
from dns import resolver, reversename
dns_resolver = resolver.Resolver()
dns_resolver.timeout = 1
dns_resolver.lifetime = 1
ips = [...]
results = []

with concurrent.futures.ThreadPoolExecutor(max_workers = 16) as pool:
    results = list(pool.map(get_hostname_from_ip, ips))

def get_hostname_from_ip(ip):
    try:
        reverse_name = reversename.from_address(ip)
        return dns_resolver.query(reverse_name, "PTR")[0].to_text()[:-1]
    except:
        return ""

rawDescription: Python Asynchronous Reverse DNS Lookups

description: Python Asynchronous Reverse DNS Lookups


code:
import numpy as np

# make sure it is a numpy.array
v = np.array(v)

# vectorized computation
N = (v >> 7) & 255

rawDescription: Parallelize operations for each cell in a numpy array


code:
import sublime_plugin

class TestCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        settings = self.view.settings()
        settings.add_on_change("color_scheme", self.callback)

    def callback(self):
        print(self.view.settings().get("color_scheme"))

rawDescription: How to detect set_user_setting event in Sublime Text 2

description: Detect set_user_setting event in Sublime Text 2


code:
value1 = 2
try:
  vset = set(value1)
except TypeError:
  vset = set([value1])

rawDescription: Converting either an integer or a list of integers to a set


code:
import wx

class SizeEvent(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Centre()
        self.SetSizeWH(400, 300)
        self.Show(True)

    def OnSize(self, event):
        hsize = event.GetSize()[0] * 0.75
        self.SetSizeHints(minW=-1, minH=hsize, maxH=hsize)
        self.SetTitle(str(event.GetSize()))

app = wx.App()
SizeEvent(None, 1, 'sizeevent.py')
app.MainLoop()

rawDescription: Resizing a wxPython Window

description: Resizing a wxPython Window


rawDescription: How to mask numpy structured array on multiple columns?

description: Mask numpy structured array on multiple columns


code:
"""This pure Python MySQL client provides a DB-API to a MySQL database by talking directly to the server via the binary client/server protocol."""

import pymysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock', user='root', passwd=None, db='mysql')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
for response in cur:
    print(response)
cur.close()
conn.close()

rawDescription: Python 3.3 Mysql Connector

description: Python 3.3 Mysql Connector


code:
# True is where condition is satisfied: numpy.ndarray([False, False, ..., True, True])
mask = t > 3

# Uninitialized array with same shape as t
Light = numpy.empty_like(t)

# Light elements set to 5 where corresponding mask elements are True
Light[mask] = 5

# Light elements set to 10 where corresponding mask elements are False
Light[~mask] = 10

rawDescription: python array basic usage: step-function

description: Python array basic usage: step-function


code:
def Timer(*args, **kwargs):
    return _Timer(*args, **kwargs)

class _Timer(Thread):
    """Call a function after a specified number of seconds:

    t = Timer(30.0, f, args=[], kwargs={})
    t.start()
    t.cancel() # stop the timer's action if it's still waiting
    """

    def __init__(self, interval, function, args=[], kwargs={}):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.finished = Event()

    def cancel(self):
        """Stop the timer if it hasn't finished yet"""
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()

rawDescription: Is there any way to extend threading.Timer in python


code:
def paths(tree, sum_so_far):
    #Helper function
    #receives a tree and
    #returns all paths that have this node as root
    if not tree:
        return []
    else: #tree is a node
        root = tree.ID
        val = tree.Value
        rooted_paths = [[[root], value]]
        for subtree in tree.nextDest:
            useable = paths(subtree, sum_so_far + val)
            for path in useable:
                rooted_paths.append([[root]+path[0], path[1]])
    return rooted_paths

rawDescription: Enumerating all paths in a tree and manipulate values associated with each node


code:
if grid_z1.T[i][j] > z0 or math.isnan(grid_z1.T[i][j]):
    grid_z1.T[i][j] = np.nan

rawDescription: scipy.interpolate.griddata: cut z-value and get area inside it

description: Scipy.interpolate.griddata: cut z-value and get area inside it


code:
backup_suffix = site.FileSuffix(backup_picked)

# Do the actual restoration here. Use sed to rename every instance in the files that will be created below.
# Make sure the created files get removed before finishing.
for tbl in selected_tables:
    table_file_name = str(tbl) + backup_suffix + ".sql"

    # Open a file each iteration, dump the table in to it. Use .wait() to make sure the command finishes.
    table_file = open(table_file_name, "w")
    p1 = subprocess.Popen(["/usr/bin/pg_restore", backup_picked, "-t", tbl], stdout=table_file)
    p1.wait()
    table_file.close()

    # Rename every instance of the table in the restore file. Format: _backup_YYYYMMDD
    sed_guts = "s/" + str(tbl) + "/"  + str(tbl) + backup_suffix + "/g"
    p2 = subprocess.Popen(["/bin/sed", "-i", sed_guts, table_file_name])
    p2.wait()

    # Use psql to restore the tables.
    try:
        site_config = site.ParseConfig(target_site)
        dontuse, site_config = addFlags(site_config, site_config)

        command = '/usr/bin/psql %s %s %s %s < %s' % (site_config['host'], site_config['dbusername'],
                                                       site_config['dbname'], site_config['port'], table_file_name)

        p2 = subprocess.Popen('%s' % command, shell=True)
        p2.communicate()[0]

        os.remove(table_file_name)

    except:
        os.remove(table_file_name)
        session.CleanUp()

    exit(0)

rawDescription: Executing a sql file in psycopg2

description: Executing a sql file in psycopg2


code:
import wx
import random

class Points(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(250, 150))

        self.Bind(wx.EVT_PAINT, self.OnPaint)

        self.Centre()
        self.Show(True)

    def OnPaint(self, event):
        w, h = self.GetClientSize()
        dc = wx.PaintDC(self)
        dc.SetBrush(wx.Brush('RED'))
        dc.DrawCircle(w/2,h/2, 20)

app = wx.App()
Points(None, -1, 'Test')
app.MainLoop()

rawDescription: align wx.DrawCircle to the center of the frame

description: Align wx.DrawCircle to the center of the frame


code:
class User:
    hash = ""
    def __init__(self, hash):
            self.hash = hash
u1 = User("hash1")
User.hash
u1.hash

rawDescription: Comparing same string where one is from Flask and one from a sqlite3 database


code:
def map_params(func):
    def decorated(request):
        return func(request, **request.GET)
    return decorated

@map_params
def some_view(request, param1, param2):
    ...

rawDescription: Auto GET to argument of view

description: Auto GET to argument of view


code:
import linecache
from random import randint

pokemon_selection = randint(1, 40)
pokemon = linecache.getline("pokedex.txt", pokemon_selection)

rawDescription: genereting list from file python

description: Genereting list from file python


code:
import os, signal

os.kill(pid, signal.SIGHUP) # Unix version only...

rawDescription: Can I raise a signal from python?

description: Raise a signal from python


code:
import itertools

[[float(aaa) / bbb for (aaa, bbb) in itertools.izip(aa, bb)] \
    for (aa, bb) in itertools.izip(a, b)]

rawDescription: How to divide list item by list item from another list using Python?

description: Divide list item by list item from another list using Python


rawDescription: Using Javascript to change all textareas in an html page


rawDescription: Python CGI Open file with absolute URL path


code:
s = statuses[0] # save just the first one for now
tweet = s.AsDict()
tweet["_id"] = "%d" % tweet["id"]
# (Couch stuff same as before)
dbcouch.save(tweet)

rawDescription: How can I use an existing property as the doc_id using Python CouchDb library Create or Save methods?

description: Use an existing property as the doc_id using Python CouchDb library Create or Save methods


code:
apiapp.config['TESTING'] = True
apitest = apiapp.test_client()

apicontentapp.config['TESTING'] = True
contenttest = apicontentapp.test_client()

rawDescription: Testing with two servers launched

description: Testing with two servers launched


rawDescription: python string splitting

description: Python string splitting


code:
fruit = 'Pear'
print("Hey, {fruit}".format(**locals()))

rawDescription: Variable interpolation in Python

description: Variable interpolation in Python


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

np.random.seed(2)
data = np.random.randn(100, 10)
cm = sns.clustermap(data)
hm = cm.ax_heatmap.get_position()
plt.setp(cm.ax_heatmap.yaxis.get_majorticklabels(), fontsize=6)
cm.ax_heatmap.set_position([hm.x0, hm.y0, hm.width*0.25, hm.height])
col = cm.ax_col_dendrogram.get_position()
cm.ax_col_dendrogram.set_position([col.x0, col.y0, col.width*0.25, col.height*0.5])

rawDescription: Changing the size of the heatmap specifically in a seaborn clustermap?


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

summary = pd.concat([mean, std], axis=1)
chart1, ax1 = plt.subplots()
sns.tsplot(sample['x'].cumsum(), ax=ax1)

chart2, ax2 = plt.subplots()
sns.tsplot(summary['mean'], ax=ax2)
result = [summary, chart1, chart2]
return result

rawDescription: How to obtain 2 separate plots in seaborn?

description: Obtain 2 separate plots in seaborn


code:
class Point(object):
    def __init__(x, y):
        self.x = x
        self.y = y

    @staticmethod
    def init_from_point(obj):
        return Point(obj.x, obj.y)

rawDescription: How to upgrade Python objects after module reloading?

description: Upgrade Python objects after module reloading


code:
from graphics import *
from random import *
import math

def main():
  win = GraphWin("Dots", 1100, 650)
  dots = []
  for x in xrange(250):
    #Create a random circle
    circle = getdrawCircle(15, 635, 15, 1085, 15, 15)
    #Repeat while overlap with other circles
    while checkOverLap(circle, dots):
      #Create a new random circle
      circle = getdrawCircle(15, 635, 15, 1085, 15, 15)
    #The new circle isn't overlap, then append to list dots
    dots.append(circle)
  drawAllCircles(win, dots)

def getdrawCircle(min_height, max_height, min_width, max_width, min_radius, max_radius):
  x = randint(min_height, max_height)
  y = randint(min_width, max_width)
  dot = Circle(Point(y, x), randint(min_radius, max_radius))
  r = lambda: randint(0,255)
  dot.setFill('#%02X%02X%02X' % (r(),r(),r()))
  return dot

#If circle overlap with circles in array then return True
def checkOverLap(circle, array):
  for circle_cmp in array:
    dist = math.hypot(circle.getCenter().getX() - circle_cmp.getCenter().getX(),
                      circle.getCenter().getY() - circle_cmp.getCenter().getY())
    if dist < circle.getRadius() + circle_cmp.getRadius():
      return True
  return False

def drawAllCircles(win, array):
  for x in range(0, 250):
    array[x].draw(win)

main()

rawDescription: How to make objects not touch in Python

description: Make objects not touch in Python


code:
while True:
    for i in range(nLEDs):
        R = [ 255 ] * nLEDs
        G = [ 255 ] * nLEDs
        B = [ 255 ] * nLEDs
        intensity = [ 0 ] * nLEDs
        intensity[i] = 1
        setLEDs(R, G, B, intensity)
        time.sleep(0.05)

    for i in reversed(range(nLEDs)):
        R = [ 255 ] * nLEDs
        G = [ 255 ] * nLEDs
        B = [ 255 ] * nLEDs
        intensity = [ 0 ] * nLEDs
        intensity[i] = 1
        setLEDs(R, G, B, intensity)
        time.sleep(0.05)

rawDescription: LED chase using python

description: LED chase using python


code:
from pygit2 import Repository
from pygit2 import GIT_SORT_TIME
from pygit2 import GIT_SORT_REVERSE
repo = Repository('/path/to/repo')
rev = repo.revparse_single('HEAD').hex
iterator = repo.walk(rev, GIT_SORT_TIME | GIT_SORT_REVERSE)
results = [(commit.committer.name, commit.message.splitlines()[0])
    for commit in iterator]
results

rawDescription: Is there a python interface to git shortlog?


code:
my_dict = {
    "keyA": 1,
    "keyB": 2,
    "keyC": 3
}
invalid = {"keyA", "keyB"}
def without_keys(d, keys):
    return {x: d[x] for x in d if x not in keys}
without_keys(my_dict, invalid)

rawDescription: Return copy of dictionary excluding specified keys


code:
objects = MyC.objects.all()
if cd['start_date']:
    objects = objects.filter(date__gt=cd['start_date'])
if cd['end_date']:
    objects = objects.filter(date__lt=cd['end_date'])
return objects

rawDescription: django - date filter without bloat

description: Django - date filter without bloat