code:
import atexit

# Normal library initialization
__library = ffi.dlopen("mylibrary")
__library.initialize()

# Private library cleanup function
def __terminate():
    __library.terminate()
# register function to be called on clean interpreter termination
atexit.register(__terminate)

rawDescription: Global state in Python module

description: Global state in Python module


code:
from astropy.table import Table
tbdata = Table.read('file.fits')
ok = tbdata['z'] < 0.2  # boolean selection mask
new_tbdata = tbdata[ok]
new_tbdata.write('new_file.fits')

rawDescription: Creating FITS file from a list of table data


code:
from bs4 import BeautifulSoup

import requests
r  = requests.get("http://www.reddit.com/r/pics/")

data = r.text

soup = BeautifulSoup(data)

for link in soup.find_all('a', href=True):
    linkHref = link.get('href')
    if linkHref.startswith('http://i.imgur.com/'):
        print(linkHref)

rawDescription: Python: Parcing through buffer for sub-stirng with wild cards within


code:
with open('myfile.txt') as fin:
    lines = [line.split() for line in fin]
    lines.sort(key=lambda s: s[2:3]) # will give empty list if there is no 3rd word

rawDescription: python sort by last word in line, different length lines

description: Python sort by last word in line, different length lines


code:
def runProcess(command, parameters):
    process = Popen([command]+parameters, stdout=PIPE,stderr=PIPE)
    return process.communicate()

out,err =runProcess('python',['manage.py','test','coffeebean'])

print ("*****Own output*****")
print(out)
print ("*****Own error output*****")
print(err)

rawDescription: Popen Communicate with PIPE does not catch all output of process


code:
class PersonSkillsInline(admin.TabularInline):
    model = Person.skills.through
    min_num = 1
    extra = 2

rawDescription: Django 1.7: how to make ManyToManyField required?


code:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((200, 200),HWSURFACE|DOUBLEBUF|RESIZABLE)
fake_screen = screen.copy()
pic = pygame.surface.Surface((50, 50))
pic.fill((255, 100, 200))

while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT: pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(event.dict['size'], HWSURFACE|DOUBLEBUF|RESIZABLE)
        fake_screen.blit(pic, (100, 100))
        screen.blit(pygame.transform.scale(fake_screen, event.dict['size']), (0, 0))
        pygame.display.flip()

rawDescription: Pygame. How do I resize a surface and keep all objects within proportinate to the new window size?


code:
import os

for root, dirs, files in os.walk("Z:/"):
    for dir in dirs:
        os.chdir('Z:\\' + dir)
        os.system('git init')
        os.system('git add .')
        os.system('git commit -m \"Initial\"')

rawDescription: Traversing directories and performing command prompt commands in each with Python


code:
import numpy
import matplotlib.pyplot as plt

#------------------Get some data------------------
X = numpy.arange(100)
Y = numpy.arange(100)
Z = numpy.arange(100**2).reshape((100,100))

levels=numpy.arange(0,100**2,1000)
ltop=levels[::2]           # labels appear on top
lbot=levels[1:][::2]       # labels appear at bottom

#-----------------------Plot-----------------------
f = plt.figure()
ax = f.gca()

cf = ax.contourf(X,Y,Z,100)
cbar=plt.colorbar(cf,orientation='horizontal',ticks=lbot,drawedges=True)

vmin=cbar.norm.vmin
vmax=cbar.norm.vmax

#-------------Print bottom tick labels-------------
cbar.ax.set_xticklabels(lbot)

#--------------Print top tick labels--------------
for ii in ltop:
    cbar.ax.text((ii-vmin)/(vmax-vmin), 1.5, str(ii), transform=cbar.ax.transAxes, va='bottom', ha='center')

plt.show(block=False)

rawDescription: matplotlib colorbar alternating top bottom labels

description: Matplotlib colorbar alternating top bottom labels


code:
try:
    con = pymongo.Connection()
except pymongo.errors.ConnectionFailure:
    ...

rawDescription: How can I tell the mongodb server is up?

description: Tell the mongodb server is up


code:
#!/usr/bin/env python2

import curses
from curses import panel

class Menu(object):

    def __init__(self, items, stdscreen):
        self.window = stdscreen.subwin(0,0)
        self.window.keypad(1)
        self.panel = panel.new_panel(self.window)
        self.panel.hide()
        panel.update_panels()

        self.position = 0
        self.items = items
        self.items.append(('exit','exit'))

    def navigate(self, n):
        self.position += n
        if self.position < 0:
            self.position = 0
        elif self.position >= len(self.items):
            self.position = len(self.items)-1

    def display(self):
        self.panel.top()
        self.panel.show()
        self.window.clear()

        while True:
            self.window.refresh()
            curses.doupdate()
            for index, item in enumerate(self.items):
                if index == self.position:
                    mode = curses.A_REVERSE
                else:
                    mode = curses.A_NORMAL

                msg = '%d. %s' % (index, item[0])
                self.window.addstr(1+index, 1, msg, mode)

            key = self.window.getch()

            if key in [curses.KEY_ENTER, ord('\n')]:
                if self.position == len(self.items)-1:
                    break
                else:
                    self.items[self.position][1]()

            elif key == curses.KEY_UP:
                self.navigate(-1)

            elif key == curses.KEY_DOWN:
                self.navigate(1)

        self.window.clear()
        self.panel.hide()
        panel.update_panels()
        curses.doupdate()

class MyApp(object):

    def __init__(self, stdscreen):
        self.screen = stdscreen
        curses.curs_set(0)

        submenu_items = [
                ('beep', curses.beep),
                ('flash', curses.flash)
                ]
        submenu = Menu(submenu_items, self.screen)

        main_menu_items = [
                ('beep', curses.beep),
                ('flash', curses.flash),
                ('submenu', submenu.display)
                ]
        main_menu = Menu(main_menu_items, self.screen)
        main_menu.display()

if __name__ == '__main__':
    curses.wrapper(MyApp)

rawDescription: How to create a menu and submenus in Python curses?

description: Create a menu and submenus in Python curses


code:
from scipy.stats import beta
import numpy as np
a, b = 2.31, 0.627
x = np.linspace(beta.ppf(0.01, a, b), beta.ppf(0.99, a, b), 100)
distribution=beta.pdf(x, a, b)
def quantile(x,quantiles):
    xsorted = sorted(x)
    qvalues = [xsorted[int(q * len(xsorted))] for q in quantiles]
    return zip(quantiles,qvalues)
quantiles = quantile(distribution,[0.05,0.16,.5,.84, 0.95])

rawDescription: Getting quantiles from a beta distribution using python


code:
import multiprocessing as mp
p = mp.Pool()
p.imap
p.map_async

rawDescription: How to make Pool sensitive of KeyboardInterrupt

description: Make Pool sensitive of KeyboardInterrupt


code:
import csv

from collections import defaultdict

agencies = defaultdict(list)

with open('file.csv', 'r') as handle:
    reader = csv.reader(handle)

    for row in reader:
        agencies[row[2]].append(row[0])

rawDescription: List CSV cells with same value in R or Python?


code:
import matplotlib.pyplot as plt

# get data
with open("data.txt") as myfile:
    temps = [float(row) for row in myfile]

# generate line numbers
num_rows = len(temps)
rownums = list(range(num_rows))   # starting at 0!

# plot
plt.plot(rownums, temps)
plt.show()

rawDescription: I've printed temperature values in one column in a file but want to graph temperature by row


code:
def Generator(x, y):
    for i in xrange(x):
        for j in xrange(y):
            yield(i, j)
dis.dis(Generator)
def Generator_expr(x, y):
   return ((i, j) for i in xrange(x) for j in xrange(y))
dis.dis(Generator_expr.func_code.co_consts[1])

rawDescription: Python: generator expression vs. yield

description: Python: generator expression vs. yield


code:
uid = User.objects.get(username='Greg').id
pinyin = Pinyin.objects.get(pinyinWord='kuai')

learned, created = Learned.objects.get_or_create(pinyinWord=pinyin.pinyinWord,
                                                                 user__id=uid)
if created:   # newly INSERTed Learned  instance
     learned.date = datetime.date.today()
     learned.learned = False
     learned.save()

rawDescription: Assistance with Django model relationships


code:
import glob

mydir = "C:\Data"

file_list = glob.glob(mydir + "/*.csv") # Include slash or it will search in the wrong directory!!
print('file_list {}'.format(file_list))

rawDescription: getting file list using glob in python

description: Getting file list using glob in python


code:
def fix_duplicate_field_names(self,names):
    """Fix duplicate field names by appending an integer to repeated names."""
    used = []
    new_names = []
    for name in names:
        if name not in used:
            new_names.append(name)
        else:
            new_name = "%s_%d"%(name,used.count(name))
            new_names.append(new_name)
        used.append(name)
    return new_names

def get_output(cursor):
    """Get sql data in numpy recarray form."""
    if cursor.description is None:
        return None
    names = [i[0] for i in cursor.description]
    names = fix_duplicate_field_names(names)
    output = cursor.fetchall()
    if not output or len(output) == 0:
        return None
    else:
        return np.rec.fromrecords(output,names=names)

rawDescription: MySQLdb query containing NULLs to Numpy array


code:
def sorted_paths(filename):
    with open(filename) as f:
       gen = (matches(line) for line in f)
       s = set(match.group(1) for match in gen if match)
    return sorted(s)

rawDescription: Eliminating duplicates - shall I use a set?


code:
import gzip
import StringIO
from bottle import response, route
@route('/')
def get_data():
    response.add_header("Content-Encoding", "gzip")
    s = StringIO.StringIO()
    with gzip.GzipFile(fileobj=s, mode='w') as f:
        f.write('Hello World')
    return s.getvalue()

rawDescription: Is it possible to use gzip compression with Server-Sent Events (SSE)?


code:
import cv2
import numpy as np
img = cv2.imread("foo.jpg")
b,g,r = cv2.split(img)

rawDescription: Splitting Image using OpenCV in python

description: Splitting Image using OpenCV in python


code:
import unittest
import SomeTestModule

loader = unittest.TestLoader()
loader.loadTestsFromModule(SomeTestModule)

rawDescription: How to run all test-cases from several modules?

description: Run all test-cases from several modules


code:
from guidata.dataset.datatypes import DataSet
from guidata.dataset.dataitems import ChoiceItem, TextItem

class ChoicesVariable(object):
    def __init__(self):
        self.choices = [(0,'First',None),(1,'Second',None),(2,'Third',None)]
    def set(self, choices):
        normalized = []
        for idx, c in enumerate(choices):
            normalized.append(self._normalize_choice(idx, c))
        self.choices = normalized
    def __call__(self, *args):
        return self.choices
    def _normalize_choice(self, idx, choice_tuple):
        img = None
        if isinstance(choice_tuple, tuple):
            if len(choice_tuple) == 2:
                key, value = choice_tuple
            else:
                key, value, img = choice_tuple
        else:
            key = idx
            value = choice_tuple
        if isinstance(value, str):
            value = str(value)
        return (key, value, img)
choices = ChoicesVariable()

class Example(DataSet):
    choiceBox = ChoiceItem("Example", choices)
    otherChoiceBox = ChoiceItem("Example2", [(0,'DontTouch'),(1,'Second'),(2,'Third')])
    text = TextItem("Example3")

if __name__ == "__main__":
    import guidata
    _app = guidata.qapplication()

    newChoices = [(0,'Aaa'),(1,'Bbb'),(2,'Ccc')]
    choices.set(newChoices)
    #Example._items[0].set_prop('data', choices=newChoices)
    win = Example()
    win.edit()
    newChoices = [(0,'Alpha',None),(1,'Beta',None),(2,'Gamma',None)]
    choices.set(newChoices)
    win.edit()

rawDescription: Edit guidata Choices

description: Edit guidata Choices


code:
import threading, urllib2
import Queue

def read_url(url, queue):
    data = urllib2.urlopen(url).read()
    print('Fetched %s from %s' % (len(data), url))
    queue.put(data)

