code:
import re
import urllib

infile = open('test2.txt')
outfile = open('test3.txt', 'w')

pattern = r'"resource": "(?P<path>.+/(?P<filename>.+)\.jpg)"'
replacement = '"resource": "../img/\g<filename>.jpg"'
prog = re.compile(pattern)

for line in infile:
    match = prog.match(line)
    if match:
        print (match.group('path'))
    text = prog.sub(replacement, line)
    outfile.write(text)
infile.close()
outfile.close

rawDescription: How should I print a string that matches this pattern in a file?


code:
def parse(self, response):
    # check response for rule criteria
    ...
    if rule:
        # create new request to pass to second callback
        req = Request("http://www.example.com/follow", callback=self.parse2)
        return req

def parse2(self, response):
    hxs = HtmlXPathSelector(response)
    # do stuff with the successful response

rawDescription: How to mention link extractor rules when using BaseSpider in scrapy

description: Mention link extractor rules when using BaseSpider in scrapy


code:
cur.execute(selectStatement)
res = cur.fetchall()
for outerrow in res:
    nSql = outerrow[0]
    cur.execute(nSql)
    # rest of your code

rawDescription: Inserting data into MySQL database from Python


code:
import urllib.request
from bs4 import BeautifulSoup
url = "http://en.wikipedia.org/wiki/Markov_chain"
soup = BeautifulSoup(urllib.request.urlopen(url))
soup.title

rawDescription: Saving content of a webpage using BeautifulSoup


code:
somedict = {"foo" :
    {"bar" : "bars value"}
}

somedict['foo']['baz'] = 'baz value'

rawDescription: add a new key value pair to existing key value pair object in python

description: Add a new key value pair to existing key value pair object in python


code:
store = pd.HDFStore('test.h5',mode='w')
store.append('df/foo1',DataFrame(np.random.randn(10,2)))
store.append('df/foo2',DataFrame(np.random.randn(10,2)))
pd.concat([ store.select(node._v_pathname) for node in store.get_node('df') ])
store.close()

rawDescription: Read entire group in an HDF5 file using a pandas.HDFStore


code:
hotels = Hotel.objects.select_related().exclude(
    Q(subscriptions__end_date__lte=datetime.date.today()))

self.premium_hotels = []
for h in hotels:
    for sub in h.subscriptions.filter(start_date__lte=datetime.now(), end_date__gte=datetime.now()):
        if sub.enquiry_count < sub.tier.enquiry_limit:
            self.premium_hotels.append(h)
            break

rawDescription: Compare two fields in Django without F Objects


code:
from django import forms
from registration.forms import RegistrationForm, RegistrationFormUniqueEmail

class DealerForm(RegistrationFormUniqueEmail):
    type = forms.ChoiceField(required=True, choices=(
        ('dealer', 'Dealer'),
        ('marketing_agent', 'Marketing Agent'),
        ('private_seller', 'Private Seller'),
        ('virtual_dealer', 'Virtual Dealer')
    ))
    dealership_name = forms.CharField(required=False, max_length=50)
    subdomain_name = forms.CharField(required=False, max_length=50)
    banner_image = forms.ImageField(required=False)
    logo_image = forms.ImageField(required=False)

rawDescription: How to make required=false in Django registration custom fields for particular case

description: Make required=false in Django registration custom fields for particular case


code:
#!/usr/bin/env python
import gimpfu
import gimp
import IPython
from gimpfu import pdb
gimpfu.register("IPython-Console", "IPython Interpreter",
                "Launches IPython interpreter in terminal",
                "Nic", "Nicolas CORNETTE", "2014",
                "<Image>/Filters/Languages/Python-Fu/_IPython Console",
                "", [], [], lambda image,layer: IPython.embed())
gimpfu.main()

rawDescription: Using ipython as the gimp py-fu interpreter, sending all output and input to the terminal


code:
from ctypes import *

class abc(Structure):
    _pack_ = 1
    _fields_ = [
        ('r1',c_ubyte),
        ('r2',c_ubyte),
        ('p1',c_ubyte),
        ('id',c_uint)]

rawDescription: python ctypes pragma pack for byte aligned read

description: Python ctypes pragma pack for byte aligned read


code:
if __name__ == '__main__':
    import sys

    main(sys.argv)

rawDescription: when should we call logging.basicConfig in a Python project?

description: When should we call logging.basicConfig in a Python project


code:
x
search_list = [0,2]
np.where((x == search_list).all(1))[0][0]
np.nonzero((x == search_list).all(1))[0][0]

rawDescription: Numpy: search for the first matching row


code:
ie = webbrowser.get('c:\\program files\\internet explorer\\iexplore.exe')
ie.open('http://google.com')

rawDescription: Open IE Browser Window

description: Open IE Browser Window


code:
keywords = []
if query:
    results = []
    keywords = query.split()
    query = Textbook.objects.all()
    for x in keywords:
        query = query.filter(Q(class_name__icontains = x) | Q(textbook_name__icontains = x) | Q(author__icontains = x) | Q(isbn__icontains = x))

numresults = len(query)

rawDescription: Django - Turning code into django query?

description: Django - Turning code into django query


code:
import pyttsx

def cb(name):
    print(name)

engine = pyttsx.init()
engine.connect('started-utterance', cb)
for word in ["here", "are", "some", "test", "words"]:
    engine.say(word, name=word)

engine.runAndWait()

rawDescription: pyttsx - loop makes runAndWait() cut off

description: Pyttsx - loop makes runAndWait() cut off


code:
import re

# create regular expression pattern
chop = re.compile('#chop-begin.*?#chop-end', re.DOTALL)

# open file
f = open('data', 'r')
data = f.read()
f.close()

# chop text between #chop-begin and #chop-end
data_chopped = chop.sub('', data)

# save result
f = open('data', 'w')
f.write(data_chopped)
f.close()

rawDescription: python replace section of text with only knowing the begining and last word

description: Python replace section of text with only knowing the begining and last word


code:
# be optimistic!
either_true = True
if x:
    do_something1
elif y:
    do_something2
else:
    either_true = False

if either_true:
    do_something3

rawDescription: if or elif either true then do something

description: If or elif either true then do something


code:
import logging
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

# first file logger
logger_1 = logging.getLogger('simple_logger')
hdlr_1 = logging.FileHandler('simplefile_1.log')
hdlr_1.setFormatter(formatter)
logger_1.addHandler(hdlr_1)

# second file logger
logger_2 = logging.getLogger('simple_logger_2')
hdlr_2 = logging.FileHandler('simplefile_2.log')
hdlr_2.setFormatter(formatter)
logger_2.addHandler(hdlr_2)

logger_1.info('message 1')
logger_2.error('error foo')

rawDescription: Logging to two files with different settings


code:
from pylab import *
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

def comma_format(x, p):
    return format(x, "6,.0f").replace(",", ".")

ax = subplot(111)
xx = np.arange(0,20,1)
yy = np.arange(1000,10000,450)
ax.get_yaxis().set_major_formatter(ticker.FuncFormatter(comma_format))
plt.scatter(xx,yy)
plt.show()

rawDescription: python + matplotlib: use locale to format y axis

description: Python + matplotlib: use locale to format y axis


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib as mpl
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(-0.05,1);ax.set_ylim(-0.05,1);
plt.grid('on');

#Rotate rectangle patch object
ts = ax.transData
coords = ts.transform([0.2, 0.5])
tr = mpl.transforms.Affine2D().rotate_deg_around(coords[0], coords[1], 10)
t= ts + tr

rec0 = patches.Rectangle((0.2,0.5),0.25,0.2,alpha=0.5)
ax.add_patch(rec0)

#Rotated rectangle patch
rect1 = patches.Rectangle((0.2,0.5),0.25,0.2,color='blue',alpha=0.5,transform=t)
ax.add_patch(rect1);

#The (desired) point of rotation
ax.scatter([0.0,0.2],[0.0,0.5],c=['g','r'],zorder=10)
txt = ax.annotate('Desired point of rotation',xy=(0.2,0.5),fontsize=16,\
xytext=(0.25,0.35),arrowprops=dict(arrowstyle="->",connectionstyle="arc3,rad=-.2"))
txt2 = ax.annotate('Actual point of rotation',xy=(0.0,0.0),fontsize=16,\
xytext=(0.15,0.15),arrowprops=dict(arrowstyle="->",connectionstyle="arc3,rad=.2"))

plt.show()

rawDescription: Unable to rotate a matplotlib patch object about a specific point using rotate_around( )


code:
DataFrame.update(other, join='left', overwrite=True,
                 filter_func=None, raise_conflict=False)

rawDescription: Merge/Join/Append two Pandas DataFrames with MultiIndex columns by both index and cols


code:
from __future__ import print_function
import pywinauto

pywinauto.Application().Start(r'explorer.exe')
explorer = pywinauto.Application().Connect(path='explorer.exe')

# Go to "Control Panel -> Programs and Features"
NewWindow = explorer.Window_(top_level_only=True, active_only=True, class_name='CabinetWClass')
try:
    NewWindow.AddressBandRoot.ClickInput()
    NewWindow.TypeKeys(r'Control Panel\Programs\Programs and Features{ENTER}', with_spaces=True, set_foreground=False)
    ProgramsAndFeatures = explorer.Window_(top_level_only=True, active_only=True, title='Programs and Features', class_name='CabinetWClass')

    # wait while list of programs is loading
    explorer.WaitCPUUsageLower(threshold=5)

    item_7z = ProgramsAndFeatures.FolderView.GetItem('7-Zip 9.20 (x64 edition)')
    item_7z.EnsureVisible()
    item_7z.ClickInput(button='right', where='icon')
    explorer.PopupMenu.MenuItem('Uninstall').Click()

    Confirmation = explorer.Window_(title='Programs and Features', class_name='#32770', active_only=True)
    if Confirmation.Exists():
        Confirmation.Yes.ClickInput()
        Confirmation.WaitNot('visible')

    WindowsInstaller = explorer.Window_(title='Windows Installer', class_name='#32770', active_only=True)
    if WindowsInstaller.Exists():
        WindowsInstaller.WaitNot('visible', timeout=20)

    SevenZipInstaller = explorer.Window_(title='7-Zip 9.20 (x64 edition)', class_name='#32770', active_only=True)
    if SevenZipInstaller.Exists():
        SevenZipInstaller.WaitNot('visible', timeout=20)

    if '7-Zip 9.20 (x64 edition)' not in ProgramsAndFeatures.FolderView.Texts():
        print('OK')
finally:
    NewWindow.Close()

rawDescription: Automating uninstall from Programs and Features


code:
import win32com.client
oAccess = win32com.client.Dispatch('Access.Application')
DbFile = r'C:\Users\hans\Documents\NewDb.mdb'
dbLangGeneral = ';LANGID=0x0409;CP=1252;COUNTRY=0'
# dbVersion40 64
dbVersion = 64
oAccess.DBEngine.CreateDatabase(DbFile, dbLangGeneral, dbVersion)
oAccess.Quit()
del oAccess

rawDescription: Python Create Access database using win32com


code:
from django.core.urlresolvers import resolve
from django.utils.translation import activate

class DisableAdminI18nMiddleware:
    def process_request(self, request):
        resolver_match = resolve(request.path)
        if resolver_match.app_name == 'admin':
            activate('en')

rawDescription: Django: how to disable locale in admin app


code:
if not request.user in thread.participants.all():
    ...

rawDescription: Check if item is in ManyToMany field?

description: Check if item is in ManyToMany field


code:
import datetime

def daterange(start_date, end_date):
    """
    Generate an iterator of dates between the two given dates.
    taken from http://stackoverflow.com/questions/1060279/
    """
    for n in range(int ((end_date - start_date).days)):
        yield start_date + datetime.timedelta(n)

def get_graph_data(start_date, end_date):
    query = MyModel.objects.all().annotate(models.Count("id"))
    data = query.values('created_at', 'id__count')

    # go through all the dates between start_date and end_date
    # and fill the missing gaps with 0
    return dict((d, data[d] if d in data else 0) for d in daterange(t, to))