def fetch_parallel():
    result = Queue.Queue()
    threads = [threading.Thread(target=read_url, args = (url,result)) for url in urls_to_load]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    return result

def fetch_sequencial():
    result = Queue.Queue()
    for i in xrange(1, 20):
        read_url("http://www.stackoverflow.com", result)
    return result

rawDescription: python urllib2 stucks 5 seconds after 6 GET, and stuck 2 seconds after each POST

description: Python urllib2 stucks 5 seconds after 6 GET, and stuck 2 seconds after each POST


code:
LA = [300, 400, 800, 900]

NY = [829, 450, 950, 300, 500, 300]

def search(now, nxt):
    if len(nxt) < 2:
        return now
    elif not now:
        return nxt[1:]
    stick = [now[0]] + search(now[1:], nxt[1:])
    switch = search(nxt[1:], now[1:])
    return max((stick, switch), key=sum)

print(search(LA, NY))

rawDescription: Maximize the sum between two lists of integers? (with restrictions)


rawDescription: nested use of numpy.where

description: Nested use of numpy.where


code:
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(9,7))
ax1 = fig.add_subplot(111)

mylists = [[765340, 765371, 765310,'MA011',], [65310, 'MA015'],
           [765422, 765422, 24920205, 24920161, 'MA125'],
           [765422, 'MA105'],[765371, 12345, 'MA004']]

x = []
y = []
y_labels = []
y_ticks = []
for i,sub_list in enumerate(mylists):
    y_labels.append(sub_list[-1])
    y_ticks.append(i)
    for v in sub_list[:-1]:
        x.append(v)
        y.append(i)

ax1.set_yticks(y_ticks)
ax1.set_yticklabels(y_labels)
ax1.plot(x, y, "ro")
plt.show()

rawDescription: Plotting values versus strings in matplotlib?


code: parser.add_argument('-update', action='store_true', help='Update the local storage')

rawDescription: Issue calling another library function using command line argument in Python


code:
frames = []

for f in files:
      frames.append(process_your_file(f))

result = pd.concat(frames)

rawDescription: Speeding up data-import function (Pandas and appending to DataFrame)


code:
from xml.etree.ElementTree import ElementTree
tree = ElementTree()
tree.parse('in.xml')

foos = tree.findall('foo')
for foo in foos:
  bars = foo.findall('bar')
  for bar in bars:
    foo.remove(bar)

tree.write('out.xml')

rawDescription: XML: remove child node of a node

description: XML: remove child node of a node


code:
class Grass(Entity):
    def __init__(self, x, y, image_cache):
        Entity.__init__(self)
        self.image = functions.get_image("data/images/Grass.png", image_cache)
        self.image.convert()
        self.rect = Rect(x, y, 32, 32)
    def hit_test(self, x, y):
        return (self.rect.x <= x < self.rect.x+self.rect.width and
                self.rect.y <= y < self.rect.y+self.rect.height)

rawDescription: Deleting Sprites in Pygame

description: Deleting Sprites in Pygame


rawDescription: How to take a median of all the values greater than a certain number if the data is stored in a numpy array?

description: Take a median of all the values greater than a certain number if the data is stored in a numpy array


code:
import functools

def requires_mock(test):

    @functools.wraps(test)
    def wrapper():
        if mock:
            return test()
        raise SkipTest

    return wrapper

rawDescription: Nose: How to write a decorator to skip certain tests?


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

# Generate the data
data = (np.random.random((20, 2, 2, 1001)) - 0.5).cumsum(axis=-1)

# Set up the figure (the figsize is what's going to control your aspect ratio)
fig, axes = plt.subplots(nrows=20, ncols=2, sharex=True, figsize=(6, 10))
fig.subplots_adjust(wspace=0.1, hspace=0, bottom=0.05)

# Turn off tick labels everywhere
for ax in axes.flat:
    for axis in [ax.xaxis, ax.yaxis]:
        axis.set_ticklabels([])

# Plot the data
color = {(0,0):'red', (0,1):'green', (1,0):'blue', (1,1):'magenta'}
for (i,j), ax in np.ndenumerate(axes):
    for k in range(2):
        ax.plot(data[i,j,k,:], color=color[(j,k)])

# Add stacked titles (and text legends)
titles = [['TITLE:', 'Red: Data X', 'Green: Data Y'],
          ['TITLE:', 'Blue: Data W', 'Magenta: Data Z']]
for i, title in enumerate(titles):
    for text, ypos in zip(title, [35, 20, 5]):
        axes[0,i].annotate(text, xy=(0.05, 1.0), xytext=(0, ypos), va='bottom',
                           xycoords='axes fraction', textcoords='offset points')

# Add arrows on "super-Y" axes
xpos, length = -0.1, 5
axes[12,0].annotate('', xy=(xpos, 0), xytext=(xpos, length),
        xycoords='axes fraction', textcoords='axes fraction',
        arrowprops=dict(arrowstyle='<|-'))
axes[12,0].annotate('{0} subplots'.format(length), xy=(xpos, length/2.0),
        xycoords='axes fraction', rotation=90, va='center', ha='right')

# Add arrows on "super-X" axes
ypos, length = -0.7, 1000
axes[-1,0].annotate('', xy=(0, ypos), xytext=(length, ypos),
        xycoords=('data', 'axes fraction'), textcoords=('data', 'axes fraction'),
        arrowprops=dict(arrowstyle='<|-'))
axes[-1,0].annotate('{0} data units'.format(length), xy=(length/2.0, ypos),
        xytext=(0, 5), xycoords=('data', 'axes fraction'),
        textcoords='offset points', ha='center', va='bottom')

plt.show()

rawDescription: Help with making a big subplot look nicer and clearer


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

"""corrected version with more PEP8 included."""

import re
import sys  # just for exit the script. There are multiple other ways.

# the assignments will be done later, no need for that here.
# alt = ""
# temp = ""

# readable names are better than cryptic ones
def get_altitude():
    alt = str(input("Enter altitude above sealevel, format 100M/F: "))

    # after `return` code will not be executed. You have to do it before the
    # return statement as mentioned by jojonas. Maybe you will also allow a
    # minus at the beginning and disallow no numbers (+ instead of *)?
    if not re.match(r'[0-9]*[mMfF]$', alt):
        raise ValueError

    return alt

# readable names are better than cryptic ones
def get_temperature():
    temp = str(input("Tempurature in format 70C/F: "))

    # the same here with the return statement
    if not re.match(r'[0-9]*[cCfF]$', temp):
        raise ValueError

    return temp

# The while loop stands for: do it forever. Maybe this is not what you want?!
# The user has to give a wrong input format (then sys.exit is your friend as
# one example of stopping the script or the user has to manually stop the
# script (STRG+C) or something like that. There are better ways.
while True:
    try:
        # you need to assign the returned values to a variable as mentioned
        # by jojonas already. Here is the way of doing it.
        alt = get_altitude()
        temp = get_temperature()

    # slight change in catching the error
    except ValueError:
        print('Invalid input format!')
        sys.exit(1)

    # finally will be done after exception occured! If you don't use
    # sys.exit (as I did as a fast hack not to totally disorder your
    # program), you have to be careful about this solution.
    finally:
        t = ''.join(x for x in temp if x.isdigit())
        a = ''.join(x for x in alt if x.isdigit())

        t = int(t)
        a = int(a)

        if "F" in temp:
            # just another way of expressing the same:
            t -= 32 / 1.8

        if "F" in alt:
            # just another way of expressing the same:
            a /= 3.3

        tPoint = 100 - a * 0.00552

        # just another way of expressing the same:
        if 0 - (int(tPoint)) < a < (100 - (int(tPoint))):
            print("Liquid")

        if a < (0 - int(tPoint)):
            print("Solid")

        if a > (100 - int(tPoint)):
            print("Gas")

rawDescription: Return & Call Variables Outside Functions in Python... What's Wrong here?


code:
im = plt.imshow(np.flipud(plt.imread('tas.png')),
                origin='lower',
                extent=[35, 75, 0, 16])

rawDescription: matplotlib python change axis

description: Matplotlib python change axis


code:
from Tkinter import Tk, Label, Entry, StringVar

app = Tk()

labelText=StringVar()
labelText.set("Enter directory of log files")
labelDir=Label(app, textvariable=labelText, height=4)
labelDir.pack(side="left")

directory=StringVar(None)
dirname=Entry(app,textvariable=directory,width=50)
dirname.pack(side="left")

app.mainloop()

rawDescription: Pack labels right next to entry box in tkinter python


rawDescription: How do I write a multivariate objective function for use with scipy.optimize.minimize() so that it can also be plotted with matplotlib?

description: Write a multivariate objective function for use with scipy.optimize.minimize() so that it can also be plotted with matplotlib


code:
from Tkinter import *

root = Tk()
canvas = Canvas(root, width=200, height=200)
canvas.create_rectangle(10, 10, 60, 60)
canvas.create_rectangle(70, 70, 120, 120)
canvas.pack()
canvas.move(ALL, 50, 50)
root.mainloop()

rawDescription: moving multiple objects on a Tkinter canvas simultaneously

description: Moving multiple objects on a Tkinter canvas simultaneously


code: people[:] = [p for p in people if p[0] != '' and p[1] != '']

rawDescription: Python removing items from list

description: Python removing items from list


rawDescription: Indexing array in python results in lost scientific notation


code:
# Required input defintions are as follows;
# time:   Time between samples
# band:   The bandwidth around the centerline freqency that you wish to filter
# freq:   The centerline frequency to be filtered
# ripple: The maximum passband ripple that is allowed in db
# order:  The filter order.  For FIR notch filters this is best set to 2 or 3,
#         IIR filters are best suited for high values of order.  This algorithm
#         is hard coded to FIR filters
# filter_type: 'butter', 'bessel', 'cheby1', 'cheby2', 'ellip'
# data:         the data to be filtered
def Implement_Notch_Filter(time, band, freq, ripple, order, filter_type, data):
    from scipy.signal import iirfilter
    fs   = 1/time
    nyq  = fs/2.0
    low  = freq - band/2.0
    high = freq + band/2.0
    low  = low/nyq
    high = high/nyq
    b, a = iirfilter(order, [low, high], rp=ripple, btype='bandstop',
                     analog=False, ftype=filter_type)
    filtered_data = lfilter(b, a, data)
    return filtered_data

rawDescription: Designing an FIR notch filter with python


code:
t = ['a', 'b', 'c']
s = ['b', 'd', 'e']
u = set(t)
v = set(s)
u
v
u | v
u.union(v)
u.union(s)

rawDescription: Set union, List Comprehensions

description: Set union, List Comprehensions


code:
MyMIDI = MIDIFile(1)
track = 0
channel = 0
pitch = 60
time = 0
duration = 1
volume = 100
MyMIDI.addNote(track,channel,pitch,time,duration,volume)

rawDescription: Simple, Cross Platform MIDI Library for Python


code:
pd.to_numeric(df['col 1'].str.extract('(\d{4})'))
pd.to_numeric(df['col2'].str.extract('-(\d{4})')) - pd.to_numeric(df['col 1'].str.extract('(\d{4})'))

rawDescription: Year range to date time format

description: Year range to date time format


code:
NAME_LIST = 4

first_name = ""
last_name  = ""

for nameCount in range(NAME_LIST):
    name = raw_input('Please enter a name: ').title()
    first_name = first_name or name
    first_name = min(first_name, name)
    last_name  = max(last_name, name)

print("First: %s" % first_name)
print("Last: %s" % last_name)

rawDescription: Using a loop to compare strings in Python


code:
from sqlalchemy import create_engine, text
engine = create_engine('postgresql://user:password@localhost/somedb')
q1 = "SELECT name FROM table_a intersect SELECT name FROM table_b"
q1res = engine.execute(text(q1)).fetchall()
# or
q2res = engine.execute(text(q1)).fetchone()

rawDescription: How to intersect two raw SQL queries using SQLAlchemy?

description: Intersect two raw SQL queries using SQLAlchemy


code:
import numpy as np
import pyqtgraph as pg
from PySide import QtGui, QtCore

win = pg.GraphicsWindow(title="Basic plotting examples")
win.resize(1000,600)
win.setWindowTitle('pyqtgraph example: Plotting')

# Enable antialiasing for prettier plots
pg.setConfigOptions(antialias=True)

p1 = win.addPlot(title="Downsampled")
# normally would plot 1000, but we downsample by 10 fold
p1.plot(np.random.normal(size=1000), pen=(255,0,0), name="Red curve", downsample=10)

p2 = win.addPlot(title="Normal")
p2.plot(np.random.normal(size=1000), pen=(0,0,255), name="Blue curve",)

## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    QtGui.QApplication.instance().exec_()

rawDescription: Best practice for plotting multiple streams of data on different graphs in Python & pyqtgraph


rawDescription: how to sort tuple value from list in python

description: Sort tuple value from list in python


code:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([0,1,2,3,4,5,6])
y = np.array([0,2,0,4.5,0.5,2,3])

line = plt.plot(x,y,'o')[0]
line.set_clip_on(False)
plt.show()

rawDescription: plotting markers on top of axes

description: Plotting markers on top of axes


code: df.groupby(level=0).filter(lambda x: all([c > 1 for v in x['c']]))

rawDescription: Pandas multiindex boolean indexing

description: Pandas multiindex boolean indexing


code:
p=0
s=[]
for item in lst:
    if len(item) > p:
        s=[item]
        p=len(item)
    elif len(item) == p:
        s.append(item)
print(s)

rawDescription: Python - printing multiple shortest and longest words from a list


code:
import os
from xml.dom import minidom

doc = minidom.parse("jobs.xml")

job = doc.getElementsByTagName("job")[0]
id = job.getElementsByTagName("id")[0]
name = job.getElementsByTagName("name")[0]

id_data = id.firstChild.data
name_data = name.firstChild.data

url = 'http://localhost:19888/ws/v1/history/mapreduce/jobs/{name}'.format(name=name_data)
cmd = 'curl --compressed -H "Accept: application/xml" -X GET "{url}"'.format(url=url)

os.system(cmd)

rawDescription: how to assign variable value in python in terminal commands?

description: Assign variable value in python in terminal commands


code:
now = datetime.datetime.now()
now_plus_10 = now + datetime.timedelta(minutes = 10)

rawDescription: python - how to find datetime 10 mins after current time?

description: Python - how to find datetime 10 mins after current time


code:
from django.conf import settings

settings.MEDIA_URL

rawDescription: MEDIA_ROOT django read and delete

description: MEDIA_ROOT django read and delete


code:
from collections import defaultdict
n_occurence = defaultdict(lambda:0)
for line in text_file:
    for item in list1:
        if item in line and str in line:
            n_occurence[item] +=1

rawDescription: Calculate the co occurrence in file text


code:
import re

new_num = 456
new_data = str(new_num) + '\n' + 'Georph\n'
written = False

with open('line_search.txt','r') as f:
    data = f.readlines()
updated_data = []
for i, line in enumerate(data):
    if re.match("\d+", line):
        if new_num <= int(line):
            updated_data = data[:i] + [new_data] + data[i:]
            break
with open('line_search.txt', 'w') as f:
    f.writelines(updated_data)

rawDescription: Writing to the previous line of a txt file in Python 3.3


code:
import scipy # numpy could work too
from functools import wraps
def asarray_strictnumeric( obj ):
    ''' only convert if the result is a numerical array. '''
    tmp=scipy.asarray(obj)
    if tmp.dtype.kind in 'iufc':
        return tmp
    else:
        return obj

def array_args(f):
    ''' Decorator:
        - converts numerical positional arguments to arrays,
        - leaves non-numerical positional arguments alone,
        - leaves all keywords alone.
    '''
    @wraps(f)
    def wrapper(*args, **kwds):
        args=[asarray_strictnumeric(x) for x in args]
        return f( *args, **kwds )
    return wrapper

rawDescription: Standardized numpy/scipy `asarray` decorator


code:
part_of_id_to_find = "slot"
elements = driver.find_elements_by_css_selector('[id*="%s"]' % part_of_id_to_find)

rawDescription: Finding all elements with an ID using Selenium


code:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
import matplotlib.cm as cmx

#make the dataframe
a = np.random.rand(100)
b = np.random.ranf(100)
df = pd.DataFrame({'a': a, 'b': b})

# do the colour mapping
c_norm  = colors.Normalize(vmin=min(df.b), vmax=max(df.b))
scalar_map = cmx.ScalarMappable(norm=c_norm, cmap=plt.get_cmap('jet'))
color_vals = [scalar_map.to_rgba(val) for val in df.b]

# make the plot
plt.vlines(df.index, np.zeros_like(df.a), df.a, colors=color_vals)

rawDescription: Plot a pandas dataframe with vertical lines


code: items = [item for item in container if item.attribute == value]

rawDescription: Get list item by attribute in Python

description: Get list item by attribute in Python


code:
def find_page(url, name, find, offset):
    movie_name, seperator, tail = name_of_movie.partition(' (')
    page = urllib.urlopen(url.format(name)).read()
    start_link = page.find(find)
    start_url = page.find('"',start_link+offset)
    end_url = page.find('" ',start_url+1)
    return page[start_url+1:end_url]

def movie_poster_url(name_of_movie):
    return find_page("another website name{} continuation of website name", name_of_movie, '"Poster":', 9)

def movie_trailer_url(name_of_movie):
    trailer_url = find_page("another website name{} trailer", name_of_movie, '

<a aria-hidden="true" href=', 110)
    return "www.youtube.com" + trailer_url

rawDescription: Same code used in multiple functions but with minor differences - how to optimize?


code:
#!/usr/bin/env python2
import subprocess

f = open("/tmp/counter.log", "a+")
p = subprocess.Popen("/tmp/counter.py", stdout=f, stderr=f, env={
    "PYTHONUNBUFFERED": "Yes please"
})

rawDescription: Redirecting stdout/stderr of a child process to a file


rawDescription: Groupby in python

description: Groupby in python


rawDescription: DatetimeIndex for daily data only in pandas


code:
t = template.Template(my_model.description)
my_string = t.render(template.Context(template_dict))

rawDescription: Using template.render() without a file reference


code:
vsdatas = {}
for pitem in range(len(plist)):
    vsdata = []
    for ritem in range(pitem, len(rlist)):
        if pitem == ritem:
            print("skipped")
        else:
            item1 = plist[pitem]
            item2 = rlist[ritem]
            vsdata.append([str(item1),str(item2)])
            print(item1 + " and " + item2)
    vsdatas[plist[pitem]] = vsdata

rawDescription: Use iterated list element to name variable in loop


code: groupId = soup.project.find('groupid', recursive=False).text

rawDescription: Finding a nonrecursive DOM subnode in Python using BeautifulSoup


code: stdin, stdout, stderr = ssh.exec_command("sudo -i command_1 & sudo -i command_2")

rawDescription: How to run multi-commands in root using python (paramiko)

description: Run multi-commands in root using python (paramiko)


code:
def run(cmd, logfile):
    p = subprocess.Popen(cmd, shell=True, universal_newlines=True, stdout=logfile)
    ret_code = p.wait()
    logfile.flush()
    return ret_code

rawDescription: Saving stdout from subprocess.Popen to file, plus writing more stuff to the file


code:
import collections
import itertools

d = collections.defaultdict(list)
for indices in itertools.product(*map(range, a.shape)):
    d[a[indices]].append(indices)

rawDescription: Python: How to index the elements of a numpy array?


code:
import wx, win32api, win32gui, win32con, ctypes

class App(wx.App):
    def OnInit(self):
        dll = ctypes.WinDLL('gdi32.dll')
        for idx, (hMon, hDC, (left, top, right, bottom)) in enumerate(win32api.EnumDisplayMonitors(None, None)):
            hDeskDC = win32gui.CreateDC(win32api.GetMonitorInfo(hMon)['Device'], None, None)
            bitmap = wx.EmptyBitmap(right - left, bottom - top)
            hMemDC = wx.MemoryDC()
            hMemDC.SelectObject(bitmap)
            try:
                dll.BitBlt(hMemDC.GetHDC(), 0, 0, right - left, bottom - top, int(hDeskDC), 0, 0, win32con.SRCCOPY)
            finally:
                hMemDC.SelectObject(wx.NullBitmap)
            bitmap.SaveFile('screenshot_%02d.bmp' % idx, wx.BITMAP_TYPE_BMP)
            win32gui.ReleaseDC(win32gui.GetDesktopWindow(), hDeskDC)
        return False

App(0)

rawDescription: Python screenshot 2+ monitors (windows)

description: Python screenshot 2+ monitors (windows)


code: '-'.join(str(x) for x in matchkey)

rawDescription: Stringify a tuple in python with dashes

description: Stringify a tuple in python with dashes


code:
class ImgPanel(wx.Panel):
    def __init__(self, parent, image):
        wx.Panel.__init__(self, parent)

        img = wx.Image(image, wx.BITMAP_TYPE_ANY)
        self.sBmp = wx.StaticBitmap(self, wx.ID_ANY, wx.BitmapFromImage(img))

        sizer = wx.BoxSizer()
        sizer.Add(item=self.sBmp, proportion=0, flag=wx.ALL, border=10)
        self.SetBackgroundColour('green')
        self.SetSizerAndFit(sizer)

rawDescription: wxPython: centering an image in a panel

description: WxPython: centering an image in a panel


code:
class Foo(object):
    classVar = []
    def __init__(self):
        self.instVar = []
f = Foo()
g = Foo()
f.classVar
f.instVar
g.classVar
g.instVar
f.instVar.append(1)
f.instVar
g.instVar
f.classVar.append(1)
f.classVar
g.classVar

rawDescription: python - best practise for using variables in class and functions

description: Python - best practise for using variables in class and functions


code:
from collections import Iterable
def flat(lst):
    for parent in lst:
        if not isinstance(parent, Iterable):
            yield parent
        else:
            for child in flat(parent):
                yield child
list(flat(t))

rawDescription: Python: how to paste a list into another list


code:
class HomepageView(TemplateView):
    def get_context_data(self, **kwargs):
        """
        Returns a different context depending
        on whether the user is logged in or not
        """
        context = super(HomepageView, self).get_context_data(**kwargs)
        if self.request.user.is_authenticated():
            context['user_type'] = 'logged in'
        else:
            context['user_type'] = 'guest'
        return context

    def get_template_names(self):
        """
        Returns a different template depending
        on whether the user is logged in or not
        """
        if self.request.user.is_authenticated():
            return 'logged_in_homepage.html'
        else:
            return 'guest_homepage.html'

rawDescription: Django 1.8 (Python 3.4): Show different templates based on user authorization with Class-Based Views


code:
def compute_probabilities_faster(img, kernels):
  means, covs, weights = map(np.dstack, zip(*kernels))
  pixels_as_rows = img.reshape((-1, 3, 1))
  responses = np.exp(-0.5 * ((pixels_as_rows - means) ** 2 / covs).sum(axis=1))
  factors = 1. / np.sqrt(covs.prod(axis=1) * ((2 * np.pi) ** 3))
  return np.sum(responses * factors * weights, axis=2).reshape(img.shape[:2])

rawDescription: Efficient density function computation

description: Efficient density function computation


code:
import pygame

pygame.init()

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

surface1 = pygame.Surface((100,100))
surface1.set_colorkey((0,0,0))
surface1.set_alpha(128)
pygame.draw.circle(surface1, (0,255,0), (50,50), 50)

surface2 = pygame.Surface((100,100))
surface2.set_colorkey((0,0,0))
surface2.set_alpha(128)
pygame.draw.circle(surface2, (255,0,0), (50,50), 50)

screen.blit(surface1, (100,100))
screen.blit(surface2, (120,120))

pygame.display.update()

RUNNING = True

while RUNNING:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            RUNNING = False

pygame.quit()

rawDescription: Pygame: Set alpha level for shapes

description: Pygame: Set alpha level for shapes


code:
models = session.query(
    DevicesGps.ReceivedDateUtc.label("gps_telemetry_ReceivedDateUtc"),
    DevicesGps.ReceivedTimeUtc.label("gps_telemetry_ReceivedTimeUtc"),
    DevicesGps.Latitude.label("gps_telemetry_Latitude"),
    DevicesGps.Longitude.label("gps_telemetry_Longitude")
)

rawDescription: sqlalchemy query: result column names

description: Sqlalchemy query: result column names


code:
import cv2, numpy as np

meas=[]
pred=[]
frame = np.zeros((400,400,3), np.uint8) # drawing canvas
mp = np.array((2,1), np.float32) # measurement
tp = np.zeros((2,1), np.float32) # tracked / prediction

def onmouse(k,x,y,s,p):
    global mp,meas
    mp = np.array([[np.float32(x)],[np.float32(y)]])
    meas.append((x,y))

def paint():
    global frame,meas,pred
    for i in range(len(meas)-1): cv2.line(frame,meas[i],meas[i+1],(0,100,0))
    for i in range(len(pred)-1): cv2.line(frame,pred[i],pred[i+1],(0,0,200))

def reset():
    global meas,pred,frame
    meas=[]
    pred=[]
    frame = np.zeros((400,400,3), np.uint8)

cv2.namedWindow("kalman")
cv2.setMouseCallback("kalman",onmouse);
kalman = cv2.KalmanFilter(4,2)
kalman.measurementMatrix = np.array([[1,0,0,0],[0,1,0,0]],np.float32)
kalman.transitionMatrix = np.array([[1,0,1,0],[0,1,0,1],[0,0,1,0],[0,0,0,1]],np.float32)
kalman.processNoiseCov = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]],np.float32) * 0.03
#kalman.measurementNoiseCov = np.array([[1,0],[0,1]],np.float32) * 0.00003
while True:
    kalman.correct(mp)
    tp = kalman.predict()
    pred.append((int(tp[0]),int(tp[1])))
    paint()
    cv2.imshow("kalman",frame)
    k = cv2.waitKey(30) &0xFF
    if k == 27: break
    if k == 32: reset()