rawDescription: Include 0 values when using values() and Count() in django


rawDescription: How to vectorize the evaluation of bilinear & quadratic forms?

description: Vectorize the evaluation of bilinear & quadratic forms


code:
import subpackage1
import subpackage2

rawDescription: clean name space and __init__.py

description: Clean name space and __init__.py


code:
from toolz.dicttoolz import keyfilter
to_keep = lambda key: key in set(keep)
keyfilter(to_keep, testdict)

rawDescription: Python functional approach: remove key from dict using filter


code:
sorted(firmware_percents, key=distutils.version.StrictVersion, reverse=True)
sorted(firmware_percents, key=distutils.version.LooseVersion, reverse=True)

rawDescription: Sort dict by key when key is a version

description: Sort dict by key when key is a version


rawDescription: removing elements from a list defined by another list

description: Removing elements from a list defined by another list


code: x, y = zip(*a)

rawDescription: select sub item in a tuple list in python

description: Select sub item in a tuple list in python


code:
# wrong:
def swap(a, b):
    a, b = b, a
swap(x, y)  # x is still x and y is still y

# right-ish -- You really don't need the function if you're gonna do it this way.
def swap(a, b):
    return b, a
a, b = swap(a, b)

rawDescription: Copying or switching array content in numpy


code:
class myclass_fast():
    def __init__(self):
        print("i'm myclass in module_x")

def test(enable_a):
    if enable_a:
        try:
            from module_a import myclass
        except ImportError:
            enable_a = False
            myclass = myclass_fast
    else:
        myclass = myclass_fast
    i = myclass()

rawDescription: conditionally import module to shadow local implementation

description: Conditionally import module to shadow local implementation


code:
from django.template import Context, Template
t = Template('{% now "d-F-Y" %}')
t.render(Context())

rawDescription: Date filter includes time before date filter applied


code:
import subprocess

command = ['ls', '-l']
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.IGNORE)
text = p.stdout.read()
retcode = p.wait()

rawDescription: How to get data from command line from within a Python program?

description: Get data from command line from within a Python program


code:
# -*- coding: utf-8 -*-
from distutils.core import setup
import py2exe
import sys

import os
dataFiles = []

sampleDir = r'.\\lang'
for root, dirs, files in os.walk(sampleDir):
    sampleList = []
    if files:
        for filename in files:
            #ignore SVN dirs
            if ".svn" not in root:
                sampleList.append(os.path.join(root, filename))
        if sampleList:
            dataFiles.append((root, sampleList))

class Target:
       def __init__(self, **kw):
           self.__dict__.update(kw)

target = Target(
       script = "script.py",
       icon_resources=[(1, 'ico.ico')],
       version = "1.5.5.000",
       company_name = "company",
       copyright = 'Copyright (c) ',
       name = 'PROGNAME',
       )

target2 = Target(
       script = "script2.py",
       icon_resources=[(1, 'ico.ico')],
       version = "1.0.0.000",
       company_name = "company",
       copyright = 'Copyright (c) ',
       name = 'SECOND PROGNAME',
       )

setup(
    author='me',
    author_email='me@me.com',
    description = 'desc',

    windows = [target, target2],

    options = {
                  'py2exe': {
                      'packages': 'encodings, kinterbasdb',
                      'includes': 'cairo, pango, pangocairo, atk, gobject, gio, glib, gtk',
                  }
              },

    data_files=dataFiles,
)

rawDescription: python py2exe compile two py files at once to two separate exe files

description: Python py2exe compile two py files at once to two separate exe files


code:
def clean_cool_filter(model_name, params):
    clause = {
        "Column": 'stub__in',
        "Person": 'web_slug__in',
        "Tag": 'name__in'
    }.get(model_name)
    if clause:
        return {clause: params}
    else:
        return {}

rawDescription: getattr keyword arg filtering

description: Getattr keyword arg filtering


code:
import dateutil.tz as dtz
import pytz
import datetime as dt
import collections
import random

timezones = collections.defaultdict(list)
for name in pytz.common_timezones:
    timezone = dtz.gettz(name)
    try:
        now = dt.datetime.now(timezone)
    except ValueError:
        # dt.datetime.now(dtz.gettz('Pacific/Apia')) raises ValueError
        continue
    abbrev = now.strftime('%Z')
    timezones[abbrev].append(name)

date_string, tz_string = '10/07/2011 04:22 CEST'.rsplit(' ', 1)
date = dt.datetime.strptime(date_string, '%m/%d/%Y %H:%M')
print(date)
# 2011-10-07 04:22:00

tz = pytz.timezone(random.choice(timezones[tz_string]))
print(tz)
# Europe/Oslo

date = tz.localize(date)
print(date)
# 2011-10-07 04:22:00+02:00

rawDescription: How do I convert a string with a different time zone to a datetime object?

description: Convert a string with a different time zone to a datetime object


code:
import pygame
import random
fractal_level = 3
colblue = (0,61,103)
colbk = (0,0,0)