rawDescription: Is there any example of cv2.KalmanFilter implementation?


code:
replace_with = """
set filelid [open "C:/Sanity_Automation/Work_Project/Output/smokeTestResult" w+]
puts $filelid
close $filelid
"""
search = "AgtQtl::CloseAllOutputFiles"

fd1 = open('so.tcl')
fd2 = open('so1.tcl', 'w')

for line in fd1.readlines():
    if line.find(search) > -1:
        fd2.write(replace_with)
    else:
        fd2.write(line)

fd1.close()
fd2.close()

rawDescription: replace particular line in text file using python?

description: Replace particular line in text file using python


code:
from tkinter import *

master = Tk()

# some dummy callback functions
callback, callback2, callback3, callback4, callbackinput = [lambda: None]*5

#creates entry inputs for answers
entry=Entry(master)
entry.grid(row=0, column=0, columnspan=6)
entry.focus_set()

#button 1 created and used to call addition function
b1 = Button(master, text="+", command=callback)
b1.grid(row=1, column=0)

#button 2 created and used to call subtraction function
b2 = Button(master, text="-", command=callback2)
b2.grid(row=1, column=1)

#button 3 created and used to call divison function
b3 = Button(master, text="/", command=callback3)
b3.grid(row=1, column=2)

#button 4 created and used to call multiplication function
b4 = Button(master, text="*", command=callback4)
b4.grid(row=1, column=3)

#button 5 created and used to check answers
b5 = Button(master, text="Check Ans", width=10, command=callbackinput)
b5.grid(row=1, column=4, columnspan=2)

rawDescription: How does Pythons .grid() function work

description: How does Pythons .grid() function work


code: my_list = [col for row in matrix for col in row]

rawDescription: Trying to converting a matrix 1*3 into a list


code:
timeit.timeit('for i in repeat(None, 1000): pass', setup='from itertools import repeat', number=100000)
timeit.timeit('for i in xrange(1000): pass', number=100000)
timeit.timeit('for i in range(1000): pass', number=100000)
timeit.timeit('for i in r: pass', setup='r = [None] * 1000', number=100000)
timeit.timeit('for i in r: pass', setup='r = range(1000)', number=100000)
timeit.timeit('for i in r: pass', setup='r = xrange(1000)', number=100000)

rawDescription: Should one use xrange(iterations) or a list of len(iterations) for better performance in a "for loop" evoked 1000000 times?


code:
tea = 100
count = 0
while tea >= 70:
    print(str(tea) + " C")
    tea -= 10   # shorthand for tea = tea-10
    count += 1
print("It's ready now")
print("It took {} blows to cool down".format(count))

rawDescription: Count how many times while loop was used


code:
def read_contents(file_path):
  with open(file_path, 'r') as f:
    return f.read()

rawDescription: Does filehandle get closed automatically in Python after it goes out of scope?


code:
user_input = "Frankreich"
country_code = ''.join([country.alpha2 for country in pycountry.countries if _(country.name) == user_input]) # u'FR'

rawDescription: convert translated country-names to alpha2 with pycountry and gettext

description: Convert translated country-names to alpha2 with pycountry and gettext


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

N = 128
x = np.arange(-5,5,10./(2*N))
y = np.exp(-x*x)
y_fft = np.fft.fftshift(np.abs(np.fft.fft(y)))/ np.sqrt(2 * N)
plt.plot(x,y)
plt.plot(x,y_fft)
plt.show()

rawDescription: Fourier transform of a Gaussian is not a Gaussian, but thats wrong! - Python


code:
#### f1.py
import f2

def calc1(a, b, c):
     a = a+b
     c = a*c
     d = f2.calc2(a, b, c)
     # This checks whether data has been sent by the second argument,
     # in which case d will not have its default value
     if d:
         # This should print the results from f2, so 'b' should retain
         # its value from calc1.
         print(b, d)

#### f2.py
def calc2(a, b, c):
    return a + c

rawDescription: Python - Passing arguments back and forth between functions


code:
import Tkinter as tk

def choose_font():
    global m, text # I hate to use global, but for simplicity

    t = tk.Toplevel(m)
    font_name = tk.Label(t, text='Font Name: ')
    font_name.grid(row=0, column=0, sticky='nsew')
    enter_font = tk.Entry(t)
    enter_font.grid(row=0, column=1, sticky='nsew')
    font_size = tk.Label(t, text='Font Size: ')
    font_size.grid(row=1, column=0, sticky='nsew')
    enter_size = tk.Entry(t)
    enter_size.grid(row=1, column=1, sticky='nsew')

    # associating a lambda with the call to text.config()
    # to change the font of text (a Text widget reference)
    ok_btn = tk.Button(t, text='Apply Changes',
                       command=lambda: text.config(font=(enter_font.get(),
                       enter_size.get())))
    ok_btn.grid(row=2, column=1, sticky='nsew')

    # just to make strechable widgets
    # you don't strictly need this
    for i in range(2):
        t.grid_rowconfigure(i, weight=1)
        t.grid_columnconfigure(i, weight=1)
    t.grid_rowconfigure(2, weight=1)

m = tk.Tk()
text = tk.Text(m)
text.pack(expand=1, fill='both')
chooser = tk.Button(m, text='Choose Font', command=choose_font)
chooser.pack(side='bottom')

tk.mainloop()

rawDescription: Cannot dynamically change font in python Tkinter text editor


code:
def CC(Map):
    label_img, cc_num = ndimage.label(Map)
    CC = ndimage.find_objects(label_img)
    cc_areas = ndimage.sum(Map, label_img, range(cc_num+1))
    area_mask = (cc_areas < 1500)
    label_img[area_mask[label_img]] = 0
return label_img, CC

rawDescription: How to remove some connected components in python?

description: Remove some connected components in python


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

frac_val = 0.1
for x in np.arange(0.1, 1, 0.2):

    arrow_props = dict(fc='k', ec='k', frac=frac_val, headwidth=10, width=2,
                       shrink=0.1)

    text = '%d%%' % (frac_val * 100)

    plt.annotate(text, xy=(x, 0.9), xytext=(x, 0.2), ha='center',
                 arrowprops=arrow_props)

    frac_val += 0.1

plt.show()

rawDescription: How to make arrow headlength longer in matplotlib?

description: Make arrow headlength longer in matplotlib


code:
def processMaze (mazeArray):
    maze = []
    for mazeRow in mazeArray:
        tempMazeRow = []
        for mazeColumn in mazeRow:
            if mazeColumn == (255, 255, 255):
                tempMazeRow.append('#')
            elif mazeColumn == (0, 0, 0):
                tempMazeRow.append(" ")
        maze.append(tempMazeRow)
    return maze

rawDescription: How to convert bitmap to ASCII

description: Convert bitmap to ASCII


code:
class ArticleResource(ModelResource):

    class Meta:
        queryset = Article.objects.all()
        resource_name = 'article'
        filtering = {'title': ALL}
        authorization=Authorization()

    # save the photo
        def deserialize(self, request, data, format=None):
            if not format:
                format = request.META.get('CONTENT_TYPE', 'application/json')

            if format.startswith('multipart'):
                data = request.POST.copy()
                photo = Article()
                photo.thumbnail = request.FILES['thumbnail']
                photo.title = request.POST.get('title')
                # ... etc
                return data
            return super(ArticleResource, self).deserialize(request, data, format)

        # overriding the save method to prevent the object getting saved twice
        def obj_create(self, bundle, request=None, **kwargs):
            pass

rawDescription: Trying to upload image to a FileField model using REST framework or Tastypie


code:
from gi.repository import Gtk, Gio
from gi.repository import WebKit

HEIGHT = 500
WIDTH = 800

class MainWindow(Gtk.Window):

    def __init__(self):

        Gtk.Window.__init__(self, title="Resolution")
        self.set_border_width(0)
        self.set_default_size(WIDTH, HEIGHT)

        hb = Gtk.HeaderBar()
        hb.props.show_close_button = True
        hb.props.title = "Resolution"
        hb.props.subtitle = "Digital Maths Revision Guide"
        self.set_titlebar(hb)

        button = Gtk.Button()
        icon = Gio.ThemedIcon(name="emblem-system-symbolic")
        image = Gtk.Image.new_from_gicon(icon, 1)
        button.add(image)
        button.connect("clicked", self.sidebarShowHide)
        button.set_focus_on_click(False)
        hb.pack_start(button)

        self.sidebarbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
        toplevelbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)

        self.add(toplevelbox)

        toplevelbox.pack_start(self.sidebarbox, False, False, 0)

        self.searchentry = Gtk.SearchEntry()
        self.searchentry.connect("search-changed", self.search_changed)
        self.sidebarbox.pack_start(self.searchentry, False, False, 0)

        label = Gtk.Label("Contents Selector")
        self.sidebarbox.pack_start(label, True, True, 0)

        scroller = Gtk.ScrolledWindow()
        content = WebKit.WebView()
        scroller.add(content)
        toplevelbox.pack_start(scroller, True, True, 0)

        content.open("/home/oliver/resolution/placeholder.html")

    def inital_show(self):
        win.show_all()
        self.sidebarbox.hide();

    #This works. The sidebar does show/hide.
    def sidebarShowHide(self, button):
        if self.sidebarbox.get_visible():
            self.sidebarbox.hide()
        else:
            self.sidebarbox.show()

    def search_changed(self, searchentry):
        pass

if __name__ == '__main__':
    win = MainWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.inital_show()
    Gtk.main()

rawDescription: Python Gtk3 Box doesn't hide

description: Python Gtk3 Box doesn't hide


code:
s = Sound()
s.read('sound.wav')
s.play()

rawDescription: Play a Sound with Python

description: Play a Sound with Python


code:
numbers = ['1','2','3','4','5']
length_numbers = len(numbers)

for i in range(0, length_numbers):
    print(i)
    if i == length_numbers - 1: # change to minus here
        print("yep list is finished and execute code below")
        # .... <-- code will be placed here