def fract_draw(x, y, width, height, count):

    color = random.sample(xrange(0,255), 3)
    pygame.draw.line(screen,color,[x + width*.25,height//2+y],[x + width*.75,height//2+y],2)
    color = random.sample(xrange(0,255), 3)
    pygame.draw.line(screen,color,[x+width*.25,(height*.5)//2+y],[x+width*.25,(height*1.5)//2+y],2)
    color = random.sample(xrange(0,255), 3)
    pygame.draw.line(screen,color,[x + width*.75,(height*.5)//2+y],[x + width*.75,(height*1.5)//2+y],2)

rawDescription: Randomizing Color Python Fractal

description: Randomizing Color Python Fractal


code: [x.row() for x in self.listWidget.selectedIndexes()]

rawDescription: Getting selected rows in QListWidget

description: Getting selected rows in QListWidget


code:
def until_func(driver):
    driver.refresh()
    elem = driver.find_element_by_css_selector("dd.Production.Status")
    if elem.is_displayed() and elem.text == 'Output Complete':
        return elem
orderElem = WebDriverWait(driver, timeout=60, poll_frequency=10).until(until_func)

rawDescription: Selenium-Python: How do I make my WebDriverWait a few seconds before reloading a page?


code:
def insertion():
    field_names = {'Customer_ID=': 'Customer_ID=0',
'Home_Phone=':'Home_Phone=0','Business_Phone=': 'Business_Phone=0'}

with open('xactions.two.txt', 'r') as from_file:
    with open('customer.diff', 'w') as to_file:
        for line in from_file:
            line = line.rstrip("\n")
            found = False
            for field in field_names.keys():
                if field in line:
                   to_file.write(line + "0")
                   found = True
            if not found:
                to_file.write(line)
            to_file.write("\n")

rawDescription: Correcting errors in one file and writing it to a new file


code:
import re
r = re.search("a(..)d(.)f", "xxabcdefg")
r.span()
r.span(1)
r.span(2)

rawDescription: How can I get the position of the captured groups?

description: Get the position of the captured groups


code:
my_dict = {}
for line in myfile_text.splitlines():
    my_dict[line.split()[0]] = line.split()[1]
result_list = []
list_tuples = ast.literal_eval(myfile_tuples)
for tup in list_tuples:
    temp_list = []
    for term in tup:
        temp_list.append(my_dict[term])
    result_list.append(tuple(temp_list))
print(result_list)

rawDescription: replacing items of tuples

description: Replacing items of tuples


code:
from Tkinter import *
import tkSnack

root = Tk()
tkSnack.initializeSnack(root)
c = tkSnack.Sound(file='test.wav')
c.record()
root.after(5000, c.stop)
root.mainloop()

rawDescription: alternatives to pyaudio for audio processing in python?

description: Alternatives to pyaudio for audio processing in python


code:
class Person():
    people={}
    @classmethod
    def create(cls,name):
        person=Person(name)
        cls.people[name]=person
        return person
    def __init__(self, name):
        self.name = name

rawDescription: What is the most efficient way to dynamically create class instances?


code:
df.sort_values('impwealth', inplace=True)
cumsum = df.indweight.cumsum()
cutoff = df.indweight.sum() / 2.0
median = df.impwealth[cumsum >= cutoff].iloc[0]

rawDescription: Python: weighted median algorithm with pandas


rawDescription: pygame drawing a filled rectangle overwrite border, but only sometimes?

description: Pygame drawing a filled rectangle overwrite border, but only sometimes


code:
from numbers import Number
[sum(x) if isinstance(x[0], Number) else x[0] for x in zip(*under__list)]

rawDescription: Add elements in a list Python

description: Add elements in a list Python


code: resolved_products = list(mycollection.find({'_id': {'$in': result['products']}}))

rawDescription: Pattern to resolve mongoDB references

description: Pattern to resolve mongoDB references


code:
import urlparse

def url_rev(pubdate, slug):
    return urlparse.urljoin('http://mysite.com',
                            '/%s/%s/%s/%s/'%(pubdate.year, pubdate.month, pubdate.day, slug))

rawDescription: how to add resources to url in python google app engine

description: Add resources to url in python google app engine


code:
class FooType(type):
    def __str__(cls):
        return 'Me a Foo'
    def __repr__(cls):
        return '<Foo>'

class Foo(object):
    __metaclass__=FooType
    def __str__(self):
        return "instance of class Foo"

print(Foo)
# Me a Foo

print(repr(Foo))
# <Foo>

rawDescription: Methods for Python classes representation


rawDescription: How to parse delimited data in python ( pandas ) to create DataFrame?

description: Parse delimited data in python ( pandas ) to create DataFrame


code:
import matplotlib.pyplot as plt

xx=[1,2,3]
yy=[2,3,4]
dy=[0.1,0.2,0.05]

fig=plt.figure()
figname = "out.png"
ax=fig.add_subplot(111)

ax.errorbar(xx,yy,dy,fmt='ro-',ms=6,elinewidth=4)

# start of hack to get renderer
fig.savefig(figname)
renderer = plt.gca().get_renderer_cache()
# end of hack

txt = ax.text(xx[1], yy[1],r'$S=0$',fontsize=16)
tbox = txt.get_window_extent(renderer)
dbox = tbox.transformed(ax.transData.inverted())
text_width = dbox.x1-dbox.x0
text_height = dbox.y1-dbox.y0
x = xx[1] - text_height
y = yy[1] - text_width/2
txt.set_position((x,y))

ax.set_xlim([0.,3.4])
ax.set_ylim([0.,4.4])

fig.savefig(figname)

rawDescription: converting text size into data coordinates

description: Converting text size into data coordinates


code:
class Title(ndb.Model):
  title = ndb.StringProperty()
  lang = ndb.StringProperty()

class Article(ndb.Model):
  titles = ndb.StructuredProperty(Title, repeated=True)

rawDescription: Google App Engine NDB repeated property additional info


rawDescription: Trying to match an exact subset in python


code:
resp = redirect('/')
resp.set_cookie('token_key', access_token.key)
resp.set_cookie('secret_key', access_token.secret)
return resp

rawDescription: Cookies set on response don't seem to persist


code:
all(c in "ab" for c in "foobar")
all(c in "ab" for c in "aaabaababbba")

rawDescription: check if a string only contains certain letters

description: Check if a string only contains certain letters


code:
def fetch_resources(uri, rel):
 """
 Callback to allow pisa/reportlab to retrieve Images,Stylesheets, etc.
 `uri` is the href attribute from the html link element.
 `rel` gives a relative path, but it's not used here.

 """
 path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
 return path

def render_pdf (html):
 result = StringIO.StringIO()
 pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), dest=result, link_callback=fetch_resources)
 return result

rawDescription: Django pdf question with pisa

description: Django pdf question with pisa


code:
from decimal import Decimal
import itertools

def encrypt(numbers_as_text, code):
    key = itertools.cycle(code[::-1])

    num = Decimal(numbers_as_text)

    power = 1
    for _ in numbers_as_text:
        num += power * int(next(key))
        power *= Decimal(10)

    return num

if __name__ == "__main__":
    print(encrypt('12345','12'))

rawDescription: python, encryption of any size code with a smaller key

description: Python, encryption of any size code with a smaller key


code:
def sign_data(private_key_loc, data):
    '''
    param: private_key_loc Path to your private key
    param: package Data to be signed
    return: base64 encoded signature
    '''
    from Crypto.PublicKey import RSA
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import SHA256
    from base64 import b64encode, b64decode
    key = open(private_key_loc, "r").read()
    rsakey = RSA.importKey(key)
    signer = PKCS1_v1_5.new(rsakey)
    digest = SHA256.new()
    # It's being assumed the data is base64 encoded, so it's decoded before updating the digest
    digest.update(b64decode(data))
    sign = signer.sign(digest)
    return b64encode(sign)

rawDescription: what is the equivalent of this in python

description: What is the equivalent of this in python


code:
# myapp/views.py
from django.views.generic import *

class MyView(DetailView):
    template_name = 'detail.html'
    model = MyModel
    # additional parameters
    slug = None

    def get_object(self, queryset=None):
        return queryset.get(slug=self.slug)

rawDescription: Django class-based view: How do I pass additional parameters to the as_view method?


code:
for line_num,line in enumerate(file):
    if line_num == 0 and line.startswith('File'):
        final_output.write(line)
    elif line_num > 0 and not line.startswith('File'):
         final_output.write(line)

rawDescription: How to remove all lines in a file containing a specific character except for the first?

description: Remove all lines in a file containing a specific character except for the first


code: listB = [obj.name for obj in listA]

rawDescription: Python's List: form a new list B of member attributes of object list A


code:
for event in pygame.event.get():
    if event.type == MOUSEMOTION:
        mousex, mousey = event.pos
        # build a vector between player position and mouse position
        moveVector = (mousex-playerx, mousey-playery)

        """
        compute the angle of moveVector from current vector that player is facing (faceVector).
        you should be keeping and updating this unit vector, with each mouse motion
        assume you have initial facing vector as (1,0) - facing East
        """

        # compute angle as in [1]

        # rotate the image to that angle and update faceVector

rawDescription: Pygame Making A Sprite Face The Mouse

description: Pygame Making A Sprite Face The Mouse


rawDescription: Facebook api graph access token

description: Facebook api graph access token


code:
import active_directory

user = active_directory.find_user("jimboface")
destination_ou = active_directory.find_ou("happyland")
destination_ou.com_object.MoveHere(str(user.as_string()), str(user.Name))
#Thats it!

rawDescription: How do you move a user to a different OU using Python

description: Move a user to a different OU using Python


code:
class ZipExhausted(Exception):
    pass

def izip_longest(*args, **kwds):
    # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
    fillvalue = kwds.get('fillvalue')
    counter = [len(args) - 1]
    def sentinel():
        if not counter[0]:
            raise ZipExhausted
        counter[0] -= 1
        yield fillvalue
    fillers = repeat(fillvalue)
    iterators = [chain(it, sentinel(), fillers) for it in args]
    try:
        while iterators:
            yield tuple(map(next, iterators))
    except ZipExhausted:
        pass

rawDescription: What is the purpose in Python's itertools.repeat?


code:
def index():
    form = forms.HelpSearch()
    if form.validate_on_submit():
        flash('Searched for: %s' % form.value.data)
        return redirect(url_for('help', keyword=form.value.data))
    return render_template('index.html', title='Index', form=form)

rawDescription: Redirect to new page with path and optional argument in Flask and Flask-WTF not working


code:
import win32com.client

excel = win32com.client.Dispatch('Excel.Application')

workbook = excel.Workbooks.open(r'c:\mybook.xls', 'password')

workbook.SaveAs('unencrypted.xls')

rawDescription: decrypt excel files

description: Decrypt excel files


code:
import sys
sys.float_info.epsilon

rawDescription: Value for epsilon in Python

description: Value for epsilon in Python


code:
def groupIntoEquivalencyClasses(aList, aEquals):
  classesByReps = {}
  for tElem in aList:
    tFound = False
    for rep in classesByReps.keys():
      if aEquals(tElem, rep):
        tFound = True
        classesByReps[rep].append(tElem)
        break
    if not tFound:
      classesByReps[tElem] = [tElem]
      #or just classesByReps[tElem] = [] if you don't want to re-store the key/representative
  return tClasses

rawDescription: Group list into equivalency classes

description: Group list into equivalency classes


code:
import wx

def show_splash():
    # create, show and return the splash screen
    bitmap = wx.Bitmap('images/splash.png')
    splash = wx.SplashScreen(bitmap, wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_NO_TIMEOUT, 0, None, -1)
    splash.Show()
    return splash

def main():
    app = wx.PySimpleApp()
    splash = show_splash()

    # do processing/initialization here and create main window
    frame = MyFrame(...)
    frame.Show()

    splash.Destroy()
    app.MainLoop()

if __name__ == '__main__':
    main()

rawDescription: How to adapt my current splash screen to allow other pieces of my code to run in the background?

description: Adapt my current splash screen to allow other pieces of my code to run in the background


code:
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)
plt.plot(t, s, c=seaborn.color_palette()[2])
plt.plot(t, 2*s, c=seaborn.color_palette()[2])

rawDescription: Matplotlib + Seaborn - two lines with the same color?


rawDescription: Display realtime candlesticks using Python and Matplotlib on the same figure


code:
target      = 0b00010100
target_mask = 0b00011100

np.where(my_array_of_binaries & target_mask == target, True, False)

rawDescription: Performing bitwise tests on integer numpy arrays


rawDescription: Determine current Mac Chrome web page using Python (py-appscript)


code:
with open(filename,"rb") as fh:
    fh.read()

rawDescription: Certain characters not being read fom file - Python


rawDescription: How to remove n number of elements from a list by index in Python?

description: Remove n number of elements from a list by index in Python


code:
class PageDataAddition(object):
    def alter_list_data_to_serialize(self, request, data):
        data['page'] = {'your_data': True}
        return data

class ItemResource(PageDataAddition, ModelResource):
    ...

rawDescription: Django tastypie: Add new Array of objects Next to "objects" and "meta" in Api output


code:
import numpy as np
X = np.array([1, 1, 0, 1, 1])
sample = [1,2,3]
X[sample]
X[sample] = 1 - X[sample]
X

rawDescription: Switch value of elements on some positions


code:
from datetime import timedelta

createdate_mongo += timedelta(days=1)

rawDescription: Changing datetime value in python

description: Changing datetime value in python


code:
import csv

# todo: for testing...
open('testfile.csv', 'w').write('''"1","2","3","4","5","6","7","can also contain text, and commas","9","10","11","12","13"
"1","2","3","4","5","6","7","can also contain text, and commas","9","10","11","12","13"
"1","2","3","4","5","6","7","can also contain text, and commas","9","10","11","12","13"
"1","2","3","4","5","6","7","can also contain text, and commas","9","10","11","12","13"
"1","2","3","4","5","6","7","can also contain text, and commas","9","10","11","12","13"''')

# the columns wanted, in order they should appear in output (zero based)
# ...example doesn't go to 68 cols, so abreviated
column_order = (0,1,2,3,4,5,6,7,11)

with open('testfile.csv') as csvin:
    reader = csv.reader(csvin)
    with open('testfile_new.csv', 'w') as csvout:
        writer = csv.writer(csvout)
        for row in reader:
            writer.writerow([row[i] for i in column_order])

# todo: for testing...
print(open('testfile_new.csv').read())

rawDescription: Python proprietary file conversion loop

description: Python proprietary file conversion loop


code: list(range(5)) #you can use list()

rawDescription: Why Is the Output of My Range Function Not a List?


code:
from selenium import webdriver

driver = webdriver.PhantomJS()
driver.get("http://google.com")

# This will get the initial html - before javascript
html1 = driver.page_source

# This will get the html after on-load javascript
html2 = driver.execute_script("return document.documentElement.innerHTML;")

rawDescription: How to get data from inspect element of a webpage using Python

description: Get data from inspect element of a webpage using Python


rawDescription: Django - any way to fetch foreign key objects instantly?


code:
from __future__ import print_function

with open('output.csv', 'w') as handle:
    for line in list_1:
        print(line, handle)
    df1.to_csv(handle, index=False)
    for line in list_2:
        print(line, handle)
    df2.to_csv(handle, index=False)

rawDescription: Python write 2 lists and Pandas DataFrames to csv/excel sequentially


code:
sum(int(float(item)) for item in big_list[start:end] if item)
                                                   # ^ skip over ""

rawDescription: Convert empty string to zero

description: Convert empty string to zero


code:
from os import path
import sys
sys.path.append(path.abspath('../Foo'))

from Project1.file1 import something

rawDescription: How to import functions from other projects in Python?

description: Import functions from other projects in Python


code:
existing_As = A.objects.filter(id__in=a_ids).values_list('id', flat=True)
As_to_create = list(set(a_ids) - set(existing_As))
A.objects.bulk_create([A(id=x) for x in As_to_create])

# Now we are sure all the As exist as we just created them, so
lots_of_b_objects = [B(a_id=1234), B(a_id=5678), ...]
B.objects.bulk_create(lots_of_b_objects)

rawDescription: Bulk creating related models in Django

description: Bulk creating related models in Django


code: save = put

rawDescription: What's the difference between entity.put() and entity.save()?


rawDescription: pandas data frame - reduce with initial value

description: Pandas data frame - reduce with initial value


code:
ax = df.plot()
ax.set_xticklabels(df.index, rotation=90)

rawDescription: Select date column by locations: #IndexingError: Too many indexers AND TypeError: cannot do slice indexing


rawDescription: string operation

description: String operation


code:
class Node(object):
    def __init__(self, globalIndex, coordinates):

        #Useful things to record
        self.globalIndex = globalIndex
        self.coordinates = coordinates # now self.coordinates is just another name for your array

rawDescription: defining an already exisiting numpy array within a class

description: Defining an already exisiting numpy array within a class


code:
xdim,ydim = data.shape
k = 2
a, b = np.meshgrid(range(ydim),range(xdim))
mask = (b - a -k) < 0

new_data = data[mask]

new_data2 = np.array(data) # to force a copy
new_data2[~mask] = 0

rawDescription: carving 2D numpy array by index

description: Carving 2D numpy array by index


code:
files = glob.glob('*')
d = {}
for f in files:
    d[f] = {}

rawDescription: How to dynamically create dictionaries whose name are taken from the contents of a directory in python?

description: Dynamically create dictionaries whose name are taken from the contents of a directory in python


code:
# https://www.python.org/dev/peps/pep-0008/#class-names
from some_module import Bean

sc.addPyFile("some_module.py")

rawDescription: Serializing a Python class

description: Serializing a Python class


code:
import re
str = 'http://google.com/sadfasdfsd$AA=mytag&SS=sdfsdf'
m = re.search(r'.*\$AA=([^&]*)\&.*', str)
m.group(1)

rawDescription: Python Get Tags from URL

description: Python Get Tags from URL


code:
# A.py
from C import blah

# B.py
import A
A.blah # this will work

rawDescription: Hierarchical python imports

description: Hierarchical python imports


rawDescription: Combine values from arbitrary number of columns into new one


code:
from scrapy.contrib.pipeline.media import MediaPipeline

class VideoPipeline(MediaPipeline):
    VIDEOS_DIR = "/stack/scrapy/video/video/store"

    def get_media_requests(self, item, info):
        """
        Evaluate file and, if you like it, download it.
        """
        os.system("vlc -vvv %s > /dev/null 2>&1 &" % item['video_url'][0])
        your_opinion = raw_input("how does it look?")
        item["comment"] = your_opinion
        if your_opinion == "hot":
            # issue request download video
            return Request(item["video_url"][0], meta={"item":item})

    def media_downloaded(self, response, request, info):
        """
        File is downloaded available as response.body save it.
        """
        item = response.meta.get("item")
        video = response.body
        video_basename = item['title'][0]
        new_filename = os.path.join(self.VIDEOS_DIR, video_basename)
        f = open(new_filename, 'wb')
        f.write(video)
        f.close()

rawDescription: Don't wait for files to download with Scrapy


code:
import re

s = "<Key>big_img/1/V071-e.jpg</Key>"

re.findall(r"<Key>(.*)</Key>",s)
['big_img/1/V071-e.jpg']

rawDescription: How to parse from string?

description: Parse from string


code:
s = unicode(your_object).encode('utf8')
f.write(s)

rawDescription: Printing a utf-8 encoded string

description: Printing a utf-8 encoded string


code:
if message.is_multipart():
    content = ''.join(part.get_payload(decode=True) for part in message.get_payload())
else:
    content = message.get_payload(decode=True)

rawDescription: Reading the mail content of an mbox file using python mailbox


code:
import urllib2

url = 'http://www.rba.gov.au/statistics/tables/csv/f17-yields.csv'

response = urllib2.urlopen(url)
html = response.read()

with open('AusCentralbank.csv', 'wb') as f:
    f.write(html)

rawDescription: Trying to download data from URL with CSV File


code:
import numpy as np
import scipy as sp
import scipy.stats

def mean_confidence_interval(data, confidence=0.95):
    a = 1.0*np.array(data)
    n = len(a)
    m, se = np.mean(a), scipy.stats.sem(a)
    h = se * sp.stats.t._ppf((1+confidence)/2., n-1)
    return m, m-h, m+h

rawDescription: Compute a confidence interval from sample data


code:
x = [1, 3, 3, 2, 3, 1, 2]
d = {1: 'a', 2: 'b', 3: 'c'}
[d[i] for i in x]
x = [True, False, True, True, False]
d = {True: 'a', False: 'b'}
[d[i] for i in x]

rawDescription: Mapping one value to another in a list

description: Mapping one value to another in a list


code:
import csv
data = []
with open('Trial_test.csv', 'rb') as csvfile:
   reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
   for row in reader:
       data.append(row)

# now do your calculations on the 'data' object.

with open('Trial_test_new.csv', 'wb') as csvfile:
   writer = csv.writer(csvfile, delimiter=' ', quotechar='|')
   for row in data:
       writer.writerow(row)

rawDescription: Appending data to csv file

description: Appending data to csv file


code:
status = app.exec_()   # run app, show window, wait for input
sys.exit(status)       # terminate program with a status code returned from app

rawDescription: why will the application show after sys.exit command?

description: Why will the application show after sys.exit command


code:
from numpy import *
from matplotlib.pyplot import *

Nx = 3
Ny = 3

# This is just creating some sample data
xx, yy = meshgrid(range(Nx), range(Ny))
zz = xx + yy
data = vstack([c.flatten() for c in [xx, yy, zz]]).T

# This is reversing the above operation to get x y and z suitable for pcolor
x, y, z = [data[:, i].reshape(Nx, Ny) for i in range(3)]

# Now you can plot
pcolor(x, y, z)
colorbar()

rawDescription: Contour Plot using Python

description: Contour Plot using Python


code:
bob['files'] #get you the list with second dictionary

bob['files'][0] #get you the first item in the list, which is the nested 2nd dictionary

bob['files'][0]['type'] == 'diskDescriptor'

rawDescription: Accessing Data Nested in Dictionary in Array in Dictionary


code:
from kivy.factory import Factory
Factory.register('Line', module='myfile')

rawDescription: How to import a new Vertex Instruction (Line) in the Kivy Language?

description: Import a new Vertex Instruction (Line) in the Kivy Language


code: #!/usr/bin/env python

rawDescription: Error in imports pyCrypto

description: Error in imports pyCrypto


code:
cars = CarModel.objects.all()
for op in self.cleaned_data['options']:
    cars = cars.filter((op, True))

rawDescription: Cleaner way to query on a dynamic number of columns in Django?


code:
import sys
import getopt

try:
    opts, args = getopt.getopt(sys.argv[1:], 'm:p:h', ['miner=', 'params=', 'help'])
except getopt.GetoptError:
    usage()
    sys.exit(2)

for opt, arg in opts:
    if opt in ('-h', '--help'):
        usage()
        sys.exit(2)
    elif opt in ('-m', '--miner'):
        miner_name = arg
    elif opt in ('-p', '--params'):
        params = arg
    else:
        usage()
        sys.exit(2)

rawDescription: How to use getopt/OPTARG in Python? How to shift arguments if too many arguments (9) are given?

description: Use getopt/OPTARG in Python? How to shift arguments if too many arguments (9) are given


code:
ranges = (
    (8700, 12600),
    (15700, 17600),
    (18750, 22350),
    (23700, 27250),
    (106950, 115300),
)

newSndIdx = 0

for start, end in ranges:
    for i in range(start, end + 1):
        sampleValue = getSampleValueAt(sound, i)
        setSampleValueAt(newSnd, newSndIdx, sampleValue)
        newSndIdx += 1
    newSndIdx += 500

rawDescription: How would make this run with an if statement and one for loop?


code: max(f(k) for k in range(n))

rawDescription: Find a maximum of a list without constructing the list


code:
import re
def yes_if_include(m, y):
    y1, y2 = map(int, m.group(1, 2))
    if y1 <= y <= y2:
        return 'yes' + m.group()[2:]
    return m.group()
textf = '<textf no="1958-1960" no="1961-1963" no="1964-1966">Some text</textf>'
re.sub(r'no="(\d+)-(\d+)"', lambda m: yes_if_include(m, 1963), textf)

rawDescription: Substituting text by checking range of int


code:
def get_func_name(function):
    return function.__name__

rawDescription: Getting an easily readable function name from a function object in python


rawDescription: Timing functions

description: Timing functions


code:
class SubmissionLogFormMixin(object):

    def get_context_data(self, **kwargs):
        context = super(SubmissionLogFormMixin, self).get_context_data(**kwargs)

        # since there could be another form on the page, you need a unique prefix
        context['footer_form'] = SubmissionLogForm(self.request.POST or None, prefix='footer_')
        return context

    def post(self, request, *args, **kwargs):
        footer_form = SubmissionLogForm(request.POST, prefix='footer_')
        if footer_form.is_valid():
            c = footer_form.save(commit=False)
            c.sub_date=datetime.now()
            c.save()

        return super(SubmissionLogFormMixin, self).post(request, *args, **kwargs)

class EditView(SubmissionLogFormMixin, UpdateView):
    form_class = CollectionForm
    model = Collection

# you can use SubmissionLogFormMixin on any other view as well.

rawDescription: How do I save post data using a decorator in Django

description: Save post data using a decorator in Django


code:
import minecart

# minecart units are 1/72 inch, measured from bottom-left of the page
ROW_BORDERS = (
    72 * 1,  # Bottom row starts 1 inch from the bottom of the page
    72 * 3,  # Second row starts 3 inches from the bottom of the page
    72 * 5,  # Third row starts 5 inches from the bottom of the page
    72 * 7,  # Third row ends 7 inches from the bottom of the page
)
COLUMN_BORDERS = (
    72 * 8,  # Third col ends 8 inches from the left of the page
    72 * 6,  # Third col starts 6 inches from the left of the page
    72 * 4,  # Second col starts 4 inches from the left of the page
    72 * 2,  # First col starts 2 inches from the left of the page
)  # reversed so that BOXES is ordered properly
BOXES = [
    (left, bot, right, top)
    for top, bot in zip(ROW_BORDERS, ROW_BORDERS[1:])
    for left, right in zip(COLUMN_BORDERS, COLUMN_BORDERS[1:])
]

def extract_output(page):
    """
    Reads the text from page and splits it into the 9 cells.

    Returns a list with 9 entries:

        [A, B, C, D, E, F, G, H, I]

    Each item in the tuple contains a string with all of the
    text found in the cell.

    """
    res = []
    for box in BOXES:
        strings = list(page.letterings.iter_in_bbox(box))
        # We sort from top-to-bottom and then from left-to-right, based
        # on the strings' top left corner
        strings.sort(key=lambda x: (-x.bbox[3], x.bbox[0]))
        res.append(" ".join(strings).replace(u"\xa0", " ").strip())
    return res

content = []
doc = minecart.Document(open("path/to/pdf-doc.pdf", 'rb'))
for page in doc.iter_pages():
    content.append(extract_output(page))

rawDescription: Python read part of a pdf page

description: Python read part of a pdf page


code:
def main():
    import matplotlib.pyplot as plt
    data = range(1,10)
    fig = plt.plot(data)
    plt.ioff()  # turns interactive mode OFF, should make show() blocking
    plt.show()

if __name__ == "__main__":
    main()

rawDescription: Stop python GUI program from exiting when run from CLI


code:
import lxml
from lxml import html
testFile=open(r'c:\temp\testlxml.htm').read()
aTree=html.fromstring(testFile)
bolds=aTree.cssselect('b')
theTitles=[item.text for item in bolds if item.text if 'KEY' in item.text]
theBoldKeys=[item for item in bolds if item.text if 'KEY' in item.text]
theFullList=[]
for e in aTree.iter():
    theFullList.append(e)

for numb,item in enumerate(theFullList):
    if item==theBoldItems[0]:
        first=numb
    if item==theBoldItems[1]:
        second=numb
theText=[]
for item in theFullList[first:second]:
    if item.text:
        theText.append(item.text)
    if item.tail:
       theText.append(item.tail)

aString=' '.join(theText)

rawDescription: Once I have identified the beginning and end parts of a section of an html document using lxml, how do I get everything between them


code:
from collections import defaultdict
lists = defaultdict(list)

def time_price_pair(a, b):
    if 32400 <= a < 53460:
        i = (a-32400)/540
        lists[i].append(b)

rawDescription: How can i shorten this python code?

description: Shorten this python code


code: subset_df = df[df['slp'] <= 20]

rawDescription: Slow iteration through pandas data frame


code:
d = dict(red=2, blue=45, green=100)
sorted(d.items(), cmp=lambda a,b: cmp(a[1], b[1]), reverse=True)

rawDescription: Python how to sort a dictionary by value in reverse order


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

X = 10*np.random.rand(5,3)

fig = plt.figure(figsize=(15,5),facecolor='w')
ax = fig.add_subplot(111)
ax.imshow(X, cmap=cm.jet)

plt.savefig("image.png",bbox_inches='tight',dpi=100)

rawDescription: Resize a figure automatically in matplotlib


code:
files = [('file[]', ("", "", "application/octet-stream")),
         ('file[]', ('qwe.txt', open('qwe.txt','rb'), 'text/plain'))]
requests.post(url, files=files)

rawDescription: How to send request with duplicate data in python?

description: Send request with duplicate data in python


code:
class MyAppData(db.Model):
    my_number = db.IntegerProperty()

# fetch entity whenever you need to store your value
data = MyAppData.get_or_insert(key_name='mydata', my_number=1)

data.my_number += 1
data.put()

rawDescription: Python: Store a num in Google App Engine


code:
import win32com.client
b = win32com.client.Dispatch('VisualStudio.DTE')
b
b.name
b.Version

rawDescription: How to script Visual Studio 2008 from Python?

description: Script Visual Studio 2008 from Python


code:
DATABASES = {
    'default': {
        'NAME': 'my_database',
        'ENGINE': 'sqlserver_ado',
        'HOST': 'dbserver\\ss2008',
        'USER': '',
        'PASSWORD': '',
    }
}

rawDescription: Configure Django with MS SQL Server database


code:
from sqlalchemy.sql.expression import bindparam
from sqlalchemy import text

updateCommand = myTable.update().where(id=bindparam("idToChange"))
valuesDict = {'idToChange':':idToChange',
              'Location':text("GeomFromText(:_location)")
}
updateCommand = updateCommand.values(**valuesDict)
data = [
    {'idToChange':1,'_location':"Point(39.0 55.0)"},
    {'idToChange':2,'_location':"Point(39.0 55.0)"},
]
#see the MySQL command as it will be executed (except for data)
print(connection.compile(bind=connection))
#actually execute the statement
connection.execute(updateCommand,data)

rawDescription: calling GeomFromText and other such functions using sqlalchemy core

description: Calling GeomFromText and other such functions using sqlalchemy core


code: ['python', 'script_name']

rawDescription: Python detect a python script's name in the list of processes


code:
for i in range(3):
    valid =checkValid()
    if(valid==1):
        break

rawDescription: Setting While Loop to Loop Maximum of 3 Times


code:
myimage = pygame.image.load("myimage.bmp")
imagerect = myimage.get_rect()

while 1:
    your_code_here

    screen.fill(black)
    screen.blit(myimage, imagerect)
    pygame.display.flip()

rawDescription: What is a good way to draw images using pygame?


code:
temp_surf = screen.copy
screen.fill((0,0,0))  # here, you can fill the screen with whatever you want to take the place of what was there before
screen.blit(temp_surf,(x_shift,y_shift))

rawDescription: Pygame translate surface a given amount

description: Pygame translate surface a given amount


code:
signed_request = pyface.parse_signed_request(request.POST['signed_request'], fb_app_secret)

if signed_request:
    if signed_request.has_key('user_id'):
        facebook_user_id = signed_request['user_id']

rawDescription: Python: server side detect whether user is logged in to facebook (and not necessarily connected to my app)


code:
for child in root.findall('.//array[@name="logEntries"]/value'):
    print(child.text)

rawDescription: Parsing attribute name text from xml using xml.etree.elementTree


code:
List.sort(key=lambda e: [e.a, e.b, e.c])
# or
List.sort(key=operator.attrgetter('a', 'b', 'c'))

rawDescription: How to sort list of objects

description: Sort list of objects


code:
import scipy.stats       as stat
import matplotlib.pyplot as plt
import matplotlib.cm     as cm
import numpy             as np

data = stat.uniform.rvs(size=2400).reshape((40,60))

plt.figure(figsize=(12, 4))
plt.axes([.05,.1,.4,.8])
plt.imshow(data,cmap=cm.jet,vmin=0,vmax=1)
plt.colorbar(fraction=.03)
plt.autoscale(False)
plt.axhline(y=20, c='w', lw=3)
plt.title('the damn white line')

rawDescription: Avoid change of figure size when adding plot() to imshow()


rawDescription: Is there a simple way to convert between bytes and their hex representations (also bytes) in python, like '\x1a\x2b\x3c\x4d' to '1a2b3c4d'?


code:
import yaml
yaml.load('string: 01', Loader=yaml.loader.BaseLoader)

rawDescription: Force YAML values to be strings

description: Force YAML values to be strings


code:
l = [1,1,0,1]

sum(j<<i for i,j in enumerate(reversed(l)))

rawDescription: Binary as list of 1s and 0s to int

description: Binary as list of 1s and 0s to int


rawDescription: How does numpy zeros implement the parameter shape?


code:
import pandas as pd
from numpy.random import randint
import matplotlib.pyplot as plt

df = pd.DataFrame(randint(0,10,(200,6)),columns=list('abcdef'))
grouped = df.groupby('a')
rowlength = grouped.ngroups/2                         # fix up if odd number of groups
fig, axs = plt.subplots(figsize=(9,4),
                        nrows=2, ncols=rowlength,     # fix as above
                        gridspec_kw=dict(hspace=0.4)) # Much control of gridspec

targets = zip(grouped.groups.keys(), axs.flatten())
for i, (key, ax) in enumerate(targets):
    ax.plot(grouped.get_group(key))
    ax.set_title('a=%d'%key)
ax.legend()
plt.show()

rawDescription: How to create Pandas groupby plot with subplots?

description: Create Pandas groupby plot with subplots


code:
import RPi.GPIO as GPIO
import time

# Module level constants
LED1 = 22
LED2 = 17

# Sets up pins as outputs
def setup(*leds):
    GPIO.cleanup()
    GPIO.setmode(GPIO.BCM)
    for led in leds:
        GPIO.setup(led, GPIO.OUT)
        GPIO.output(led, GPIO.LOW)

# Turn on and off the leds
def blink(*leds):
    # Blink all leds passed
    for led in leds:
        GPIO.output(led, GPIO.HIGH)
        time.sleep(1)
        GPIO.output(led, GPIO.LOW)

if __name__ == '__main__':
    # Setup leds
    setup(LED1, LED2)
    # Run blinking forever
    try:
        while True:
            blink(LED1, LED2)
    # Stop on Ctrl+C and clean up
    except KeyboardInterrupt:
        GPIO.cleanup()

rawDescription: RuntimeWarnings with GPIO.setup and GPIO.cleanup not work with KeyboardInterrupt


code:
class Bar:
    pass

class MyUnpickler(pickle.Unpickler):
    def find_class(self, module, name):
        if module == "foo" and name == "Bar":
            return Bar
        else:
            return pickle.Unpickler.find_class(self, module, name)

bars = MyUnpickler(open("objects.pkl")).load()

rawDescription: How to substitute module.Class() to locally defined Class() when loading with Python's Pickle?

description: Substitute module.Class() to locally defined Class() when loading with Python's Pickle


code:
def return_none(*args, **kwargs):
    """Ignores all arguments and returns None."""
    return None

class MyClass(object):
    def __getattr__(self, attrname):
        """Handles lookups of attributes that aren't found through the normal lookup."""
        return return_none

rawDescription: Python: making a class that return None on any function calls


code:
import math
def myRounding(x):
   return math.ceil(x*100) / 100.0

rawDescription: Problem with nontypical rounding in python


code:
import fileinput
import sys

def delete ():

    train = input("Enter the train time that you want to remove: ")
    train = train.strip()

    # REMEMBER WHICH LINE THE TRAIN WAS FOUND ON
    train_found_on = None

    # OPEN THE FILE FOR IN-PLACE WRITING
    for i, line in enumerate(fileinput.input('schedule.txt', inplace=1)):

        # NEVER WRITE OUT THE LINE WHERE THE TRAIN WAS MATCHED
        if 'Time:' in line and train in line:
            train_found_on = i
            continue

        # NOR THE LINES AFTER IN THAT BLOCK
        if train_found_on and i < (train_found_on + 7):
            continue

        # BUT WRITE OUT THE OTHERS
        sys.stdout.write(line)

rawDescription: Removing lines after one selected in file using python


code: m = max(map(lambda x: os.path.getmtime(x[0]), os.walk("directory")))

rawDescription: Find last update time of a directory (includes all levels of sub folders)


code:
df
df["col"].str.split(", ")
df["col"].str.split(", ").str[1]

rawDescription: String splitting loop through Dataframe

description: String splitting loop through Dataframe


code:
import threading
import subprocess

def popenAndCall(onExit, popenArgs):
    """
    Runs the given args in a subprocess.Popen, and then calls the function
    onExit when the subprocess completes.
    onExit is a callable object, and popenArgs is a list/tuple of args that
    would give to subprocess.Popen.
    """
    def runInThread(onExit, popenArgs):
        proc = subprocess.Popen(*popenArgs)
        proc.wait()
        onExit()
        return
    thread = threading.Thread(target=runInThread, args=(onExit, popenArgs))
    thread.start()
    # returns immediately after the thread starts
    return thread

rawDescription: Python subprocess: callback when cmd exits


code:
f = plt.figure(figsize=(5,5))
plt.subplot(2, 2, 1)
# this "A" is clipped in the plot
plt.annotate("A",
             xy = (-0.25, 1.1),
             xytext = (-0.25, 1.1),
             xycoords = 'axes fraction',
             textcoords = 'axes fraction',
             fontsize=30)
plt.subplot(2, 2, 2)
plt.subplot(2, 2, 3)
plt.subplot(2, 2, 4)
plt.tight_layout()
plt.subplots_adjust(top=0.9)
plt.show()

rawDescription: how to change figure canvas size in matplotlib without altering plots?

description: Change figure canvas size in matplotlib without altering plots


code:
import multiprocessing
pool = multiprocessing.Pool(processes=4)
def fu(chunk):
    #your code here
    return result

def produce_data(data):
    while data:
        #you need to split data
        yield chunk

result = pool.map(fu,produce_data(data))
# result will be ordered list of results for each chunk

rawDescription: Parallelizing a CPU-bound Python function


code:
def chain_method(from_method, to_method):
    def inner(arg):
        return to_method(from_method(arg))
    return inner

possible_funcs = []
log_strings = []
for possible_combo in itertools.product([Seq.head,Seq.odd,Seq.even,Seq.reverse], repeat=4):
    meta_method = possible_combo[0]
    for method in possible_combo[1:]:
        meta_method = chain_method(meta_method, method)
    log_string = []
    for method in possible_combo:
        log_string.extend(['.', method.__name__, '()'])
    possible_funcs.append(meta_method)
    log_strings.append("".join(log_string))

rawDescription: how to enumerate class method then chain them with itertools.product() in python?

description: Enumerate class method then chain them with itertools.product() in python


code:
class MySerializer(serializers.ModelSerializer):
    proposal_side = serializers.SlugRelatedField(many=False, read_only=False, slug_field='proposal_side')
    my_proposal_type = serializers.SlugRelatedField(many=False, read_only=False, slug_field='proposal_type')
    my_proposal_delivery_type = serializers.SlugRelatedField(many=False, read_only=False, slug_field='delivery_type')
    my_survey_method = serializers.SlugRelatedField(many=False, read_only=False, slug_field='method')
    class Meta:
        model = diliModels.Proposal
        fields = (
            'id'
            ,'my_proposal_side'
            ,'my_proposal_type'
            ,'number_of_participants'
            ,'cost_per_participants'
            ,'minimum_dollar_commitment'
            ,'commercial_terms'
            ,'is_publicly_visible'
            ,'is_anonymous'
            ,'is_republish'
            ,'name'
            ,'my_delivery_type'
            ,'my_survey_method'
            ,'number_of_unique_contacts'
            ,'availability_start'
            ,'availability_end'
            ,'location_country'
            ,'location_city'
            ,'location_state'
            ,'description'
            ,'desired_meetings'
        )

    def validate(self, attrs):
         raise serializers.ValidationError("error")
         return attrs

rawDescription: How to validate a model in django rest framework?

description: Validate a model in django rest framework


code:
import csv
with open('output1.txt','w') as out1, open('file1.csv') as f1:
     csvf1=csv.reader(f1)

     for txt1 in csvf1:
           id1=txt1[0]
           z1=txt1[1]

           with open('file2.csv') as f2:
               csvf2=csv.reader(f2)
               for txt2 in csvf2:
                   id2=txt2[0]
                   z2=txt2[3]
                   ra=txt2[1]
                   if id1 == id2:
                       out1.write("{} {} {}\n".format(id2,z1,ra))

rawDescription: loop for two files only prints first line python

description: Loop for two files only prints first line python


code:
def check_maximize(event):
    screen_w, screen_h = root.winfo_screenwidth(), root.winfo_screenheight()
    window_w, window_h = root.winfo_width(), root.winfo_height()

    # check if window is as wide as screen and between height of screen and 100 pixels
    # to compensate for task bar
    if screen_w == window_w and screen_h > window_h > screen_h - 100:
        print('Maximized or Maximised')

root = Tk()

root.bind('<Configure>', check_maximize) # callback on window move/resize

mainloop()

rawDescription: Function called by window maximise

description: Function called by window maximise


code: [d for d in l if d['name'].startswith('Tom')]

rawDescription: How to parse for wildcard values in dictionary inside a list?

description: Parse for wildcard values in dictionary inside a list


code:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# all your fancy plotting code

ax.xaxis.set_major_locator(mdates.AutoDateLocator())
ax.xaxis.set_major_formatter(mdates.AutoDateFormatter())

plt.show()

rawDescription: matplotlib - what kind of set_major_locator should I use

description: Matplotlib - what kind of set_major_locator should I use


code:
from yourapp.models import YourModel

class CustomDebugMiddleware_first(object):
    def process_request(self, request):
         new_http_information = YourModel(http_info=INFO_YOU_WANT_TO_SAVE)
         new_http_information.save()

rawDescription: Python, Django - how to store http requests in the middleware?


code:
class MyApp(object):
    def __init__(self):
        self.root = Tk()
        self.root.wm_title("ImagePro")

        #Original
        original = Image.open(infile)
        (w, h) = (original.size[0], original.size[1])
        tkpi = ImageTk.PhotoImage(original)
        label = Label(self.root, image=tkpi)
        label.grid(row =0, column=0, padx=5,pady=5)

        img = original.copy().convert("L")
        tkpi2 = ImageTk.PhotoImage(img)
        label = Label(self.root, image=tkpi2)
        label.grid(row =0, column=1, padx=5,pady=5)

        Label(self.root, text = "Original").grid(row=1, column=0)
        Label(self.root, text = "Modified").grid(row=1, column=1)

        self.buttonframe = Frame(self.root)
        self.buttonframe.grid(row=2, column=0, columnspan=2)
        Button(self.buttonframe, text = "Brighten").grid(row=0, column=0)
        Button(self.buttonframe, text = "Darken").grid(row=0, column=1)
        Button(self.buttonframe, text = "Warm").grid(row=0, column=2)
        Button(self.buttonframe, text = "Cool").grid(row=0, column=3)

        self.root.mainloop()

rawDescription: How to line up buttons on Tkinter

description: Line up buttons on Tkinter


code:
from itertools import product

list(product(possible_frequency, clamp_range))

rawDescription: All possible tuples

description: All possible tuples


rawDescription: How floats are stored in python

description: How floats are stored in python


rawDescription: Convert a very large base n number to bytes


code:
from werkzeug.test import Client
from werkzeug.wrappers import Response

client = Client(current_app, response_wrapper=Response)
res = client.open(
    method='GET',
    path='/api/v1/device/'
)

rawDescription: user-defined command instead of curl for REST api

description: User-defined command instead of curl for REST api


code:
my_table = Table('my_temp_table', metadata,
    Column('id', Integer, primary_key=True),
    prefixes=['TEMPORARY'],
    postgresql_on_commit='PRESERVE ROWS')

rawDescription: Making sqlalchemy not drop (or truncate) temporary tables on commit


code:
fig, ax = plt.subplots(1, 1)

ax.bar([0, 1, 2], [1, 2, 3], color='b', align='center')
ax.axvspan(0, 1, color='k', alpha=.75, zorder=-1)
ax.axvspan(1, 2, color='r', alpha=.75, zorder=-1)
ax.set_ylim([0, 5])
ax.set_xlabel('fake x')
ax.set_ylabel('fake y')

rawDescription: Stuck colored filled area in bar chart, python


code: a = [i for i in a if i != p]

rawDescription: Removing elements from an array in python


code:
from win32com import client

class Excel(object):
    def __init__(self):
        self._app = client.Dispatch("Excel.Application")

    def get(self, cell):
        return self._app.Range(cell).value

    def show(self):
        self._app.Visible = 1

    def __getattr__(self, name):
        try:
            return getattr(self._app, name)
        except AttributeError:
            raise AttributeError(
                "'%s' object has no attribute '%s'" % (type(self).__name__, name))

rawDescription: Extend Python object in run-time using inheritance


code:
def aircraftListBoxRefresh():
    sqlConnect=sqlite3.connect("fglconfdb")
    sqlCursor=sqlConnect.cursor()
    sqlCursor.execute("SELECT fgAircraftDir FROM fglconfig")
    adl=sqlCursor.fetchall()
    for x in adl:
        aircraftDirectories.append(x)

aircraftDirectories=[]
aircraftDir=StringVar(value=aircraftDirectories)
aircraftListBox=Listbox(mainframe,height=7,width=100,listvariable=aircraftDir)
aircraftListBox.place(x=170,y=170)

rawDescription: Can't edit a tuple from inside a function


code:
import iso8601
stamp, tz = s.split()
timezone = iso8601.iso8601.parse_timezone(tz[:3] + ':' + tz[3:])
dt = datetime.fromtimestamp(int(stamp)).astimezone(timezone)

rawDescription: Parse UNIX timestamp with timezone offset (e.g. "14232335 +0200")


code:
list_of_dicts = xmlrpc_call(...)
objects_to_put = []

for row in list_of_dicts.items():
    object = DatastoreModel(**row)
    object.x = ...
    objects_to_put.append(object)
    if len(objects_to_put) > 10:
        db.put_async(objects_to_put)
        del objects_to_put[:]

db.put_async(objects_to_put)

rawDescription: What's the most memory-efficient way of creating a large batch of datastore objects on Google App Engine?


code:
class Membership(db.Model):
    user = db.ReferenceProperty(UserModel)
    membership_class = db.StringProperty()
    membership_code = db.StringProperty()
    live = db.BooleanProperty(default = False)
    membership_active = db.BooleanProperty(default = False)
    activated = db.BooleanProperty(default = False)
    documents_left = db.IntegerProperty(default = 0)

rawDescription: How can I better use filters in appengine to save me filtering by looping through a long list of entities?

description: Better use filters in appengine to save me filtering by looping through a long list of entities


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

x = np.linspace(1,10,1000)

flogs = [lambda x, a=a: np.log(a * x) for a in range(1,4)]
fexps = [lambda x, a=a: np.exp(a * x) for a in [0.18,0.2]]
funcs = flogs + fexps

fig = plt.figure()
ax = fig.add_subplot(111)

for func in funcs:
    ax.plot(x,func(x))

def add_ellipse(funcs, x):
    # the y-coordinate of the center of our ellipse:
    y = np.mean([funcs[i](x) for i in range(len(funcs))])
    # fix the width of the ellipse to this value:
    w = 0.4
    # find the height of the ellipse needed, and pad a bit:
    h = np.ptp([funcs[i](x) for i in range(len(funcs))]) * 1.5
    e = Ellipse(xy=(x,y), width=w, height=h, angle=0)
    e.set_facecolor('none')
    ax.add_artist(e)

add_ellipse(fexps, 8.5)
add_ellipse(flogs, 8)

plt.show()

rawDescription: How to surround curves with annotation in matplotlib?

description: Surround curves with annotation in matplotlib


code:
from cv import *

storage = CreateMemStorage(0)
img = LoadImage(file)  # or read from camera

found = list(HOGDetectMultiScale(img, storage, win_stride=(8,8),
                padding=(32,32), scale=1.05, group_threshold=2))

rawDescription: How can I detect and track people using OpenCV?

description: Detect and track people using OpenCV


code:
def convert(numerator, denominator):
    #print("---->", numerator, "/", denominator)
    result = [str(numerator//denominator) + "."]
    subresults = [numerator % denominator]          ### changed ###
    numerator %= denominator
    while numerator != 0:
        #print(numerator)
        numerator *= 10
        result_digit, numerator = divmod(numerator, denominator)
        result.append(str(result_digit))             ### moved before if-statement

        if numerator not in subresults:
            subresults.append(numerator)
            #print("appended", result_digit)

        else:
            result.insert(subresults.index(numerator) + 1, "(")   ### added '+ 1'
            #print("index", subresults.index(numerator), subresults, "result", result)
            result.append(")")
            #print("repeating", numerator)
            break
    #print(result)
    return "".join(result)

rawDescription: Convert fraction to string with repeating decimal places in brackets


code:
# myapp/__init__.py (main config)
def main(global_config, **settings):
    config = Configurator(...)
    # basic setup of your app
    config.include('pyramid_tm')
    config.include('pyramid_jinja2')

    # add config for each of your subapps
    config.include('project.app1')
    config.include('project.app2')

    # make wsgi app
    return config.make_wsgi_app()

# myapp/app1/__init__.py (app1's config)
def includeme(config):
    config.add_route(...)
    config.scan()

# myapp/app2/__init__.py (app2's config)
def includeme(config):
    config.add_route(...)
    config.scan()

rawDescription: Pyramid project structure

description: Pyramid project structure


code:
x = Counter(factors(a))
y = Counter(factors(b))

min = x & y

gcd = 1

for key, value in min.items():
    gcd = gcd * key ** value

return gcd

rawDescription: Finding the GCD using Counter - Python

description: Finding the GCD using Counter - Python


code:
my_list = [func_test_1, func_test_2, func_test_3]
random.choice(my_list)()

rawDescription: Syntax to call random function from a list


rawDescription: how to random a list using python

description: Random a list using python


code:
# Create the big lists in advance to avoid skewing the memory counts
seq1 = [None] * 10**6 # Big list of references to None
seq2 = seq1[::10]

# Create and reference a lot of smaller lists
seq1[:] = [[] for x in range(10**6)] # References all the new lists
seq2[:] = seq1[::10] # Grab a second reference to 10% of the new lists

# Memory fragmentation in action
seq1[:] = [None] * 10**6 # 90% of the lists are no longer referenced here
seq2[:] = seq1[::10] # But memory freed only after last 10% are dropped

rawDescription: Why doesn't memory get released to system after large queries (or series of queries) in django?


code:
from scipy.optimize import differential_evolution

def func(parameters, *data):

    #we have 3 parameters which will be passed as parameters and
    #"experimental" x,y which will be passed as data

    a,b,c = parameters
    x,y = data

    result = 0

    for i in range(len(x)):
        result += (a*x[i]**2 + b*x[i]+ c - y[i])**2

    return result**0.5

if __name__ == '__main__':
    #initial guess for variation of parameters
    #             a            b            c
    bounds = [(1.5, 0.5), (-0.3, 0.3), (0.1, -0.1)]

    #producing "experimental" data
    x = [i for i in range(6)]
    y = [x**2 for x in x]

    #packing "experimental" data into args
    args = (x,y)

    result = differential_evolution(func, bounds, args=args)
    print(result.x)

rawDescription: Scipy, differential evolution

description: Scipy, differential evolution


code:
cols_to_keep = ['User_ID', 'Year']
df[cols_to_keep].to_hdf(...)

rawDescription: pandas - How to save only selected columns of a DataFrame to HDF5

description: Pandas - How to save only selected columns of a DataFrame to HDF5


code:
def __repr__(self):
    return 'MyClass #%d' % (self.id,)

rawDescription: Something more beautiful than <__main__.MyClass instance at 0x1624710>


code:
#!/usr/bin/env python3
import asyncio

async def some_coroutine(loop):
    task = loop.create_task(asyncio.sleep(1))  # just some task
    await task # wait for it (inside a coroutine)

loop = asyncio.get_event_loop()
task = loop.create_task(asyncio.sleep(1)) # just some task
loop.run_until_complete(task) # wait for it (outside of a coroutine)
loop.run_until_complete(some_coroutine(loop))

rawDescription: How can I wait for task until complete when the task is created by create_task()?

description: Wait for task until complete when the task is created by create_task()


code:
import os

clear = lambda : os.system('tput reset')
clear()

rawDescription: Completely clearing the terminal window using Python


code:
class FeatureManager(models.Manager):

    @staticmethod
    def _test_cases_eq_0( qs ):
       return qs.annotate( num_test_cases=models.Count('testcase_set') ).filter(num_test_cases=0)

    @staticmethod
    def _standardized_gt_0( qs ):
        return qs.annotate( standardised=Count('documentation_set__standard') ).filter(standardised__gt=0)

    def without_test_cases(self):
        return self._test_cases_eq_0( self.get_query_set() )

    def standardised(self):
        return self._standardized_gt_0( self.get_query_set() )

    def intersection( self ):
        return self._test_cases_eq_0( self._standardized_gt_0( self.get_query_set() ) )

rawDescription: How can I find the intersection of two Django querysets?

description: Find the intersection of two Django querysets


code:
import mimetypes

mimetypes.add_type('image/svg+xml', '.svg')
#                        ^ no s

rawDescription: How do I serve a static SVG file with Flask?

description: Serve a static SVG file with Flask


code:
test = ['Item 1', [['Item 1.1', []], ['Item 1.2', []]]]

def convert(oldlist, newlist):
    for i in range(len(oldlist)):
        if type(oldlist[i]) == list and type(oldlist[i][0]) != list:
            newlist.append(oldlist[i][0])
        elif type(oldlist[i]) != list:
            newlist.append(oldlist[i])
        else:
            newlist.append([])
            convert(oldlist[i], newlist[-1])
    return newlist

print(convert(test, []))

rawDescription: Converts old style lists to the new easier to understand format


code:
# -*- coding: utf-8 -*-
import kivy
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
from kivy.uix.label import Label

Builder.load_string(
'''
#:import la kivy.adapters.listadapter
#:import lbl kivy.uix.label

<TI>
    but: but
    ListView:
        id: but
        adapter: la.ListAdapter(data=[], cls=lbl.Label)

<MyLabel>:
    font_name: 'data/fonts/DejaVuSans.ttf'
''')

class MyLabel(Label):
    pass

class TI(FloatLayout):
    def __init__(self, **kwargs):
        super(TI, self).__init__(**kwargs)
        self.but.adapter.data = [u'سلام دنیا']
        self.but.adapter.cls = MyLabel

class MyApp(App):
    def build(self):
        return TI()

if __name__ == '__main__':
    MyApp().run()

rawDescription: wrinting persian in kivy list view item

description: Wrinting persian in kivy list view item


code:
try:
    from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
    from django.contrib.auth.models import User
else:
    User = get_user_model()

rawDescription: A better way to import AUTH_USER_MODEL in Django 1.5


rawDescription: Allow a ToolItem to fill horizontally in a Toolbar


code:
IMDBLOGIN = "https://secure.imdb.com/register/login?ref_=nv_usr_lgin_3"
form = OrderedDict([("49e6c", "3478"), ("login", self.username), ("password",  self.password)])
cj = CookieJar()
opener = build_opener(HTTPHandler(), HTTPSHandler(), HTTPErrorProcessor(),
                     HTTPRedirectHandler(), HTTPCookieProcessor(cj))
params = urlencode(form)
response = opener.open(IMDBLOGIN, params)

# cookies automatically sent
response2 = opener.open(csv_url)
content = response2.read()

rawDescription: access IMDB watchlist in CSV format

description: Access IMDB watchlist in CSV format


code:
from django import forms

class MyForm(forms.Form):
    my_file = forms.FileField()

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['my_file'].widget.attrs.update({'accept': 'image/*'})

rawDescription: Subclassing django's fileField form's widget?


code:
class LocationForm(ModelForm):
    ...
    def save(self, commit=True, **kwargs):
        # create the instance but don't commit it to the database
        location = super(LocationForm, self).save(commit=False, **kwargs)

        # now set your cleaned fields on the model instance
        location.cleanedStreetAddress = ...

        if commit:
            location.save()

        return location

rawDescription: Extra fields in Django ModelForms: I can see them, but cannot save them to the model. Why?


code:
import wx
import wx.grid

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.panel = wx.Panel(self)
        self.grid = wx.grid.Grid(self.panel)
        self.grid.CreateGrid(3, 3)
        self.grid.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.grid.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
        self.grid.Bind(wx.EVT_CHAR_HOOK, self.OnChar)

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.grid, 1)

        self.panel.SetSizerAndFit(self.sizer)
        self.Show()

    # You may or may not want to add e.Skip() to your RETURN key handling.
    # If you do not call e.Skip(), the event is not propagated to the widget.
    # Depends on your app logic if that is something you want or not.

    def OnKeyDown(self, e):
        # Python 2.7, wxPython 2.8 - Works, but more like EVT_CHAR_HOOK
        # Python 3.3, wxPython Phoenix - Never shows up
        code = e.GetKeyCode()
        if code in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:
            print("Return key down")
        else:
            e.Skip()

    def OnKeyUp(self, e):
        code = e.GetKeyCode()
        if code in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:
            print("Return key up")
        else:
            e.Skip()

    def OnChar(self, e):
        # Python 2.7, wxPython 2.8 - Never shows up
        # Python 3.3, wxPython Phoenix - Works
        code = e.GetKeyCode()
        if code in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:
            print("Return key char")
        else:
            e.Skip()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: Processing Return key in wxGrid class

description: Processing Return key in wxGrid class


code:
xs = np.random.randn(10000)
ax1 = plt.subplot(111)
cnt, bins, patches = ax1.hist(xs)

# area under the istogram
area = np.dot(cnt, np.diff(bins))

ax2 = ax1.twinx()
ax2.grid('off')

# align the twinx axis
ax2.set_yticks(ax1.get_yticks() / area)
lb, ub = ax1.get_ylim()
ax2.set_ylim(lb / area, ub / area)

# display the y-axis in percentage
from matplotlib.ticker import FuncFormatter
frmt = FuncFormatter(lambda x, pos: '{:>4.1f}%'.format(x*100))
ax2.yaxis.set_major_formatter(frmt)

rawDescription: Scaling the second axe on a histogram with Matplotlib


code:
"""
.. versionadded:: 1.1.0
   This demo depends on new features added to contourf3d.
"""

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm

fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = ax.contourf(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)

ax.set_xlabel('X')
ax.set_xlim(-40, 40)
ax.set_ylabel('Y')
ax.set_ylim(-40, 40)
ax.set_zlabel('Z')
ax.set_zlim(-100, 100)

plt.show()

rawDescription: python : 2D perspective projection of a 3D surface plot

description: Python : 2D perspective projection of a 3D surface plot


code: zip(input, input[1:])[::2]

rawDescription: Turn flat list into two-tuples

description: Turn flat list into two-tuples


code:
gradebook = list()
with open('scores.txt') as infile:
    for line in file:
        line = line.split(':').rstrip()
        gradebook.append((line[0], line[1]))

rawDescription: Sorting and printing a text file in Python idle


code:
plt.imshow(dat2, interpolation='none', aspect='auto', origin='upper',
           cmap=cmap, vmin=0, vmax=4)

rawDescription: Make a heatmap with a specified discrete color mapping with matplotlib in python


code:
a = [1,2,3,4,5]
b = iter(a)

try:
    while True:
        c = b.next()
        if (condition):
            c = b.next()
except StopIteration:
    pass

rawDescription: Iterate again within the for loop

description: Iterate again within the for loop


code:
def is_close(object1, object2, distance):
    return math.hypot(object2.x-object1.x, object2.y-object1.y) < float(distance)

... #rest of your code

while True:  #This is your main while loop
    ... #rest of your code

    for enemy in enemies:
        if is_close(player, enemy, 25):
            enemy.state = new_state  #change state, this may simply be a color change

rawDescription: If player comes within a radius of enemy,change state


code:
import os
import sys

from dropbox.client import DropboxClient

# get an access token, local (from) directory, and Dropbox (to) directory
# from the command-line
access_token, local_directory, dropbox_destination = sys.argv[1:4]

client = DropboxClient(access_token)

# enumerate local files recursively
for root, dirs, files in os.walk(local_directory):

    for filename in files:

        # construct the full local path
        local_path = os.path.join(root, filename)

        # construct the full Dropbox path
        relative_path = os.path.relpath(local_path, local_directory)
        dropbox_path = os.path.join(dropbox_destination, relative_path)

        # upload the file
        with open(local_path, 'rb') as f:
            client.put_file(dropbox_path, f)

rawDescription: How to upload complete folder to Dropbox using python

description: Upload complete folder to Dropbox using python


rawDescription: Custom sort of list of dicts Python

description: Custom sort of list of dicts Python


code:
import operator

OPERATORS = operator.__dict__

def evaluate_expression(expr):
    try:
        return int(expr)
    except ValueError:
        pass
    op, _, args = expr.rpartition('(')
    rest, _, thisop = op.rpartition(',')
    args = args.rstrip(')').split(',')
    argvalues = map(int, args)
    thisvalue = OPERATORS[thisop](*argvalues)
    if rest:
        return evaluate_expression('{},{}'.format(rest, thisvalue))
    return thisvalue

while True:
    expr = input()
    print(evaluate_expression(expr))

rawDescription: Parsing list to create python code

description: Parsing list to create python code


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

plt.figure(figsize=(12,4))

# Example 1
plt.subplot(1,4,1)
line1 = np.array([[-1,0],[0,0]])
line2 = np.array([[0,0],[1,1]])
line3 = np.array([[-1,-1],[0,0]])
line4 = np.array([[0,0],[1,0]])
plt.plot(line1[:,0], line1[:,1], 'b', linewidth=4)
plt.plot(line2[:,0], line2[:,1], 'b', linewidth=4)
plt.plot(line3[:,0], line3[:,1], 'b--', linewidth=4)
plt.plot(line4[:,0], line4[:,1], 'b--', linewidth=4)

# Example 2
plt.subplot(1,4,2)
x1 = np.linspace(-1,1,100)
x2 = np.linspace(-1,1,100)
y1 = x1*0
y2 = x2
plt.plot(x1,y1,'r', linewidth=4)
plt.plot(x2,y2,'g', linewidth=4)

# Example 3
plt.subplot(1,4,3)
#some sort of split condition:
solid1 = x1<0
solid2 = x2>0
#plot each line in two seperate plot calls
plt.plot(x1[solid1], y1[solid1], 'r', linewidth=4)
plt.plot(x1[np.logical_not(solid1)], y1[np.logical_not(solid1)], 'r--', linewidth=4)
plt.plot(x2[solid2], y2[solid2], 'g', linewidth=4)
plt.plot(x2[np.logical_not(solid2)], y2[np.logical_not(solid2)], 'g--', linewidth=4)

# Example 4
plt.subplot(1,4,4)
# put the spines to the middle
ax = plt.gca()
ax.spines['left'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('center')
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

plt.show()

rawDescription: Changing line style for certain range of values using matplotlib


code:
import sys
from PyQt5 import QtGui, QtCore, QtWidgets

class MyApp(object):
    def __init__(self):
        super(MyApp, self).__init__()
        self.mainWidget = QtWidgets.QWidget()
        self.mainLayout = QtWidgets.QVBoxLayout()
        self.mainWidget.setLayout(self.mainLayout)

        self.slider = QtWidgets.QSlider()
        self.slider.setOrientation(QtCore.Qt.Horizontal)
        self.slider.setStyleSheet(self.stylesheet())

        self.mainLayout.addWidget(self.slider)
        self.mainWidget.show()
        sys.exit(app.exec_())

    def stylesheet(self):
        return """
            QSlider::groove:horizontal {
                background: white;
                height: 40px;
            }

            QSlider::sub-page:horizontal {
                background: qlineargradient(x1: 0, y1: 0,    x2: 0, y2: 1,
                    stop: 0 #66e, stop: 1 #bbf);
                background: qlineargradient(x1: 0, y1: 0.2, x2: 1, y2: 1,
                    stop: 0 #bbf, stop: 1 #55f);
                height: 40px;
            }

            QSlider::add-page:horizontal {
                background: #fff;
                height: 40px;
            }

            QSlider::handle:horizontal {
                background: #bbf;
                border: 0px;
                width: 0px;
                margin-top: 0px;
                margin-bottom: 0px;
                border-radius: 0px;
            }
        """

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

rawDescription: How to create graphic slider in Python that can be modified with mouse?

description: Create graphic slider in Python that can be modified with mouse


code:
from cffi import FFI
ffi = FFI()
ffi.cdef('typedef enum {RANDOM, IMMEDIATE, SEARCH} strategy;')
c = ffi.dlopen('c')
c.RANDOM
c.IMMEDIATE
c.SEARCH

rawDescription: Accessing cffi enums

description: Accessing cffi enums


rawDescription: How to generate an optimal order of multiple elements based on pairwise element score values

description: Generate an optimal order of multiple elements based on pairwise element score values


code:
from string import punctuation
import csv

strs = "Hello! It's a nice day."

with open('abc.csv', 'w') as f:
    writer = csv.writer(f, delimiter=',')
    writer.writerow(['ID', 'PUNCTUATION', 'WORD'])
    #use enumerate to get word as well as index
    table = dict.fromkeys(map(ord, punctuation))
    for i, word in enumerate(strs.split(), 1):
        #str.translate is faster than regex
        new_strs = word.translate(table)
        #if the new word is not equal to original word then use 'Y'
        punc = 'Y' if new_strs != word else 'N'
        writer.writerow([i, punc, new_strs])

rawDescription: Remove punctuation and create .csv file with list of words, flagged with whether punctuation existed


code:
import MySQLdb
# connect
db = MySQLdb.connect(host="localhost", user="root", passwd="xxxxxxx", db="world")
cursor = db.cursor()

for x in xrange(1,1000,2):
    cursor.execute('INSERT INTO table (mynumber) VALUES(' + str(x) + ');')

rawDescription: Directing the output of a python code to msqldb table


rawDescription: Blender open a hyperlink by clicking on object


code: list('the string')

rawDescription: Python: Split a string, including the whitespace character


code:
from PyQt5.QtGui import QDesktopServices
from PyQt5.QtCore import QUrl

class MainWindow(QMainWindow, Ui_MainWindow):
    def link(self, linkStr):

        QDesktopServices.openUrl(QUrl(linkStr))

    def __init__(self):
        super(MainWindow, self).__init__()

        # Set up the user interface from Designer.
        self.setupUi(self)
        self.label.linkActivated.connect(self.link)
        self.label.setText('Stackoverflow/')

rawDescription: How can I make link on web page in window using pyqt4?

description: Make link on web page in window using pyqt4


code:
class Answer(models.Model):
    answer_title = models.TextField(...)
    question = models.ForeignKey(Question, related_name='answer_set')

    class Meta:
        abstract = True

    objects = InheritanceManager()

rawDescription: django - getting related subclassed objects

description: Django - getting related subclassed objects


code:
Array = ['foo', 'bar']

for item in Array:
    if item.startswith('fo'):
        print(Array.index(item))

rawDescription: Return an index of a string stored in an array


code:
def link_callback(uri, rel):
    if uri.find('chart.apis.google.com') != -1:
        return uri
    return os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))

rawDescription: Using an image URL for link_callback in the pisa html to pdf library


code:
if (x['name'] in list1 or
    x['name'] in list2 or
    x['name'] in list3):
    ...

rawDescription: Python check variable against multiple lists


code:
import sys
sys._getframe(number)

rawDescription: In Python, how do I obtain the current frame?


code:
s = "Split along words, preserve punctuation!"
re.sub(r"\s+|\b", '\f', s).split('\f')

rawDescription: Why doesn't Python's `re.split()` split on zero-length matches?


rawDescription: List Comprehension in Python

description: List Comprehension in Python


code:
tagged = nltk.pos_tag(txt)
tags =  [ e[1] for e in tagged]
tags

rawDescription: How to print out tags in python

description: Print out tags in python


code:
import re

...

outf = open('myout', 'r+')
inf = open('infile', 'r')
outdata = outf.read()
for line in inf:
    outdata = re.sub("(?<=Status of %s: )'N/A'" % line.strip().split()[0], line.strip().split()[2], outdata)
outf.write(outdata)
outf.close()
inf.close()

rawDescription: Managing text inside files in Python

description: Managing text inside files in Python


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

x = np.arange(0, 5, 0.1)
y = np.sin(x)

plt.plot(x,
         y,
         marker='o',
         fillstyle='full',
         markeredgecolor='red',
         markeredgewidth=0.0)

rawDescription: How to remove outline of circle marker when using pyplot.plot in matplotlib

description: Remove outline of circle marker when using pyplot.plot in matplotlib


code:
bs = b'\x80\x03}q\x00(X\x03\x00\x00\x00ageq\x01K\x14X\x05\x00\x00\x00scoreq\x02KXX\x04\x00\x00\x00nameq\x03X\x03\x00\x00\x00Bobq\x04u.'
import pickle
loaded = pickle.loads(bs)
loaded

rawDescription: How to translate a known binary data into a object in Python?

description: Translate a known binary data into a object in Python


code:
for button in buttonslist:
    button.connect("clicked",button_function)

rawDescription: Multiple buttons to call same function in python Gtk


rawDescription: django query - how to get latest row during distinct

description: Django query - how to get latest row during distinct


code:
line(x,y, color="#0000FF", tools="pan,wheel_zoom,box_zoom,reset",
     name="line_example", plot_width=800, plot_height=300)

rawDescription: How to change size of bokeh figure

description: Change size of bokeh figure


code:
from collections import Counter

foo = lambda x: ','.join(sorted([k for k,v in Counter(x).iteritems() if v>=3]))

df['new'] = df['column'].str.split(',').map(foo)

#In [33]: df
#Out[33]:
#    column NewColumn new
#0  A,A,A,C         A   A
#1  C,B,C,C         C   C
#2  B,B,B,B         B   B

rawDescription: How to loop through a dataframe, create a new column and append values to it in python

description: Loop through a dataframe, create a new column and append values to it in python


code:
def timeConvert():
    miliTime = input("Enter a time in hh:mm (military) format: ")
    hours, minutes = miliTime.split(":")
    hours, minutes = int(hours), int(minutes)
    setting = "AM"
    if hours > 12:
        setting = "PM"
        hours -= 12
    print(("%02d:%02d" + setting) % (hours, minutes))

rawDescription: 0-23 hour military clock to standard time (hh:mm)


code:
session.get(domain+"/export_data_test/convertxl.aspx",
            params=payload,
            allow_redirects=True,
            verify=certifi.where())

rawDescription: Python Requests - Download File From Get Form


code: return [compute_something(x).a_property_of_z for x in xs]

rawDescription: Pythonic way of handling two statements in a for loop?


rawDescription: Python: Finding max of a dictionaries tupled-value


code: bind_layers( Ether,         ARP,           type=2054)

rawDescription: Adding a new protocol to scapy (Similiar to ARP)


code:
for i in range(nMoments):
    middle[i] = middle[i].subs(K, m1[i]**2/m2[i])

rawDescription: sympy sequential substitution python

description: Sympy sequential substitution python


code:
def get_context_data(self, **kwargs):
    articles = Article.objects.order_by("-published_date")[:5]
    videos = Video.objects.order_by("-published_date")[:5]
    items = list(articles) + list(videos)
    items.sort(key=lambda i: i.published_date, reverse=True)
    return {"items": items[:5]}

rawDescription: Passing Multiple Models to a Template under a single context_object_name


code:
# Create some example data
points = np.array([[1,2,3,4]]);

# Just subtract the transpose from points
B = points - points.T

#   array([[ 0,  1,  2,  3],
#          [-1,  0,  1,  2],
#          [-2, -1,  0,  1],
#          [-3, -2, -1,  0]])

rawDescription: Given a list of n points, how can I generate a matrix that contains the distance from every point to every other point using numpy?


code:
import cv2
import numpy as np

window_x = 340
window_y = 340

cv2.namedWindow("Big picture")

capture1 = cv2.VideoCapture(0)
capture2 = cv2.VideoCapture(1)
capture3 = cv2.VideoCapture(3)

while True:

    ret, frame1 = capture1.read()
    ret, frame2 = capture2.read()
    ret, frame3 = capture3.read()

    #Create the big Mat to put all three frames into it
    big_frame = m = np.zeros((window_y, window_x*3, 3), dtype=np.uint8)

    # Resize the frames to fit in the big picture
    frame1 = cv2.resize(frame1, (window_y, window_x))
    frame2 = cv2.resize(frame2, (window_y, window_x))
    frame3 = cv2.resize(frame3, (window_y, window_x))
    rows,cols,channels = frame1.shape

    #Add the first frame to the big picture
    roi = big_frame[0:cols, 0:rows]
    dst = cv2.add(roi,frame1)
    big_frame[0:cols, 0:rows] = dst

    #Add second frame to the big picture
    roi = big_frame[0:cols, rows:rows*2]
    dst = cv2.add(roi,frame2)
    big_frame[0:cols, rows:rows*2] = dst

    #Add third frame to the big picture
    roi = big_frame[0:cols, rows*2:rows*3]
    dst = cv2.add(roi,frame3)
    big_frame[0:cols, rows*2:rows*3] = dst

    cv2.imshow("Big picture", big_frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

capture1.release()
capture2.release()
capture3.release()

cv2.destroyAllWindows()

rawDescription: How do I get a video feed to shrink to fit a window using OpenCV Beta 3.0.0 and Python 2.7.5?

description: Get a video feed to shrink to fit a window using OpenCV Beta 3.0.0 and Python 2.7.5


code:
import pandas as pd

df = pd.DataFrame({'contribution': [0.188137,0.160208,0.160208,0.151654,0.149489,0.135975,0.063206]}
                  ,index=['A','B','C','D','E','F','G'])

colors = ['b', 'green', 'y', 'pink','orange','cyan','darkgrey']

ax = df.plot(kind='barh', color=colors, legend=False)

for bar in ax.patches:
    bar.set_facecolor('#888888')

highlight = 'D'
pos = df.index.get_loc(highlight)

ax.patches[pos].set_facecolor('#aa3333')
ax.legend()

rawDescription: Pandas + Matplotlib, Make one color in barplot stand out


rawDescription: How to check if the header contains the string "example@example.com"?

description: Check if the header contains the string "example@example.com"


code:
def queryURI(self,e):
    global outDir
    valueYouWant = ""
    with queryURIDlg() as dlg:
        dlg.ShowModal()
        valueYouWant = dlg.getYourValue()
    self.ProgressBox.AppendText('Querying ' + valueYouWant)

rawDescription: Returning value from custom Dialog in Python


code:
import inspect
import pprint
import calendar

hc = calendar.HTMLCalendar()
hc.__class__.pathos = None
calendar.Calendar.phobos = None
pprint.pprint(inspect.classify_class_attrs(hc.__class__))

rawDescription: How would you determine where each property and method of a Python class is defined?


code:
p = u'<tag>((?:(?!</tag>).)*cheese.*?)</tag>'
patt = re.compile(p, re.UNICODE | re.DOTALL | re.IGNORECASE)
patt.findall(cheesetext)

rawDescription: python's re: multiple regex

description: Python's re: multiple regex


code:
import shlex
shlex.split('"abc dfg" ab da')

rawDescription: Remove " from regex result python

description: Remove " from regex result python


code:
def rchop(thestring, ending):
  if thestring.endswith(ending):
    return thestring[:-len(ending)]
  return thestring

somestring = rchop(somestring, ' rec')

rawDescription: python: remove substring only at the end of string

description: Python: remove substring only at the end of string


code:
# 100 lists of length 10 = 100 points in 10 dimensions
from random import random
big_list = [[random() for i in range(10)] for j in range(100)]

# compute eight representative points
from sklearn.cluster import KMeans
model = KMeans(n_clusters=8)
model.fit(big_list)
centers = model.cluster_centers_
print(centers.shape)  # (8, 10)

# this is the sum of square distances of your points to the cluster centers
# you can adjust n_clusters until this is small enough for your purposes.
sum_sq_dists = model.inertia_

rawDescription: fast comparison of large amount of list of lists

description: Fast comparison of large amount of list of lists


code:
p = "^[a-z]{2}:(\w+)$"
re.match(p, "eu:road").group(1)
re.match(p, "road:eu")

rawDescription: Regex parse string in python

description: Regex parse string in python


code:
list_answer = [item.CalculateDutyCycle() * 100.0 for item in self.dictTable.values()]
newTable = np.array(list_answer)

rawDescription: Iterating through dictionary and numpy array simultaneously


code: df = pd.read_csv(file_path, header=None, usecols=[3,6])

rawDescription: Pandas read in table without headers

description: Pandas read in table without headers


code:
import struct

RESULT_FORMAT = 'd' # Double-precision float.
RESULT_SIZE = struct.calcsize(RESULT_FORMAT)
RESULT_FILE = '/tmp/results'

def worker(position, input_filename1, input_filename2):
    val = MyScript(input_filename1, input_filename2)
    with open(RESULT_FILE, 'rb+') as f:
        f.seek(RESULT_SIZE * position)
        f.write(struct.pack(RESULT_FORMAT, val))

rawDescription: Simple way to storing data from multiple processes


rawDescription: How to get value from nested dictionary in python?

description: Get value from nested dictionary in python


code:
train = train_df.get_dummies()
test = test_df.get_dummies()

# get the columns in train that are not in test
col_to_add = np.setdiff1d(train.columns, test.columns)

# add these columns to test, setting them equal to zero
for c in col_to_add:
    test[c] = 0

# select and reorder the test columns using the train columns
test = test[train.columns]

rawDescription: Possible ways to do one hot encoding in scikit-learn?