rawDescription: Run code after iteration is done

description: Run code after iteration is done


code:
@timed(2.1)
def test():
    func_with_timeout(timeout=2)

rawDescription: How to test that a Python function takes less than a certain time to complete

description: Test that a Python function takes less than a certain time to complete


code:
class PostManager(models.Manager):

    def get_queryset(self):
        return super(PostManager, self).get_queryset().filter(is_active=True)

rawDescription: custom model manager not working properly

description: Custom model manager not working properly


code:
username = "neelkamath@gmail.com"
usernamelist = []
while len(username) > 0:
    for part in accumulate(username):
        usernamelist.append(part)
    username = username[1:]
print(usernamelist)

rawDescription: Python: Why does my "variable += 1" not work as expected?


rawDescription: How to extract an element (href) with selenium and save to a variable

description: Extract an element (href) with selenium and save to a variable


code:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro') # Your original list
plt.plot(5, 25, 'go')                 # Additional point
plt.plot(6, 36, 'yo')                 # Additional point
plt.axis([0, 10, 0, 40])              # Modified axis
plt.show()

rawDescription: Insert a dot at a certain point on a line with matplotlib


code:
def application(environ, start_response):
    status = '200 OK'
    output = 'Hello World!'

    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]

rawDescription: python for the web

description: Python for the web


code:
def findDupes(conn): #pass in your database connection object here
    file_curs = conn.cursor()
    file_curs.execute('select files from myTable order by files')
    while True:
        row = file_curs.fetchone()
        if row == None:
            break
        dup_curs = conn.cursor()
        dup_curs.execute('select files from myTable where files like ?',(row[0]+'%',))
        dupe = dup_curs.fetchone()
        print (dupe[0])

rawDescription: Why is a second SQL statement breaking my loop?


code:
def power_of_two(target):
    if target > 1:
        for i in range(1, int(target)):
            if (2 ** i >= target):
                return 2 ** i
    else:
        return 1

rawDescription: Python: Closest Power of Two To Target

description: Python: Closest Power of Two To Target


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

def forceAspect(ax,aspect=1):
    im = ax.get_images()
    extent =  im[0].get_extent()
    ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)

a=np.random.randn(8,4)
fig = plt.figure(1, figsize=(5,4))
plt.matshow(a,fignum=1)
ax=plt.gca()
forceAspect(ax,aspect=1)
plt.xticks(np.arange(0, 4, 1), np.arange(1, 5, 1))
plt.yticks(np.arange(0, 8, 1), np.arange(1, 9, 1))
cbar = plt.colorbar()
plt.draw()
pos_cbar = cbar.ax.get_position()
pos_ax = ax.get_position()
pos_cbar.y0 = pos_ax.y0
pos_cbar.y1 = pos_ax.y1
cbar.ax.set_position(pos_cbar)

plt.show()

rawDescription: Extra space around a matshow/imshow plot after scaling


code:
class AB(object):
    __slots__ = ('a', 'b')

rawDescription: Is there a dataset in python similar to structs in C++?


code:
import numpy as np

N = 4601
data = np.arange(N*58).reshape(-1, 58)
np.random.shuffle(data)

a = data[:int(N*0.6)]
b = data[int(N*0.6):int(N*0.8)]
c = data[int(N*0.8):]

rawDescription: Numpy: How to randomly split/select an matrix into n-different matrices


code:
result = ""
for char in string:
    if not (char.isalpha() and char in result):
        result += char

rawDescription: Removing only alpha duplicates

description: Removing only alpha duplicates


code:
widgets = {}
for daynum in range(31):
    widgets[daynum] = Button(text=str(day), width = 2)
...
widgets[daynum].grid_forget()

rawDescription: dictionary in python tkinter not hiding button in grid even with grid_forget()

description: Dictionary in python tkinter not hiding button in grid even with grid_forget()


code:
def find_plugins(directory):
    for dirname, _, filenames in os.walk(directory): # recursively search 'directory'
        for filename in filenames:
            # Look for files that end in '.py'
            if (filename.endswith(".py")):
                # Assume the filename is a python module, and attempt to find and load it
                ###  need to chop off the ".py" to get the module_name
                module_name = filename[:-3]
                # Attempt to find and load the module
                try:
                    module_info = imp.find_module(module_name, [dirname])
                    module = imp.load_module(module_name, *module_info)
                    # The module loaded successfully, now look through all
                    # the declarations for an item whose name that matches the module name
                    ##  First, define a predicate to filter for classes from the module
                    ##  that subclass PluginInterface
                    predicate = lambda obj: inspect.isclass(obj) and \
                                            obj.__module__ == module_name and \
                                            issubclass(obj, PluginInterface)
                    for _, declaration in inspect.getmembers(module, predicate):
                        # Each 'declaration' is a class defined in the module that inherits
                        # from 'PluginInterface'; you can instantiate an object of that class
                        # and return it, print the name of the class, etc.
                        # TODO:  fill this in
                        pass
                except:
                    # If anything goes wrong loading the module, skip it quietly
                    pass

rawDescription: Scan a directory to load Python plugin from C++


code:
from distutils.core import setup
import py2exe

setup (name = "script2compile",
       console=['script2compile.pyw'],
       version = "1.4",
       author = "me",
       author_email="somemail@me.com",
       url="myurl.com",
       windows = [{
                    "script":"script2compile.pyw",
                    "icon_resources":[(1,"./ICONS/app.ico")]  # Icon file to use for display
                 }],
       # put packages/libraries to include in the "packages" list
       options = {"py2exe":{"packages": [   "pickle",
                                            "csv",
                                            "Tkconstants",
                                            "Tkinter",
                                            "tkFileDialog",
                                            "pyexpat",
                                            "xml.dom.minidom",
                                            "win32pdh",
                                            "win32pdhutil",
                                            "win32api",
                                            "win32con",
                                            "subprocess",
                                        ]}}

       )

import win32pdh
import win32pdhutil
import win32api

rawDescription: Create plugins for python standalone executables


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

driver = webdriver.Firefox()
driver.get("http://www.python.org")

searchbox = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located(
        (By.XPATH, "//input[@placeholder='Search']")
    )
)

rawDescription: Type in Instagram's Search Bar using Selenium


code:
def after_semi(input):
    for line in input:
        yield line.split(';')[0]

with open('output', 'w') as f:
    for line in after_semi(input):
        f.write('%s\n', line)

rawDescription: Python: how to go to the next line if you encounter a character within a line


code:
from timeit import timeit
n = 12345678
timeit("n % 10 == 8", "from __main__ import n")
timeit("str(n)[-1] == '8'", "from __main__ import n")

rawDescription: Most efficient way to look for the last digit of a number?


code:
import re
mo = re.search ("a", "a")
mo_class = type(mo)
mo_class
class SubClass(mo_class):
    pass

rawDescription: How to subclass the MatchObject in Python?

description: Subclass the MatchObject in Python


code:
import os
path = os.path.dirname(my_module.__file__)
process_script = path+ 'process.py'
put(process_script)

rawDescription: put a module file on a remote server using fabric

description: Put a module file on a remote server using fabric


code:
import os
my_file = open("data.csv", "ab")
my_file.seek(0, os.SEEK_END)

rawDescription: How to add data to the end of a CSV file (Python)

description: Add data to the end of a CSV file (Python)


code:
#client
import socket

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

while True:
    connection.connect(('localhost', 8600))
    connection.send('hello world!')
    connection.close()

rawDescription: Python while 1 loop behaviour event triggered?


code: out, err = p.communicate()

rawDescription: How do I read the output for a file spawned through subprocess.popen in Python?

description: Read the output for a file spawned through subprocess.popen in Python


code:
import urllib2, urllib
import json

root = jenkins_url
username = username
user_url = root +'/user/{username}/api/json'.format(username=username)
config_url = root + '/user/{username}/configSubmit'.format(username=username)

d = json.loads((urllib2.urlopen(user_url).read()))

fullname = d['fullName']
description = d['description']
new_email = 'new_user_email'

post_d = {"userProperty1": {"address": new_email}}

request = urllib2.Request(config_url)
values = {'json': json.dumps(post_d),
          'fullName': fullname,
          'email.address': new_email,
          'description': description}

data = urllib.urlencode(values)

response = urllib2.urlopen(request, data).read()

rawDescription: modifying user email using jenkins api with python

description: Modifying user email using jenkins api with python


code:
def _FindByTyping(self, searchColumn, prefix):
    pass

rawDescription: Disable searching in Python ObjectListView


rawDescription: Convert multi-index indices to columns

description: Convert multi-index indices to columns


code:
import xlwt
import xlrd

workbook = xlrd.open_workbook('input.xls')
sheet = workbook.sheet_by_index(0)

data = [sheet.cell_value(0, col) for col in range(sheet.ncols)]

workbook = xlwt.Workbook()
sheet = workbook.add_sheet('test')

for index, value in enumerate(data):
    sheet.write(0, index, value)

workbook.save('output.xls')

rawDescription: Using Python, write an Excel file with columns copied from another Excel file


code:
import base64
encoded = base64.b64encode('data to be encoded')
encoded
data = base64.b64decode(encoded)
data

rawDescription: Is it possible to code images into a python script?


code:
x = pd.Series([1,2,3,4], index=[2,5,6,8])
x
x.reindex(range(9), fill_value=0)

rawDescription: Pandas: expand index of a series so it contains all values in a range


code:
choice_dict = {c.question_id: c for c in Choice.objects.filter(question__in=questions).all()}
for question in questions:
     Answer(question=question,
            choice=choice_dict[question.id],
            response=response)

rawDescription: Optimal way to filter object from list of django model objects


code:
from subprocess import Popen

def send_to_imagemagick(self, shell_command):

    try:
        # log.info('Shell command = {0}'.format(shell_command))
        description=Popen(shell_command)
        description.communicate()

        # log.info('description = {0}'.format(description))
    except Exception as e:
        log.info('Error with Img cmd tool {0}'.format(e))

    while True:
        line = description.readline()
        if not line: break
        return line

rawDescription: Python popen shell command wait till subprocess has finished


code:
x = get_object_or_404(BaseItem, ppk=sou.ppk, project=sou.project, current=True)
createRevision(request, "", x)
# .... loads of lines of code
unlock(x)

rawDescription: Django method same object not saving

description: Django method same object not saving


code:
from flask import Flask, make_response
from flask.ext.restful import reqparse, abort, Api, Resource
class E2C(Resource): # English to Chinglish
    def get(self):
        chinese = u'爱'
        type(chinese) # unicode
        return make_response(chinese)

rawDescription: How to response a unicode string in flask restful api?

description: Response a unicode string in flask restful api


code:
y, x = np.nonzero(ary)
plt.plot(x, y, '.', markersize=5)

rawDescription: Updated: Matplotlib: Display numpy "sparse" array - Enlarge dots?


code:
with open('out.csv', 'a') as f:
    f.seek(0, 2) # os.SEEK_END, on Windows file position set to 0 even in append mode.
    if f.tell() == 0:
        f.write(header)
    f.write(','.join([date, str(temp_f), weather]))
    f.write('\n')

rawDescription: Python how can change my open "mode" options for "open". R+A maybe?


code:
import glob
import os
for f in glob.glob("*.obj"):
    os.remove(f)

rawDescription: Using Python, how do you remove files given a filespec such as "*.obj" on Windows?


code:
ndvi1_masked = np.ma.masked_array(ndvi1, (mergedmask==False))
ax, ay = np.unravel_index(ndvi1_masked.argmin(), ndvi1.shape)

rawDescription: Retrieve indexes of min and max values in np.ndarray


code:
df = DataFrame(randn(10,2),columns=list('AB'))
df
df.loc[:,'B'] > 0
x = df.loc[:,'B'] > 0
x[x].index
x[~x].index

rawDescription: Get indices that satisfy some criteria

description: Get indices that satisfy some criteria


code: tscores = [x for x in tscores if x != []]

rawDescription: Remove empty nested lists - Python

description: Remove empty nested lists - Python


code:
import datetime
import openpyxl
from openpyxl import load_workbook

# Source workbook - wb

wb = load_workbook(filename = r'C:\data\TEST.xlsx' , use_iterators = True)
ws = wb.get_sheet_by_name(name ='QuoteFile ')

# Quick explanation:
# If it's a number, return it. Otherwise, take the difference between the datetime
# and 1899-12-31 00:00:00. The way the datetimes work is they're internally a float,
# being the number of days since the start of 1900. We get the number of seconds in
# the delta (done through subtraction) and divide that by 86400 (the number of seconds
# in a day).
forcefloat = lambda val : val if type(val) in (int,float) else (
                         (val - datetime.datetime(1899,12,31,0,0,0)).total_seconds() / 86400)

for row in ws.iter_rows():
        print(row[0].internal_value ,forcefloat(row[3].internal_value) ,row[4].internal_value         ,row[5].internal_value)

print('Done')

rawDescription: floating numeric value read as timedate using openpyxl

description: Floating numeric value read as timedate using openpyxl


code: tagger = ClassifierBasedPOSTagger(train=training_sentences, cutoff_prob=0.95)

rawDescription: Do built in POS Taggers within NLTK have a Confidence Value for it's decisions?


code:
import hashlib
class Image(models.Model):
#...
    def save(self, *args, **kwargs):
        super(Image, self).save(*args, **kwargs)
        f = self.image_file.open('rb')
        hash = hashlib.sha1()
        if f.multiple_chunks():
           for chunk in f.chunks():
              hash.update(chunk)
        else:
              hash.update(f.read())
        f.close()
        self.sha1 =  hash.hexdigest()
        self.filesize = self.image_file.size

rawDescription: How to get the filesize and SHA-1 digest of an uploaded file?

description: Get the filesize and SHA-1 digest of an uploaded file


code:
import pyodbc

DBfile = 'Exam_BackUp.mdb'
conn = pyodbc.connect('FILEDSN='+DBfile)
cursor = conn.cursor()

# Do whatever you want with SQL selects, etc

cursor.close()
conn.close()

rawDescription: open access file in python

description: Open access file in python


code: cv_image = cv_image[:,:,::-1]

rawDescription: Optimize iteration throught numpy array

description: Optimize iteration throught numpy array


code:
my_list = [[1,2,3,1, 3], [1,3,2]]
[(i,j) for i,x in enumerate(my_list) for j,y in enumerate(x) if y == 3]

rawDescription: Find all occurences of an element in a matrix in Python


code:
class Tag(models.Model):
  name = models.TextField()
  children = models.ManyToManyField(
      'self',
      blank=True,
      related_name="parents",
      symmetrical=False
  )

green = Tag.objects.create(name='green')
color = Tag.objects.create(name='color')
color.children.add(green)
color in green.parents.all() # True

rawDescription: Django m2m field symmetrical to another m2m field


code:
class Bot:
    def __init__(self, sudoku):
        """ init code """
        pass

    # public access
    def findJokers(self, target):
        # forward to private
        return self.__findJokers(target)

    # private access
    def __findJokers(self, target):
        """ some validations """
        # hopefully you're doing something else,
        # since this is an infinite recursion.
        return self.__findJokers(target)

rawDescription: Pythonic way to calling a private function recursively within a class


code:
def index(filename, words):
    with open(filename) as f:
        for line_number, line in enumerate(f, 1):
            word = line.strip()
            if word in words:
                print(word, line_number)

fileName = 'index.txt'
wordList = ['bird', 'cat'] # input().split()
words = set(wordList)
index(fileName, words)

rawDescription: Iteration over lines in a text file, returning line numbers and occurrences?


code:
import json
data = {'val1' : 'this is x', 'val2' : True}
return HttpResponse( json.dumps( data ) )

rawDescription: how to return a dictionary in python django and view it in javascript?

description: Return a dictionary in python django and view it in javascript


code:
orders = ("kind", "apiVersion", "metadata", "spec")
for key in orders:
    v = object_pairs_hook[key]
    del object_pairs_hook[key]
    object_pairs_hook[key] = v

rawDescription: OrderedDict with specific order in Python


code:
from matplotlib.spines import Spine
from matplotlib.path import Path

ax.spines[u'middle'] = Spine( ax, 'right', Path(([[ 0., -1.], [ 0.,  1.]]), None), linestyle='--', linewidth=1, facecolor=[0,0,0], zorder=1, transform = ax.transData )

rawDescription: matplotlib: add line to axes, such that ax.set_axis_off() also hides line

description: Matplotlib: add line to axes, such that ax.set_axis_off() also hides line


code:
class MyTab(QtGui.QWidget):
    def __init__(self, parent):
       ...
       self.worker = Worker()
       self.thread = QtCore.QThread(self)
       self.worker.moveToThread(self.thread)
       self.worker.resultReady.connect(self.handleResult)
       self.thread.start()

    def callSomeFunction(self):
        QtCore.QMetaObject.invokeMethod(self.worker, 'someFunction', QtCore.Qt.QueuedConnection, QtCore.Q_ARG(str, 'arg1'))

    @QtCore.pyqtSlot(object)
    def handleResult(self, result):
        ... # do stuff with result

class Worker(QtCore.QObject):

    resultReady = QtCore.pyqtSignal(object)

    @QtCore.pyqtSlot(str)
    def someFunction(self, arg):
        ...
        self.resultReady.emit({'func': 'someFunction', 'result': True})

rawDescription: PyQt Classes Multiprocess

description: PyQt Classes Multiprocess


code:
response.css("td.c1 > span::text").extract()
response.xpath("//td[@class='c1']/span/text()").extract()

rawDescription: newbie in scrapy : how to response.css scrap the text part?

description: Newbie in scrapy : how to response.css scrap the text part


code:
subprocess.Popen(['/possibly/path/to/vncserver', ':8080', '-localhost'],
                 env={'WHATEVER': 'you', 'MAY': 'need'})

rawDescription: Starting module shell command from python subprocess module


code:
for passenger in driver.find_elements_by_css_selector("ol.passengerlist li[data-personid]"):
    passenger.click()

    has_infant = passenger.get_attribute("data-hasinfant")

    # choose seats
    if has_infant:
        # select a non-selected infant seat
        seat = driver.find_element_by_css_selector(".planebody a.seat.infant:not(.reserved):not(.selected)")
    else:
        # select a non-reserved non-selected seat
        seat = driver.find_element_by_css_selector(".planebody a.seat:not(.reserved):not(.selected)")

    print("Passenger: %s, choosing seat: %s" % (passenger.text.strip(), seat.get_attribute("data-seat")))
    seat.click()

rawDescription: How to loop through and click on relevant items

description: Loop through and click on relevant items


code:
v = 'videos'
getattr(userObj, v).filter(...)

rawDescription: Django reference managers and related managers on a model instance


code:
""" add required Python packages """
from pysde import *
from sympy import *
""" Variables acclaimed """
x,dx=symbols('x dx')
r,G,e,d=symbols('r G epsilon delta')
""" Solve Kolmogorov Forward Equation """
l=sde.KolmogorovFE_Spdf(r*(G-x),e*x*(1-x),0,1)
sol=l.subs({e:r*d})

pprint(sol)

rawDescription: Is there a python module to solve/integrate a system of stochastic differential equations?


code:
def no_collision_forward(amount, walls):
    movement = 1 if abs(amount) == amount else -1 # If amount is negative, moving down
    for i in range(abs(amount)):
        cur_pos = pos()
        nex_pos = Vec2D(cur_pos[0], cur_pos[1] + movement)
        if nex_pos in walls:
            return  # Can return whatever
        else:
            forward(movement)

def no_collision_backward(amount, walls):
    return no_collision_forward(-amount, walls)

rawDescription: Collision detection in Python

description: Collision detection in Python


rawDescription: getting list without k'th element efficiently and non-destructively

description: Getting list without k'th element efficiently and non-destructively


rawDescription: Doubling binary digits

description: Doubling binary digits


rawDescription: Read a hex string from a file in python

description: Read a hex string from a file in python


code:
d = {'A': ['available', 'unavailable','available','available','available'],
     'B': ['unavailable', 'unavailable','available','available','available'],
     'C': ['available', 'unavailable','unavailable','available','available'],
     'D': ['available', 'unavailable','available','unavailable','unavailable']}

letter = raw_input().upper()
d[letter].count('available')

rawDescription: Using raw_input to define what variable list to search


code:
lod = [
{'name': 'Tom', 'score': 60},
{'name': 'Tim', 'score': 70},
{'name': 'Tam', 'score': 80},
{'name': 'Tem', 'score': 90}
]

max(lod, key=lambda x: x['score'])

rawDescription: How to get whole dict with max value of a common key in a list of dicts

description: Get whole dict with max value of a common key in a list of dicts


code:
for i in range(len(a)):
    yield a[:i] + a[i+1:]

rawDescription: Python: for elem in list get list without that elem


code:
class WordPress(object):
    def newentry(self):
        data = get_data()
        data = process_data(data)

        # do moe generi cthings

    def process_data(self):
        return data

rawDescription: Is it possible 'step into' a method to make changes when needed


rawDescription: more efficient way split quoted string by space with python?

description: More efficient way split quoted string by space with python


code:
import subprocess
output = subprocess.check_output("df -h /", shell=True ).split('\n')[1]

data = output.split()[3][:-1]

if int(data) < 150:
    exit()

rawDescription: Parsing the output of a command

description: Parsing the output of a command


code: categories = url.split('/')[1:]

rawDescription: Regex to extract categories/sub-categories from urls with python


code:
import pygtk
pygtk.require('2.0')
import gtk

pics = []
clicks = 0

def on_destroy (widget):
    gtk.main_quit()
    return False

def on_button_clicked (widget, image):
    global clicks
    clicks += 1
    image.set_from_pixbuf (pics[clicks % len(pics)])

def create ():
    window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    window.connect("destroy", on_destroy)

    pics.append (gtk.gdk.pixbuf_new_from_file("sample1.png"))
    pics.append (gtk.gdk.pixbuf_new_from_file("sample2.png"))

    image = gtk.Image()
    image.set_from_pixbuf(pics[0])

    button = gtk.Button ("Switch Image")
    button.connect("clicked", on_button_clicked, image)

    vbox = gtk.VBox()
    vbox.pack_start (image)
    vbox.pack_start (button)

    window.add(vbox)
    window.show_all()

if __name__ == "__main__":
    create()
    gtk.main()

rawDescription: pygtk how to update gtk.Image

description: Pygtk how to update gtk.Image


rawDescription: Map discrete value to color

description: Map discrete value to color


code:
b.transpose(2, 0, 1)
b.transpose(2, 0, 1)[0]

rawDescription: create a 3D array of square matrices in numpy

description: Create a 3D array of square matrices in numpy


code:
import math
import wave
import struct

BITRATE = 44100
FREQUENCY = 440
LENGTH = 1
WIDTH = 2

def GenerateSine(NumberOfFrames):
  wave = ''
  for i in xrange(NumberOfFrames):
    value = math.sin(i * 2 * math.pi * FREQUENCY / BITRATE)
    value *= 128
    value *= (256 ** (WIDTH - 1)) - 1
    value = int(round(value))
    if WIDTH == 2:
      wave += struct.pack("<h", value)
    elif WIDTH == 4:
      wave += struct.pack("<l", value)
  return wave

WaveData = GenerateSine(int(BITRATE * LENGTH))

wf = wave.open("output.wave", 'w')
wf.setnchannels(1)
wf.setsampwidth(WIDTH)
wf.setframerate(BITRATE)
wf.writeframes(WaveData)
wf.close()

rawDescription: Python and wave width

description: Python and wave width


code:
from Tkinter import *

class App(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.pack()
        self.ent = Entry(self, width=15)
        self.ent.pack()

        self.ent.bind('<Control-x>', lambda e: 'break') #disable cut
        self.ent.bind('<Control-c>', lambda e: 'break') #disable copy
        self.ent.bind('<Control-v>', lambda e: 'break') #disable paste
        self.ent.bind('<Button-3>', lambda e: 'break')  #disable right-click

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

rawDescription: Disabling Copy/Paste action from the Tkinter entry


code:
import random
import csv
import os

os.remove("train_select.csv")

file_size=700
f=open("train.csv",'r')
o=open("train_select.csv", 'w')

f.seek(0)
random_line=f.readline()
o.write(random_line)

for i in range(0,20):
    offset=random.randrange(file_size)
    f.seek(offset)
    f.readline()
    random_line=f.readline()
    o.write(random_line)

f.close()
o.close()

rawDescription: Reading random lines from large CSV and write into a different CSV file


code:
# split the query into a list
search = 'oct 2014'
words = search.strip().split()

# use an unnest subquery instead of directly passing the list to in_
# this is for performance reasons for large lists of keywords
words_tab = db.session.query(db.func.unnest(words).label('word')).subquery()

# count the words that match for each episode as a subquery
# this also does the filtering since we're doing the join here
words_q = db.session.query(
    Episode.id,
    db.func.count(Episode.id).label('words')
).join(Episode._key_words
).filter(EpisodeKeyword._word.in_(words_tab)
).group_by(Episode.id
).subquery()

# join on the word query and order by its counts
results = Episode.query.join(
    (words_q, words_q.c.id == Episode.id)
).order_by(words_q.c.words.desc()
).all()

rawDescription: How can this query be ordered by the number of keyword matches?


code:
from datetime import datetime
timestamp = 1456741175
dt = datetime.fromtimestamp(timestamp)
print(dt.day)
# Week day number
print(dt.weekday())
print(dt.minute)
print(dt.second)

rawDescription: getting the specific weekday number, specific hour, specific minute, and specific second from unix timestmap in python

description: Getting the specific weekday number, specific hour, specific minute, and specific second from unix timestmap in python


code:
import sendgrid

sg = sendgrid.SendGridClient('Username','Password')
message = sendgrid.Mail()

message.add_to("Email Address of Reciever")
message.set_from("Email Address of Sender")
message.set_subject("Email Subject")
message.set_html("Email html")

sg.send(message)

rawDescription: How to Send Emails Using SendGrid with Python

description: Send Emails Using SendGrid with Python


code:
axes = df.boxplot(by='g')
fig = axes[0][0].get_figure()
fig.suptitle('')

rawDescription: Set no title for pandas boxplot (groupby)


code:
def findit(root, exclude_files=[], exclude_dirs=[]):
    exclude_files = (fnmatch.translate(i) for i in exclude_files)
    exclude_files = '('+')|('.join(exclude_files)+')'
    exclude_files = re.compile(exclude_files)
    exclude_dirs = (os.path.normpath(i) for i in exclude_dirs)
    exclude_dirs = (os.path.normcase(i) for i in exclude_dirs)
    exclude_dirs = set(exclude_dirs)
    for current, dirs, files in os.walk(root):
        if os.path.normpath(os.path.normcase(current)) in exclude_dirs:
            # exclude this dir and subdirectories
            dirs[:] = []
            continue
        for f in files:
            if not exclude_files.match(os.path.normcase(f)):
                yield os.path.join(current, f)

rawDescription: Python OS.WALK Remove Directories

description: Python OS.WALK Remove Directories


code:
str_list = [
    ['its', 'all', 'ball', 'bearings', 'these', 'days'],
    ['its', 'all', 'in', 'a', 'days', 'work']
]
str_set = set(word for sublist in str_list for word in sublist)

str_dict = {word: set(lindex
        for lindex, sublist in enumerate(str_list) if word in sublist)
    for word in str_set}

print (str_dict)

rawDescription: How do I add values to a set in a comprehension?

description: Add values to a set in a comprehension


code:
def sum_num(num_list):
    total = 0
    once = False
    for i in num_list:
        if i % 2 == 0 and not once:
            once = True
            continue
        total += i
    return total

rawDescription: Summing list: Skip first even number

description: Summing list: Skip first even number


rawDescription: Tkinter scrollbar resets to initial position


code:
mat = numpy.random.rand(10,10)
f = open('myFile','a')
m,n = mat.shape
for i in range(0,m):
    for j in range(0,n):
        f.writelines(repr(round(mat[i,j],4)).rjust(7))
f.writelines('\n')

f.close()

rawDescription: How to save a python array with numbers of strings to a file that is human readable

description: Save a python array with numbers of strings to a file that is human readable


code:
timFVelL.grid(row=0, column=0)
timFVelE.grid(row=0, column=1)
timFiveL.grid(row=1, column=0)
timFiveE.grid(row=1, column=1)
# ...

rawDescription: How do I align PanedWindows in Tkinter?

description: Align PanedWindows in Tkinter


code:
def save(self, *args, **kwargs):
    old_caption = None
    if self.id:
        old_caption = Art.objects.get(id=self.id).caption
    super(Art, self).save(*args, **kwargs)
    if old_caption and (self.caption != old_caption):
        if old_caption.art_set.all():
            old_caption.is_orphan = False
        else:
            old_caption.is_orphan = True
        old_caption.save()

rawDescription: Updating models to reflect changes to other models


code:
form=cgi.FieldStorage()
dir(form)

rawDescription: inserting data in database using form connected through python

description: Inserting data in database using form connected through python


code: df['C'] = df.apply(lambda x: len(set(x.B).intersection(set(x.A.split()))), axis = 1)

rawDescription: python - pass dataframe column as argument in apply function

description: Python - pass dataframe column as argument in apply function


code:
import xlwt

file_type = 'application/ms-excel'
file_name = 'sample.xls'

wbk = xlwt.Workbook()
sheet = wbk.add_sheet('Hey, Dude')
sheet.write(0, 0, 'Part Number')

file = StringIO.StringIO()
wbk.save(file)
file.seek(0)

with files.open(file_name, 'a') as f:
  f.write('%s' % file.getvalue())

files.finalize(file_name)

blob_key = files.blobstore.get_blob_key(file_name)

rawDescription: How can i store excel file created using pyExcelerator as input for db.BlobProperty()

description: Store excel file created using pyExcelerator as input for db.BlobProperty()


code:
string1 = "my music is good"
joinedstring = string1.replace(" ","")
joinedstring

rawDescription: Python - Removing space in a string without using built in methods


code:
def store_birthinfo(self, user, birthday):
    data = {}
    for key in 'date', 'place', 'country':
        data[key] = birthday.get(key, '')
    BirthInfo(user=user, **data).put()

rawDescription: Improve code: test for key in dict and store in datastore


code:
import datetime
my_datestr = "06/04/2015"
my_dateobj = datetime.datetime.strptime(my_datestr, '%m/%d/%Y')

rawDescription: Turning strings into datetime in python 3


code:
lst = ['abc', 'def']
result = [a+b for chars in lst for a, b in zip(chars, chars[1:])]
print(result)
# -> ['ab', 'bc', 'de', 'ef']

rawDescription: Python: re.sub single item in list with multiple items


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

fig = plt.figure()
ax = fig.gca(projection='3d')

r=1 # radius of sphere
phi = np.linspace(0,360, 12)/180.0*np.pi
theta = np.linspace(-90,90,7)/180.0*np.pi

# make up some function  like OP (original poster) suggested:
# numerical value in the range of 20-40.
vars=[]
for i  in range(len(phi)-1):
    for j in range(len(theta)-1):
        vars.append( (i*j* - i +j)/25+40)  # min at 20, max at 40

# set colors as function of data in vars
# less than 25 as red, from 25-35 as yellow
# and anything greater than 35 as green. –
cols=[]
for var in vars:
    if var <25:
        col='r'
    elif 25<=var<=35:
        col='y'
    else:
        col='g'
    cols.append(col)

verts2 = []
for i  in range(len(phi)-1):
    for j in range(len(theta)-1):
        cp0= r*np.cos(phi[i])
        cp1= r*np.cos(phi[i+1])
        sp0= r*np.sin(phi[i])
        sp1= r*np.sin(phi[i+1])

        ct0= np.cos(theta[j])
        ct1= np.cos(theta[j+1])

        st0= r*np.sin(theta[j])
        st1= r*np.sin(theta[j+1])

        verts=[]
        verts.append((cp0*ct0, sp0*ct0, st0))
        verts.append((cp1*ct0, sp1*ct0, st0))
        verts.append((cp1*ct1, sp1*ct1, st1))
        verts.append((cp0*ct1, sp0*ct1, st1))
        verts2.append(verts   )

poly3= Poly3DCollection(verts2 ,facecolor= cols)

poly3.set_alpha(0.9)
ax.add_collection3d(poly3)
ax.set_xlabel('X')
ax.set_xlim3d(-1, 1)
ax.set_ylabel('Y')
ax.set_ylim3d(-1, 1)
ax.set_zlabel('Z')
ax.set_zlim3d(-1, 1)
plt.show()

rawDescription: How do I color individual sections of a 3d sphere in Python

description: Color individual sections of a 3d sphere in Python


code:
def adminhome():
    row1 =''
    try:
        db = connect_db()
        rows=g.db.query("SELECT * FROM `auth_user` order by id DESC ")
        rows1 = list(rows)
        data=''
        if len(rows1) > 0:
            users = rows1
        #close_db(db)
    except Exception as e:
        users = e
    return users

@app.context_processor
def inject():
    return dict(adminhome=adminhome)

rawDescription: register function for all urls in flask

description: Register function for all urls in flask


code:
import lib # first import
# later ....
import imp
imp.reload(lib)  # lib being the module which was imported before

rawDescription: Python does not show code changes from imported file


code:
df = pd.DataFrame({'mean': 30 * np.random.random(5)})
df['mean_sum'] = pd.rolling_sum(df['mean'], 3)
df

rawDescription: Sum last X column values into new column


code: df['d'].replace(0 , method = 'ffill')

rawDescription: how to modify a pandas dataframe column more efficient

description: Modify a pandas dataframe column more efficient


code:
class ArticleController(BaseController):
    def view(self):
        c.referral = self.detect_referral()
        return render('/article.mako')

    @staticmethod
    def detect_referral():
        return request.META.get('HTTP_REFERRER', '')

rawDescription: Referencing variable from static method inside another action in Pylons


code:
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
x = [0,1,1,0]
y = [0,0,1,1]
z = [0,1,0,1]
verts = [zip(x, y,z)]
ax.add_collection3d(Poly3DCollection(verts))
plt.show()

rawDescription: Plotting 3D Polygons in python-matplotlib


code:
from django.contrib import admin

class ArticleInline(admin.TabularInline):
    model = Article

class ReporterAdmin(admin.ModelAdmin):
    inlines = [
        ArticleInline,
    ]

rawDescription: Is it possible to have an inline formset built into a ModelForm or Form in django?


code:
file1 = drive.CreateFile({'title': fname,
    "parents":  [{"id": id}],
    "mimeType": "application/vnd.google-apps.folder"})

rawDescription: Create a folder (if not exists) on google drive and upload a file to it using Python script


code:
import numpy as np
import scipy.misc

a = np.random.uniform(0, 2**16 - 1, (500, 500)).astype('int32')
img = scipy.misc.toimage(a, high=np.max(a), low=np.min(a), mode='I')
img.save('my16bit.png')

# check that you got the same values
b = scipy.misc.imread('my16bit.png')
b.dtype
# dtype('int32')
np.array_equal(a, b)
# True

rawDescription: Retain unchanged data when saving Numpy array to image with Scipy imsave


code:
handles=plt.plot([0,1],[5,6],[0,1],[8,7])
plt.legend(handles,["label a","label b"])

rawDescription: add legend to pyplot, when using single plot call

description: Add legend to pyplot, when using single plot call


code:
class SomeClass(object):
    # ...
    def __eq__(self, other):
        if not isinstance(other, SomeClass):
            return NotImplemented
        return self.attr1 == other.attr1 and self.attr2 == other.attr2

    def __ne__(self, other):
        return not (self == other)

    # if __hash__ is not needed, write __hash__ = None and it will be
    # automatically disabled
    def __hash__(self):
        return hash((self.attr1, self.attr2))

rawDescription: In python 2.7 what's the difference between "x != y" and "not x == y"?


code:
foo ="barbazzapp"
foo[:foo.find("zapp")] # Returns 'barbaz'

rawDescription: NSScanner Equivalent in C or Python

description: NSScanner Equivalent in C or Python


code:
def _gpg_pipe(args, data, passphrase):
    '''Pipe things through gpg.

    With the right args, this can be either an encryption or a decryption
    operation.

    For safety, we give the passphrase to gpg via a file descriptor.
    The argument list is modified to include the relevant options for that.

    The data is fed to gpg via a temporary file, readable only by
    the owner, to avoid congested pipes.

    '''

    # Open pipe for passphrase, and write it there. If passphrase is
    # very long (more than 4 KiB by default), this might block. A better
    # implementation would be to have a loop around select(2) to do pipe
    # I/O when it can be done without blocking. Patches most welcome.

    keypipe = os.pipe()
    os.write(keypipe[1], passphrase + '\n')
    os.close(keypipe[1])

    # Actually run gpg.

    argv = ['gpg', '--passphrase-fd', str(keypipe[0]), '-q', '--batch'] + args
    tracing.trace('argv=%s', repr(argv))
    p = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    out, err = p.communicate(data)

    os.close(keypipe[0])

    # Return output data, or deal with errors.
    if p.returncode: # pragma: no cover
        raise obnamlib.Error(err)

    return out

def encrypt_symmetric(cleartext, key):
    '''Encrypt data with symmetric encryption.'''
    return _gpg_pipe(['-c'], cleartext, key)

def decrypt_symmetric(encrypted, key):
    '''Decrypt encrypted data with symmetric encryption.'''
    return _gpg_pipe(['-d'], encrypted, key)

rawDescription: Python/POpen/gpg: Supply passphrase and encryption text both through stdin or file descriptor


rawDescription: How can I get a value that's inside parentheses in a string in Python?

description: Get a value that's inside parentheses in a string in Python


rawDescription: Data type when returning multiple values


code:
import os
import random

all_dirs = [x[0] for x in os.walk('/tmp')]
random.shuffle(all_dirs)

for a_dir in all_dirs:
    print(a_dir)
    # do something witch each directory, e.g. copy some file there.

rawDescription: Python 3 Self replicating file into random directory - then running file


code:
from django.utils.functional import lazy

class CarSearchForm(forms.Form):
    # lots of fields like this
    bodystyle = forms.ChoiceField(choices=lazy(bodystyle_choices, tuple)())

rawDescription: Lazy choices in Django form

description: Lazy choices in Django form


code:
import copy
t1 = (1, ['a', 'b'])
t2 = copy.deepcopy(t1)
t1 is t2
t1[0].append('c')
t2

rawDescription: I think immutable types like frozenset and tuple not actually copied. What is this called? Does it have any implications?


code:
conn = sqlite3.connect('databaza.db')
c = conn.cursor()
conn.text_factory = str
data3 = str(input('Please enter name: '))
query = "DELETE FROM Zoznam WHERE Name = '%s';" % data3.strip()
print(query)
mydata = c.execute(query)

rawDescription: How to delete record from table?

description: Delete record from table


code:
import heapq
from numpy import inf
heap=[[0, 0, 0], [inf, 1, 1], [inf, 2, 2], [5, 3, 3], [inf, 4, 4]]
heapq.heapify(heap)
heap
heapq.heappop(heap)
heapq.heappop(heap)
heapq.heappop(heap)
heapq.heappop(heap)
heapq.heappop(heap)

rawDescription: Unusual result from heappop?

description: Unusual result from heappop


code:
import gzip
with gzip.open('logfile.gz', 'a') as log:
    # Needs to be a bytestring in Python 3
    log.write(b"I'm a log message.\n")

rawDescription: Python write text to .tar.gz

description: Python write text to .tar.gz


code:
import copy

individual_vocab = [[e,t] for l in range(L)]

population = [copy.deepcopy(individual_vocab) for n in range(N)]

rawDescription: Dynamic triple nested list in Python

description: Dynamic triple nested list in Python


code:
nl_count = 0  # Number of new line characters
tot_count = 0  # Total number of characters
for character in buf:
    if character == '\n':
         nl_count += 1
    tot_count += 1

rawDescription: Function that opens a file for reading and returns the number of bytes and newlines


code:
import numpy as np
a = np.array([[1,2],[3,4]])
a
b=a.repeat(3,axis=0)
b
c = b.repeat(2,axis=1)
c

rawDescription: Oversample Numpy Array (2D)

description: Oversample Numpy Array (2D)


code:
class ClubFilter(django_filters.FilterSet):
    # ...

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(ClubFilter, self).__init__(*args, **kwargs)

rawDescription: Get Current User in django-filter Method


code:
from flask import request
request.args.get('key', '')

rawDescription: Getting values from a url in python(3)

description: Getting values from a url in python(3)


code:
class YourView(SomeView):
    def dispatch(self, request, *args, **kwargs):
        # parse the request here ie.
        self.foo = request.GET.get('foo', False)

        # call the view
        return super(YourView, self).dispatch(request, *args, **kwargs)

rawDescription: Is it okay to set instance variables in a Django class based view?


code:
import sys

def main(args):
    pass

# All your other function definitions here

if __name__ == '__main__':
    exit(main(sys.argv[1:]))

rawDescription: Scope, using functions in current module


code:
import xlwings as xw
wb = xw.Workbook('WorkbookName')
xw.Sheet('SheetName').xl_sheet.checkboxes['CheckBox_Name'].value.get()

rawDescription: How to interact with VBA objects in sheets using xlwings?

description: Interact with VBA objects in sheets using xlwings


code:
typ, data = M.search(None, '(BEFORE 01-Jan-2009)')
for num in data[0].split():
   M.store(num, '+FLAGS', '\\Seen')

rawDescription: Parse Gmail with Python and mark all older than date as "read"


code: b = sorted(a, key=lambda item:(-item[1], item[0]))

rawDescription: Order list according to two items

description: Order list according to two items


code: joined = '\x01'.join(data)

rawDescription: How to concatenate strings with binary values in python?

description: Concatenate strings with binary values in python


code:
for i in range(1, sh.nrows):
    data = OrderedDict()
    for j in range(1, sh.ncols+1):
        data[sh.row_values(0)[j-1]] = sh.row_values(i)[j-1]
        data3.append(sh.row_values(i)[j-1])

        #data[j] = ({sh.row_values(0)[j-(sh.nrows - sh.ncols)] : sh.row_values(j)})
        #print("I = "+i.__str__())
        #print("J = "+j.__str__())
    data_list.append(data)

rawDescription: How to dynamically update dictonary (key/data) in python

description: Dynamically update dictonary (key/data) in python


code:
from xlrd import open_workbook

wb = open_workbook('spreadsheet.xlsx')
for s in wb.sheets():
     print('Sheet:',s.name) # you can check for the sheet name here if you want
     for row in range(2): #the first 2 rows (A and B) (use s.nrows for all)
         values = []
         for col in range(3): #the first 3 columns (use s.ncols for all)
            values.append(str(s.cell(row,col).value))
         print(','.join(values))

rawDescription: python library or code to read already open Excel file

description: Python library or code to read already open Excel file


code:
class tInt(int):

    def __add__(self, other):
        if isinstance(other, str):
            return str(self) + str(other)
        elif isinstance(other, int):
            return int(self) + other
        elif isinstance(other, float):
            return float(self) + float(other)
        else:
            return NotImplemented

    def __radd__(self, other):
        return self.__add__(other)

a = tInt(2)
for x in ["5", 5, 5.0]:
    print (a + x)
    print (x + a)

25
25

7
7

7.0
7.0

rawDescription: Automatic type conversions of user defined classes


code: Main.objects(id=main_id).update_one(pull__values__id = Sub(Id=sub_id) )

rawDescription: Using MongoDB, how do you remove embedded document from a list based on a match


rawDescription: Split Regular expression after each repetition


code:
my_list = ["Value1", "Value2"]
json = simplejson.dumps(my_list)
# send json

rawDescription: Generating XML in Python

description: Generating XML in Python


code:
s1 = set( input_1 )
s2 = set( input_2 )

lines_in_both_files = s1.intersection(s2)
lines_in_either = s1.union(s2)

# lines in input_1 not in input_2
l1_n2 = s1 - s2
# lines in input_2 not in input_1
l2_n1 = s2 - s1

rawDescription: Python: two way de-duplicating

description: Python: two way de-duplicating


code:
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
profile = FirefoxProfile ()
profile.set_preference("browser.download.folderList",2)
profile.set_preference("browser.download.manager.showWhenStarting",False)
profile.set_preference("browser.download.dir", 'D:\\') #choose folder to download to
profile.set_preference("browser.helperApps.neverAsk.saveToDisk",'application/octet-stream')
driver = webdriver.Firefox(firefox_profile=profile)
driver.get('https://www.google.com/googlebooks/uspto-patents-grants-text.html#2015')
filename = driver.find_element_by_xpath('//a[contains(text(),"ipg150106.zip")]') #use loop to list all zip files
filename.click()

rawDescription: Download files using Python 3.4 from Google Patents


code:
class Borg:

    _shared_state = {}

    def __init__(self):
        self.__dict__ = self._shared_state

rawDescription: Singleton- python, Situation with the need of only one object


code:
def packageN(f):
    return lambda: lambda *x: f(*x)

rawDescription: making function lazy in Python

description: Making function lazy in Python


code:
if make_directories:
    for car in cars:
        carpath = os.path.join(outer_dir, car)
        os.makedirs(carpath)
        for fn in textfiles:
            filepath = os.path.join(carpath, fn)
            #... use filepath ...

rawDescription: How to dynamically create directories and output files into them python

description: Dynamically create directories and output files into them python


code:
import numpy as np
from pylab import *
from sklearn import mixture

# Create some sample data
def G(mu, cov, pts):
    return np.random.multivariate_normal(mu,cov,500)

# Three multivariate Gaussians with means and cov listed below
MU  = [[5,3], [0,0], [-2,3]]
COV = [[[4,2],[0,1]], [[1,0],[0,1]], [[1,2],[2,1]]]

A = [G(mu,cov,500) for mu,cov in zip(MU,COV)]
PTS = np.concatenate(A) # Join them together

# Use a Gaussian Mixture model to fit
g = mixture.GMM(n_components=len(A))
g.fit(PTS)

# Returns an index list of which cluster they belong to
C = g.predict(PTS)

# Plot the original points
X,Y = map(array, zip(*PTS))
subplot(211)
scatter(X,Y)

# Plot the points and color according to the cluster
subplot(212)
color_mask = ['k','b','g']
for n in xrange(len(A)):
    idx = (C==n)
    scatter(X[idx],Y[idx],color=color_mask[n])
show()

rawDescription: Build in function for plotting bayes decision boundary given the probability function


code:
with open(csvfile, newline='') as f_left:
    reader_left = csv.reader(f_left, delimiter=',')
    with open(csvfile, newline='') as f_right:
        reader_right = csv.reader(f_right, delimiter=',')
        for row in reader_left:
            for compare_row in reader_right:
                if row == compare_row:
                    print(row,'is equal to',compare_row)
                else:
                    print(row,'is not equal to',compare_row)
            f_right.seek(0)

rawDescription: Python CSV Reader - Compare Each Row with Each Other Row Within One Column


code: return '%d' % (next(self.counter) + 1)

rawDescription: python, return calculations with %d

description: Python, return calculations with %d


code:
list_of_strings = ["aaa", "dasdas", "aaafff", "afff", "abbbc"]
[x for x in list_of_strings if re.search(r'(.)\1{2}', x)]

rawDescription: Filter strings where there are n equal characters in a row


code:
response = HttpResponse(my_data, content_type='text/x-python')
response['Content-Disposition'] = 'attachment; filename="foo.py"'

rawDescription: Django, how to make a download button for a script displayed on the website