code:
s='aáàAâÂbBcCçÇdDeéEfFgGğĞhHiİîÎíīıIjJkKlLmMnNóoOöÖpPqQrRsSşŞtTuUûúÛüÜvVwWxXyYzZ'
s2='aaaaaabbccccddeeeffgggghhiiiiiiiijjkkllmmnnoooooppqqrrssssttuuuuuuuvvwwxxyyzz'
trans = str.maketrans(s, s2)

def unikey(seq):
    return seq[0].translate(trans)

rawDescription: sorting of list containing utf-8 charachters

description: Sorting of list containing utf-8 charachters


code:
#!/usr/bin/env python
import re

try:
    from urllib2 import urlopen
except ImportError: # Python 3
    from urllib.request import urlopen

from bs4 import BeautifulSoup, NavigableString

def table_after_atoz(tag):
    '''Whether tag is a <table> after an element with id="LUA to Z".'''
    if tag.name == 'table' and 'TableLineupBox' in tag.get('class', ''):
        for tag in tag.previous_elements: # go back
            if not isinstance(tag, NavigableString): # skip strings
                return tag.get('id') == "LUA to Z"

def confirmed_band_links(soup):
    table = soup.find(table_after_atoz) # find A to Z table
    for tr in table.find_all('tr'): # find all rows (including nested tables)
        if tr.find('img', alt="confirmed"): # row with a confirmed band?
            yield tr.find('a', href=re.compile(r'^/festivals/bands')) # a link

def main():
    url = "http://www.efestivals.co.uk/festivals/glastonbury/2013/lineup.shtml"
    soup = BeautifulSoup(urlopen(url))
    for link in confirmed_band_links(soup):
        print("%s\t%s" % (link['href'], link.string))

main()

rawDescription: Basic beautiful soup help - Glastonbury lineup


code: dict((k,v) for k,v in parent_dict.iteritems() if 2 < k < 4)

rawDescription: Pythonic way to fetch all elements in a dictionary, falling between two keys?


code:
from threading import Thread
t = Thread(target=self.ReadThread)
t.setDaemon(True)

rawDescription: Quit when QThreadPool not empty?

description: Quit when QThreadPool not empty


code:
import signal

def input_or_timeout(timeout):
    def nothing(sig, frame): pass
    signal.signal(signal.SIGALRM, nothing)
    signal.alarm(timeout)
    try:
        raw_input()
        signal.alarm(0)
    except (IOError, EOFError): pass

rawDescription: Python: wait for a key press or until timeout


code:
class Choice(object):
    def __init__(self, id, label):
        self.id = id
        self.label = label

    def __repr__(self):
        return self.label

rawDescription: Why isn't swing calling toString() on the objects I pass to a JComboBox?


code:
clothing = {
    (True, True): "shorts",
    (True, False): "jeans",
    (False, False): "jacket"
}

rawDescription: python boolean key for a dictionary

description: Python boolean key for a dictionary


code:
import pylab as pl

pl.clf()
for count in range(5):
    pl.scatter(pl.rand(10), pl.rand(10), color=pl.cm.seismic(count / 5.0), s=50)

rawDescription: matplotlib: How to plot multiple scatter plots in one grid where each plot is different color based on a separate list?

description: Matplotlib: How to plot multiple scatter plots in one grid where each plot is different color based on a separate list


code:
db.users.aggregate([
    { "$unwind": "$acl.users" },
    { "$group": {
        "_id": "$acl.users",
        "count": { "$sum": 1 }
    }}
])

rawDescription: Mongodb aggregation query inside an array over multiple entries


rawDescription: A pythonic approach to extracting data from array


code:
def Main():
    global param
    s = subThread.subThread(param)
    s.start()
    s.join()
    param = s.param
    print(param)

if __name__ == '__main__':
    Main()

rawDescription: How do I update a variable passed onto a thread?

description: Update a variable passed onto a thread


code:
import os

filename = askopenfilename()
directory = os.path.split(filename)[0]

ext = 'npz'

for i in range(1, NF):
    filename = os.path.join(directory, '%s.%s' % (i, ext))
    ...

rawDescription: How to define from where the script loads files?

description: Define from where the script loads files


code:
import matplotlib.pyplot as plt
import numpy

def setPlot(data, mycolor, myalpha, mylinestyle):
    plt.style.use('ggplot')
    plt.rc('xtick',labelsize=12)
    plt.rc('ytick',labelsize=12)
    plt.xlabel("Incomes")
    plt.hist(data, bins=50, color= mycolor, alpha=myalpha)
    plt.axvline(numpy.mean(data), color=mycolor, linestyle=mylinestyle,
                linewidth=1.5,label='{:5.0f}'.format(numpy.mean(data)))

setPlot(numpy.random.rand(100)*30000.,'r',0.5,'--')
setPlot(numpy.random.rand(100)*20000.,'b',0.5,'-')

plt.legend(loc=0)

plt.savefig('myfig.png')

rawDescription: Python Matplotlib: add legend with the exact value of a mean lien


code:
from numpy.random import uniform, seed
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
import numpy as np
# make up data.
#npts = int(raw_input('enter # of random points to plot:'))

def f(spi, the_colormap):
    plt.subplot(spi)
    seed(0)
    npts = 200
    x = uniform(-2, 2, npts)
    y = uniform(-2, 2, npts)
    z = x*np.exp(-x**2 - y**2)
    xi = np.linspace(-2.1, 2.1, 100)
    yi = np.linspace(-2.1, 2.1, 200)
    zi = griddata(x, y, z, xi, yi, interp='linear')

    CS = plt.contour(xi, yi, zi, 15, linewidths=0.5, colors='k')
    CS = plt.contourf(xi, yi, zi, 15, cmap=the_colormap,
                      vmax=abs(zi).max(), vmin=-abs(zi).max())
    plt.colorbar()  # draw colorbar
    # plot data points.
    plt.scatter(x, y, marker='o', c='b', s=5, zorder=10)
    plt.xlim(-2, 2)
    plt.ylim(-2, 2)
    plt.title('griddata test (%d points)' % npts)

f(131, plt.cm.rainbow)
f(132, plt.cm.gray)
f(133, plt.cm.hot)

plt.show()

rawDescription: Greyscale in python - incorect colors changing from dark grey to light grey to dark grey


code:
fh = h5py.File('dummy.h5','a')
fh['random'].value
fh['random'][0][0] = 6
fh['random'].value
fh['random'][0,0] = 6
fh['random'].value

rawDescription: How can I update a 2 dimension array with h5py?

description: Update a 2 dimension array with h5py


rawDescription: Counting elements in a list of lists in python


code:
import imp
import sys
from threading import Thread
from time import sleep

import wx

class MyFinder(object):
    def __init__(self):
        print('MyFinder initializing')
        if imp.lock_held():
            while imp.lock_held():
                print('import lock held')
                sleep(2)
            print('import lock released')
        else:
            print('import lock is not held')

    def find_module(self, module, package=None):
        print('MyFinder.find_module called with module name "{}", pakcage name "{}"'.format(module, package))
        return None

def test():
    sys.meta_path.append(MyFinder())
    from my_time import sleep
    count = 0
    while True:
        print("{} thread still running".format(count))
        count += 1
        sleep(2)

app = wx.App()
frame = wx.Frame(None, -1, 'simple.py')
frame.Show()
thread = Thread(target=test)
thread.setDaemon(True)
thread.start()
app.MainLoop()

rawDescription: thread fails to start if wx.app.mainloop isn't called from the main module

description: Thread fails to start if wx.app.mainloop isn't called from the main module


code:
from Tkinter import *

root = Tk()
t = Text(root)
t.pack()
t.insert(END, '''\
blah blah blah Failed blah blah
blah blah blah Passed blah blah
blah blah blah Failed blah blah
blah blah blah Failed blah blah
''')
t.tag_config('failed', background='red')
t.tag_config('passed', background='blue')

def search(text_widget, keyword, tag):
    pos = '1.0'
    while True:
        idx = text_widget.search(keyword, pos, END)
        if not idx:
            break
        pos = '{}+{}c'.format(idx, len(keyword))
        text_widget.tag_add(tag, idx, pos)

search(t, 'Failed', 'failed')
search(t, 'Passed', 'passed')

#t.tag_delete('failed')
#t.tag_delete('passed')

root.mainloop()

rawDescription: Tkinter: Highlight/Colour specific lines of text based on a keyword


rawDescription: Python 2: one-line or very compact code to check "startswith" across several strings?


rawDescription: python len calculation

description: Python len calculation


code:
"""Functions for getting memory usage of Windows processes."""

__all__ = ['get_current_process', 'get_memory_info', 'get_memory_usage']

import ctypes
from ctypes import wintypes

GetCurrentProcess = ctypes.windll.kernel32.GetCurrentProcess
GetCurrentProcess.argtypes = []
GetCurrentProcess.restype = wintypes.HANDLE

SIZE_T = ctypes.c_size_t

class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
    _fields_ = [
        ('cb', wintypes.DWORD),
        ('PageFaultCount', wintypes.DWORD),
        ('PeakWorkingSetSize', SIZE_T),
        ('WorkingSetSize', SIZE_T),
        ('QuotaPeakPagedPoolUsage', SIZE_T),
        ('QuotaPagedPoolUsage', SIZE_T),
        ('QuotaPeakNonPagedPoolUsage', SIZE_T),
        ('QuotaNonPagedPoolUsage', SIZE_T),
        ('PagefileUsage', SIZE_T),
        ('PeakPagefileUsage', SIZE_T),
        ('PrivateUsage', SIZE_T),
    ]

GetProcessMemoryInfo = ctypes.windll.psapi.GetProcessMemoryInfo
GetProcessMemoryInfo.argtypes = [
    wintypes.HANDLE,
    ctypes.POINTER(PROCESS_MEMORY_COUNTERS_EX),
    wintypes.DWORD,
]
GetProcessMemoryInfo.restype = wintypes.BOOL

def get_current_process():
    """Return handle to current process."""
    return GetCurrentProcess()

def get_memory_info(process=None):
    """Return Win32 process memory counters structure as a dict."""
    if process is None:
        process = get_current_process()
    counters = PROCESS_MEMORY_COUNTERS_EX()
    ret = GetProcessMemoryInfo(process, ctypes.byref(counters),
                               ctypes.sizeof(counters))
    if not ret:
        raise ctypes.WinError()
    info = dict((name, getattr(counters, name))
                for name, _ in counters._fields_)
    return info

def get_memory_usage(process=None):
    """Return this process's memory usage in bytes."""
    info = get_memory_info(process=process)
    return info['PrivateUsage']

if __name__ == '__main__':
    import pprint
    pprint.pprint(get_memory_info())

rawDescription: How to get PrivateUsage memory value from python on win7x64

description: Get PrivateUsage memory value from python on win7x64


code:
import sys
oldhook = sys.displayhook
sys.displayhook = your_module.DisplayHook(oldhook)

rawDescription: __str__ and pretty-printing (sub)dictionaries


code:
import scipy.optimize as optimize
def rosen(x):
    """The Rosenbrock function"""
    return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)
x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
xopt = optimize.fmin(rosen, x0, xtol=1e-8, disp=True)
# Optimization terminated successfully.
#          Current function value: 0.000000
#          Iterations: 339
#          Function evaluations: 571
print(xopt)
# [ 1.  1.  1.  1.  1.]

rawDescription: Minimizing python function that has numpy array as argument


code:
@app.route('/')
def template():
    return render_template('index.html')

status = False
@app.route('/result')
def serial_monitor():
    global status
    #connect to serial port for once
    if status== False:
        ser = serial.Serial('/dev/cu.wchusbserialfa140',9600)
        status = True

    result = str(ser.readline())
    voltage = {'value':result}
    return jsonify(voltage)

rawDescription: Run command only once when request with .getJSON in Flask


code:
d1 = {'el1': 2, 'el3': 4, 'el5': 17, 'el12':32}
d2 = {'el1': 5, 'el3': 9, 'el5': 11, 'el12':6}
d3 = {'el1': 1, 'el6': 2, 'el7': 41, 'el12':13}

d = [d1, d2, d3]

G = nx.DiGraph()
# or just Graph() if not weighted
# If unweighted, you should use combinations() instead, as for a given list
# ['e1', 'e2', 'e3'], permutations(l, 2) will give both ('e1', 'e2') and ('e2','e1')
# whereas combinations will give only one of those.

for item in d:
    G.add_nodes_from(item)
    for entry in item:
        try:
            G.node[entry]['weight'] += item[entry]
        except:
            G.node[entry]['weight'] = item[entry]
    for source, target in itertools.permutations(item.keys(), 2):
        G.add_edge(source, target)
        try:
            G.edge[source][target]['weight'] += 1
        except:
            G.edge[source][target]['weight'] = 1

G.node
{'el1': {'weight': 8},
 'el12': {'weight': 51},
 'el3': {'weight': 13},
 'el5': {'weight': 28},
 'el6': {'weight': 2},
 'el7': {'weight': 41}}
G.edge
{'el1': {'el12': {'weight': 3},
  'el3': {'weight': 2},
  'el5': {'weight': 2},
  'el6': {'weight': 1},
  'el7': {'weight': 1}},
 'el12': {'el1': {'weight': 3},
  'el3': {'weight': 2},
  'el5': {'weight': 2},
  'el6': {'weight': 1},
  'el7': {'weight': 1}},
 'el3': {'el1': {'weight': 2}, 'el12': {'weight': 2}, 'el5': {'weight': 2}},
 'el5': {'el1': {'weight': 2}, 'el12': {'weight': 2}, 'el3': {'weight': 2}},
 'el6': {'el1': {'weight': 1}, 'el12': {'weight': 1}, 'el7': {'weight': 1}},
 'el7': {'el1': {'weight': 1}, 'el12': {'weight': 1}, 'el6': {'weight': 1}}}

rawDescription: Building a huge weighted network with networkx in python


code: dfm.index = range(1,len(dfm) + 1)

rawDescription: Pandas: Reindex Unsorts Dataframe

description: Pandas: Reindex Unsorts Dataframe


rawDescription: Why Ruby and Python long division differs from GMP and Java BigInteger?


code: g_proptypes = dict((string, i) for i, string in enumerate(string_list))

rawDescription: pythonic way to map set of strings to integers

description: Pythonic way to map set of strings to integers


code:
from django.utils.decorators import method_decorator

class ContactFormView(FormView):
    ...
    @method_decorator(csrf_protect)
    def dispatch(self, *args, **kwargs):
        return super(ContactFormView, self).dispatch(*args, **kwargs)

rawDescription: CSRF protection on Django FormView

description: CSRF protection on Django FormView


code: mydict['_id'] = str(ObjectId())

rawDescription: Unable to add multiple docs to Couchdb because of identical _ids


code:
for element in text_list:
    if element in opening_bracket_list:
       s.push(element)
    elif element in closing_bracket_dict:
       if s.pop() != closing_bracket_dict[element]:
          return False

rawDescription: How to return the last element in stack

description: Return the last element in stack


code:
import numpy as np

data = np.random.random((500000, 24))
 # This returns an array of size 500,000 that is the row of 24 values
minimum = data.min(axis=1)

data = data * minimum

rawDescription: Numpy column wise multiplication

description: Numpy column wise multiplication


code:
def replace_all(output_file, data):
    homedir = os.path.expanduser("~")
    contracts_dir = homedir + "/tmp"
    with open(output_file, "r") as my_file:
        contents = my_file.read()
    destination_file = contracts_dir + "/" + data["filename"]
    fp = open(destination_file, "w")
    for key, value in data.iteritems():
        contents = contents.replace("$" + str(key), value)
    fp.write(contents)
    fp.close()

rawDescription: How to replace values from JSON with those found by RegEx in a file using Python?

description: Replace values from JSON with those found by RegEx in a file using Python


code:
import curses

stdscr = curses.initscr()

def print_char(x, y, char):
    stdscr.addch(y, x, char)

rawDescription: Print character to a certain point on console in Python?


code:
class UserProfileSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username', read_only=True)
    email = serializers.EmailField(source='user.email', read_only=True)

    class Meta:
        model=UserProfile
        fields = (phone, username, email)

rawDescription: django rest framework get data from foreign key relation

description: Django rest framework get data from foreign key relation


code:
import sys
print (sys.path)

rawDescription: Python Library Path

description: Python Library Path


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

full_fig, full_ax = plt.subplots()
x = np.arange(5)

for i, color in zip(range(1, 4), sns.color_palette()):

    part_fig, part_ax = plt.subplots(subplot_kw=dict(ylim=(0, 12)))
    y = x * i
    full_ax.plot(x, y, c=color)
    part_ax.plot(x, y, c=color)
    part_ax.set_title("Part %d" % i)
    part_fig.savefig("part_%d.png" % i)
full_ax.set_title("Full")
full_fig.savefig("full_png")

rawDescription: Generate multiple separate graphs from one script


code:
for image in folderToResizeContents:
    for fmt in sizeFormats:
        (w,h) = fmt.split('x')

rawDescription: How to loop through one element of a zip() function twice - Python

description: Loop through one element of a zip() function twice - Python


rawDescription: Python 3: convert a list into a dictionary


code:
import Tkinter as tk
import ttk

def about_window():
    top2 = tk.Toplevel(root)
    top2.title("About")
    top2.resizable(0,0)

    explanation = "This program is my test program"

    ttk.Label(top2,justify=tk.LEFT,text=explanation).pack(padx=5,pady=2)
    ttk.Button(top2,text='OK',width=10,command=top2.destroy).pack(pady=8)

    top2.transient(root)
    top2.grab_set()
    root.wait_window(top2)

root = tk.Tk()
root.resizable(0,0)

root.style = ttk.Style()
# ('clam', 'alt', 'default', 'classic')
root.style.theme_use("clam")

menu = tk.Menu(root)
root.config(menu=menu)

fm = tk.Menu(menu, tearoff=0)
menu.add_cascade(label="Settings",menu=fm)
fm.add_command(label="Preferances")

hm = tk.Menu(menu, tearoff=0)
menu.add_cascade(label="Help",menu=hm)
hm.add_command(label="About", command=about_window)
hm.add_command(label="Exit",command=root.quit)
#

tk.mainloop()

rawDescription: Python Tkinter. Show only one copy of window


code: os.getuid() == 0 and "root" or "not root"

rawDescription: Admin privileges for script

description: Admin privileges for script


code:
import dicom, dicom.UID
from dicom.dataset import Dataset, FileDataset
import numpy as np
import datetime, time

def write_dicom(pixel_array,filename):
    """
    INPUTS:
    pixel_array: 2D numpy ndarray.  If pixel_array is larger than 2D, errors.
    filename: string name for the output file.
    """

    ## This code block was taken from the output of a MATLAB secondary
    ## capture.  I do not know what the long dotted UIDs mean, but
    ## this code works.
    file_meta = Dataset()
    file_meta.MediaStorageSOPClassUID = 'Secondary Capture Image Storage'
    file_meta.MediaStorageSOPInstanceUID = '1.3.6.1.4.1.9590.100.1.1.111165684411017669021768385720736873780'
    file_meta.ImplementationClassUID = '1.3.6.1.4.1.9590.100.1.0.100.4.0'
    ds = FileDataset(filename, {},file_meta = file_meta,preamble="\0"*128)
    ds.Modality = 'WSD'
    ds.ContentDate = str(datetime.date.today()).replace('-','')
    ds.ContentTime = str(time.time()) #milliseconds since the epoch
    ds.StudyInstanceUID =  '1.3.6.1.4.1.9590.100.1.1.124313977412360175234271287472804872093'
    ds.SeriesInstanceUID = '1.3.6.1.4.1.9590.100.1.1.369231118011061003403421859172643143649'
    ds.SOPInstanceUID =    '1.3.6.1.4.1.9590.100.1.1.111165684411017669021768385720736873780'
    ds.SOPClassUID = 'Secondary Capture Image Storage'
    ds.SecondaryCaptureDeviceManufctur = 'Python 2.7.3'

    ## These are the necessary imaging components of the FileDataset object.
    ds.SamplesPerPixel = 1
    ds.PhotometricInterpretation = "MONOCHROME2"
    ds.PixelRepresentation = 0
    ds.HighBit = 15
    ds.BitsStored = 16
    ds.BitsAllocated = 16
    ds.SmallestImagePixelValue = '\\x00\\x00'
    ds.LargestImagePixelValue = '\\xff\\xff'
    ds.Columns = pixel_array.shape[0]
    ds.Rows = pixel_array.shape[1]
    if pixel_array.dtype != np.uint16:
        pixel_array = pixel_array.astype(np.uint16)
    ds.PixelData = pixel_array.tostring()

    ds.save_as(filename)
    return

if __name__ == "__main__":
#    pixel_array = np.arange(256*256).reshape(256,256)
#    pixel_array = np.tile(np.arange(256).reshape(16,16),(16,16))
    x = np.arange(16).reshape(16,1)
    pixel_array = (x + x.T) * 32
    pixel_array = np.tile(pixel_array,(16,16))
    write_dicom(pixel_array,'pretty.dcm')

rawDescription: Create pydicom file from numpy array

description: Create pydicom file from numpy array


code:
from django.shortcuts import render_to_response
from django.template import Template, Context
from django.utils.safestring import mark_safe
from string import letters
def home(request):
    t = Template("""

                        {% for key, value in d.items %}

{{ key }}: {{ value }}

                        {% endfor %}

""")
    c = Context({'d': {k: v for v, k in enumerate(letters)}})
    return render_to_response('home.html', {'t': mark_safe(t.render(c))})

rawDescription: How to include template generated in runtime and stored in variable?

description: Include template generated in runtime and stored in variable


rawDescription: Remove repeating tuples from a list, depending on the values in the tuples


code: modhandle = imp.load_source(modname, modfile)

rawDescription: Python reload with dynamic import (imp.load_source)


code:
import pandas as pd
pd.get_dummies(['male', 'female'])

rawDescription: How do i convert 30 categories into numbers for scikit

description: Convert 30 categories into numbers for scikit


code:
def prastevila(n):
    p = []
    for k in range(2, n + 1):
        i = 0
        while i < len(p) and k % p[i] != 0:
            i += 1
        if i == len(p):
            p.append(k)
    return p

#In [2]: prastevila(20)
#Out[2]: [2, 3, 5, 7, 11, 13, 17, 19]

rawDescription: Finding all primes below a given limit with this partial code


code:
def my_timer(*args):
    return True# do ur work here, but not for long

gtk.timeout_add(60*1000, my_timer) # call every min

rawDescription: Run a function every X minutes - Python

description: Run a function every X minutes - Python


code:
if request.method == 'POST':
    username = request.POST.get('username')
else:
    username = request.GET.get('username')

rawDescription: How can I take data from this input box?

description: Take data from this input box


code:
for group, items in placed_objects.items():
    placed_objects[group] = [x for x in items if not x.collidepoint(mousePos)]

rawDescription: Shortcut in Python for repetitive actions with variables?


code:
active_videos_ids = Video.objects.filter(active=True).values_list('id', flat=True)
comments = Comment.objects.for_model(Video).filter(object_pk__in=active_videos_ids)

rawDescription: Filter on content_object django comments


code:
import time
import sys

bar = '>'
for i in range(100):
    bar = '='.join(['', bar])
    sys.stdout.write('\r' + bar)
    sys.stdout.flush()
    time.sleep(0.5)

rawDescription: Appending text and continuing progrees bar in Python


code:
def __eq__(self, other):
    if not isinstance(other, ThisClass):
        return NotImplemented
    return self.member_tuple == other.member_tuple

rawDescription: How to implement __cmp__() and __hash__() for my class?

description: Implement __cmp__() and __hash__() for my class


code:
Somewhere.objects.extra(select={'year': 'EXTRACT(year FROM date)',
                                'month': 'EXTRACT(month FROM date)'}
                       ).values_list('year', 'month').annotate(Sum('amount'))

rawDescription: Can I do custom complicated group by in a Django QuerySet?

description: Do custom complicated group by in a Django QuerySet


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

x1 = np.random.binomial(5100,0.5,51100)
y1 = np.random.binomial(5000,0.7,51100)
x2 = np.random.binomial(5000,0.5,51100)
y2 = np.random.binomial(5000,0.7,51100)

xmin,xmax,xnum = 2350,2700,50
ymin,ymax,ynum = 3350,3700,50
xx,yy=np.mgrid[xmin:xmax:xnum*1j,ymin:ymax:ynum*1j]

def closest_idx(x,y):
    idcs    = np.argmin((xx-x)**2 + (yy-y)**2)
    i_x,i_y = np.unravel_index(idcs, (xnum,ynum) )
    return i_x,i_y

def calc_count( xdat,ydat ):
    ct = np.zeros_like(xx)
    for x,y in itertools.izip(xdat,ydat):
        ix,iy = closest_idx(x,y)
        ct [ix,iy] += 1
    return ct

ct1 = calc_count( x1,y1 )
ct2 = calc_count( x2,y2 )

def color_mix( c1 , c2 ):
    cm=np.empty_like(c1)
    for i in [0,1,2]:
        cm[i] = (c1[i]+c2[i])/2.
    return cm

dens1 = ct1 / np.max(ct1)
dens2 = ct2 / np.max(ct2)

ct1_color = np.array([1+0*dens1 , 1-dens1 , 1-dens1  ])
ct2_color = np.array([1-dens2   , 1-dens2 , 1+0*dens2])

col = color_mix( ct1_color , ct2_color )
col = np.transpose( col, axes=(2,1,0))

plt.imshow( col , interpolation='nearest' ,extent=(xmin,xmax,ymin,ymax),origin='lower')
plt.show()

rawDescription: Scatter plot with alpha still opaque on areas where spots are dense


code:
#!/usr/bin/env python
import Tkinter as tk
import tkFileDialog

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.grid()
        self.quit_program()
        self.browse_file()
        self.file_opt = options = {}
        options['defaultextension'] = '.txt'
        options['filetypes'] = [('musicfiles', '.mp3'),('vediofiles', '.mp4')]

        options['parent'] = self
        options['title'] = 'This is a title'

    def quit_program(self):
        self.quitButton = tk.Button(self, text='Quit',
          command=self.quit)
        self.quitButton.grid()

    def browse_file(self):
        self.browseButton = tk.Button(self, text='Browse',command=self.askopenfile)
        self.browseButton.grid()
    def askopenfile(self):
        return tkFileDialog.askopenfile(**self.file_opt )

app = Application()
app.master.title('Sample application')
app.mainloop()

rawDescription: Browsing not shown for Python GUI Tkinter


rawDescription: Group Datetime in panda into three hourly intervals


rawDescription: MongoDB Query in Pymongo

description: MongoDB Query in Pymongo


code:
cv.PyrDown(img, dsimg)

data = np.asarray(dsimg)
blue, green, red = data.T

res = (green > (_RED_DIFF + red)) & (green > (_BLU_DIFF + blue))
res = res.astype(np.uint8) * 255

res = cv.fromarray(res)

rawDescription: OpenCV Python binds incredibly slow iterations through image data


code:
time.strptime('2010-10-15 11:01:02', '%Y-%m-%d %H:%M:%S')
# returns the following on a computer with Central European Sommer Time (CEST, +02:00):
time.struct_time(tm_year=2010, tm_mon=10, tm_mday=15, tm_hour=11, tm_min=1, tm_sec=2, tm_wday=4, tm_yday=288, tm_isdst=-1)

rawDescription: Why Python sets my default timezone to -1?


rawDescription: Make a scatter colorbar display only a subset of the vmin/vmax


code:
#!/usr/bin/env python3
import os
import time
from subprocess import Popen, PIPE, DEVNULL

# start AVL Program
with Popen(os.path.abspath("avl.exe"), stdin=PIPE, stdout=DEVNULL, bufsize=1,
           universal_newlines=True) as process:
    time.sleep(2)
    # start program with LOAD and filename:
    print("LOAD " + os.path.abspath(r"input_cases\sample.avl"), file=process.stdin)
    time.sleep(2)
    print(file=process.stdin) # send newline
    time.sleep(5)
    print(file=process.stdin) # send newline
    time.sleep(0.5)
    print("QUIT", file=process.stdin)

rawDescription: Python Subprocess: Fortran runtime error: End of file


code:
import threading
import time

lock = threading.Lock()
cond = threading.Condition(threading.Lock())

def waitLock(timeout):
    with cond:
        current_time = start_time = time.time()
        while current_time < start_time + timeout:
            if lock.acquire(False):
                return True
            else:
                cond.wait(timeout - current_time + start_time)
                current_time = time.time()
    return False

rawDescription: How to implement a Lock with a timeout in Python 2.7

description: Implement a Lock with a timeout in Python 2.7


code:
from Tkinter import *

root = Tk()

mytext = "Here_your very long text"

scrbar = Scrollbar(root, orient=VERTICAL)
scrbar.pack(side=RIGHT,fill=Y)

text = Text(root, width=80, height=10, state=NORMAL, background="white", foreground="black")
text.insert(INSERT, mytext)
text['state'] = DISABLED
text.pack()

text['yscrollcommand'] = scrbar.set
scrbar['command'] = text.yview

root.title("Matrix References")
root.mainloop()

rawDescription: python scroll workaround

description: Python scroll workaround


code:
range_expr = 'C:C'

for row in ws.iter_rows(row_offset=4):
    '''do things'''

rawDescription: worksheet.iter_rows() not pulling any data from spreadsheet

description: Worksheet.iter_rows() not pulling any data from spreadsheet


code:
mydll.PrintArray.restype = None
mydll.PrintArray(px)

rawDescription: ctypes outputting unknown value at end of correct values

description: Ctypes outputting unknown value at end of correct values


code:
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.proto import rfc1902
cmdgen.CommandGenerator().setCmd(
    cmdgen.CommunityData('my-agent', 'public', 1),
    cmdgen.UdpTransportTarget(('192.168.0.1', 161)),
    ((1,3,6,1,2,1,69,1,1,3,0), rfc1902.Integer(1))
)

rawDescription: Change my PC IP programmatically

description: Change my PC IP programmatically


code:
while inner_counter < len(inner_copy) and outer_counter < len(outer_copy):
    key = min(inner_copy[inner_index][inner_join_index],
              outer_copy[outer_index][outer_join_index])
    inner_group = []
    while inner_index < len(inner) and key == inner_copy[inner_index][inner_join_index]:
        inner_group.append(inner_copy[inner_index])
        inner_index += 1
    outer_group = []
    while outer_index < len(outer) and key == outer_copy[outer_index][outer_join_index]:
        outer_group.append(outer_copy[outer_index])
        outer_index += 1
    # Here you can handle left or right join by replacing an
    # empty group with a group of one empty row (None,)*len(row)
    for i in inner_group:
        for o in outer_group:
            yield i + o

rawDescription: Sort-Merge-Join Algorithm in Python

description: Sort-Merge-Join Algorithm in Python


code:
x = re.search("sub(\d+)\.domain\.com\/(\d+)","sub123.domain.com/546").groups()
url = "%s blah blah %s" % x

rawDescription: Regular Expression Match/Replace

description: Regular Expression Match/Replace


code:
found = None
for i,s in enumerate(lines):
  if substr in s:
    found = i
    break

if found:
  lines = lines[:found-1] + lines[found+2:]

rawDescription: python delete next and previous rows from textfile. Based on sample

description: Python delete next and previous rows from textfile. Based on sample


rawDescription: Python sequence naming convention

description: Python sequence naming convention


code:
labels = {}
for name in ("one", "two", "three"):
    labels[name] = tk.Label(..., text=name)
    labels[name].pack(...)

rawDescription: Clear the contents of a window and replace them with new contents?


code:
e = evince.View()
docmodel = evince.DocumentModel()
doc = evince.document_factory_get_document('file:///path/to/file/example.pdf')
docmodel.set_document(doc)
e.set_model(model)

rawDescription: Simple "Hello-World" program for python-evince


code:
class Thing():
    def __init__(self, summary=False):
        if summary:
            self.summary = "summary"
            self._whole = None
        else:
            self._whole = "wholething"

    @property
    def whole(self):
        if self._whole: return self._whole
        else:
            self.__init__()
            return self._whole

rawDescription: Mutate an object into an instance of one its subclasses


rawDescription: Selenium-webdriver count tables array

description: Selenium-webdriver count tables array


code:
def get_form(self, request, obj=None, **kwargs):
    form = super(orderAdmin,self).get_form(request,obj,**kwargs)
    autoselect_fields_check_can_add(form,self.model,request.user)
    return form

rawDescription: django ajax select add button

description: Django ajax select add button


code:
import csv
with open('test.txt','r') as infile:
    column23 = [ cols[1:3] for cols in csv.reader(infile, delimiter="\t") ]

rawDescription: How to cut 2nd and 3rd column out of a textfile? python

description: Cut 2nd and 3rd column out of a textfile? python


code:
# rest of file as before
setup(
      ext_modules = cythonize("example.pyx",
                              working="build"))

rawDescription: Specify cython output file

description: Specify cython output file


code:
print('E\xe9ntalige affiche in Halle !!')
'E\xe9ntalige affiche in Halle !!'.encode('utf8')
print('E\xe9ntalige affiche in Halle !!'.encode('utf8').decode('latin1'))

rawDescription: Python CSV writer with utf-8 code formats


code:
import time

x = 210513
c = time.clock()
print("Your computer just went through {} integers to find 7!".format(x))
print("Your computer just took {0:.20f} seconds to run!".format(c))
print("Your computer took {0:.20f} seconds per integer!".format(c / x))

rawDescription: How do I get rid of scientific notation and covert to a floating number in Python?

description: Get rid of scientific notation and covert to a floating number in Python


code:
class Rectangle:
    # Other definitions required here
    def overlaps(self, otherRectangle):
        return otherRectangle.colliderect(Rect(self.x, self.y, self.height, self.width))

r_1 = Rectangle()
r_2 = Rectangle()

print(r_1.overlaps(r_2))

rawDescription: Python Pygame Call Function

description: Python Pygame Call Function


code: next(i for (i, e) in enumerate("aaaaaxcbaa") if e != "a")

rawDescription: Python: index of first non-matching character?


code:
def pruneLeaves(self,obj):
    if isinstance(obj, dict):
        isLeaf = True
        for key in obj.keys():
            if key=='children':
                isLeaf = False
                if self.pruneLeaves(obj[key]): del obj[key]
        return isLeaf

    elif isinstance(obj, list) :
        leaves = []
        for (index, element) in enumerate(obj):
          if self.pruneLeaves(element): leaves.append(index)
        leaves.reverse()
        for index in leaves: obj.pop(index)
        return not bool(obj)
    else:  # String values look like attributes in your dict, so never prune them
        return False

rawDescription: How to delete keys in a nested dictionary of lists based on the values

description: Delete keys in a nested dictionary of lists based on the values


code:
class Parent(Base):
    __tablename__ = "Parent"
    id = Column(Integer, primary_key=True)
    first = Column("First", Integer, ForeignKey('Child.Ex1'))
    second = Column("Second", Integer, ForeignKey('Child.Ex2'))

    first_child = relationship("Child", primaryjoin="Parent.first==Child.ex1")
    second_child = relationship("Child", primaryjoin="Parent.second==Child.ex2")

class Child(Base):
    __tablename__ = "Child"
    id = Column(Integer, primary_key=True)
    ex1 = Column("Ex1", Integer)
    ex2 = Column("Ex2", Integer)

rawDescription: How to map multiple foreign keys to the same parent in SQLAlchemy?

description: Map multiple foreign keys to the same parent in SQLAlchemy


code:
def parse_page1(self, response):
    item = MyItem()
    item['main_url'] = response.url
    # parse response and populate item as required
    request = Request("http://www.example.com/some_page.html",
                      callback=self.parse_page2)
    request.meta['item'] = item
    return request

def parse_page2(self, response):
    item = response.meta['item']
    # parse response and populate item as required
    item['other_url'] = response.url
    return item

rawDescription: Scrapy: Item details on 3 different pages


code:
import numpy as np
np.random.seed(1)

df = sc.parallelize([
    (int(x), ) for x in np.random.randint(50, size=10000)
]).toDF(["x"])

cnts = df.groupBy("x").count()
mode = cnts.join(
    cnts.agg(max("count").alias("max_")), col("count") == col("max_")
).limit(1).select("x")
mode.first()[0]
## 0

rawDescription: Calculate the mode of a PySpark DataFrame column?


rawDescription: matplotlib.pyplot.imshow: removing white space within plots when using attributes "sharex" and "sharey"

description: Matplotlib.pyplot.imshow: removing white space within plots when using attributes "sharex" and "sharey"


code:
def func(rawData):
    sum = 0
    for i in rawData[::-1]:
        sum += i
        sum <<= 8

    sum >>= 8
    return sum

rawDescription: How to turn variable length bytes(less than 8) to long long int faster in python3?

description: Turn variable length bytes(less than 8) to long long int faster in python3


code:
ax = df[[1,2]].plot(subplots=True, layout=(1,2), ylim=[0,40])

for axe in ax[0]:
    axe.plot(df.index, df[0], label=0)

rawDescription: Plotting DataFrame with column in all subplots


rawDescription: A big and ever-growing table in my Django app needs a better performance strategy


rawDescription: Django models and Python properties

description: Django models and Python properties


code:
class A(object):
    def __init__(self):
        self.greet()
    def greet(self):
        print('Hello from A')

class B(self):
    def __init__(self, name):
        super(B, self).__init__()
        self.name = name
    def greet(self):
        print('Hello from B', self.name)

rawDescription: Is it bad form to call an instance method from within that instance's __init__ method?


code: variety = each.get('action', {}).get('hacking', {}).get('variety', {})

rawDescription: Pythonic way to access keys of sub dicts


rawDescription: Why does S3 (using with boto and django-storages) give signed url even for public files?


code:
#!/usr/bin/env python
import numpy as np
from vtk.util import numpy_support as VN
from matplotlib import pyplot as plt
import vtk

def readVTK(filename):
    #read the vtk file with an unstructured grid
    reader = vtk.vtkUnstructuredGridReader()
    reader.SetFileName(filename)
    reader.ReadAllVectorsOn()
    reader.ReadAllScalarsOn()
    reader.Update()
    return reader

def createLine(p1,p2,numPoints):
    # Create the line along which you want to sample
    line = vtk.vtkLineSource()
    line.SetResolution(numPoints)
    line.SetPoint1(p1)
    line.SetPoint2(p2)
    line.Update()
    return line

def probeOverLine(line,reader):
    #Interpolate the data from the VTK-file on the created line.
    data = reader.GetOutput()
    # vtkProbeFilter, the probe line is the input, and the underlying dataset is the source.
    probe = vtk.vtkProbeFilter()
    probe.SetInputConnection(line.GetOutputPort())
    probe.SetSource(data)
    probe.Update()
    #get the data from the VTK-object (probe) to an numpy array
    q=VN.vtk_to_numpy(probe.GetOutput().GetPointData().GetArray('U'))
    numPoints = probe.GetOutput().GetNumberOfPoints() # get the number of points on the line
    #intialise the points on the line
    x = np.zeros(numPoints)
    y = np.zeros(numPoints)
    z = np.zeros(numPoints)
    points = np.zeros((numPoints , 3))
    #get the coordinates of the points on the line
    for i in range(numPoints):
        x[i],y[i],z[i] = probe.GetOutput().GetPoint(i)
        points[i,0]=x[i]
        points[i,1]=y[i]
        points[i,2]=z[i]
    return points,q

def setZeroToNaN(array):
    # In case zero-values in the data, these are set to NaN.
    array[array==0]=np.nan
    return array

#Define the filename of VTK file
filename='a-VTK-file.vtk'

#Set the points between which the line is constructed.
p1=[0.0,-0.1,0.0]
p2=[0.0,-0.1,1.0]

#Define the numer of interpolation points
numPoints=100

reader = readVTK(filename) # read the VTKfile
line=createLine(p1,p2,numPoints) # Create the line
points,U =  probeOverLine(line,reader) # interpolate the data over the line

U = setZeroToNaN(U) # Set the zero's to NaN's
plt.plot(points[:,2],U[:,0]) #plot the data
plt.show()

rawDescription: Probing/sampling/interpolating VTK data using python TVTK or MayaVi


code:
fig = plt.figure()
ax = fig.add_axes([.1,.1,.8,.8]) # main axes
colors=['red','blue']
for key  in Xpr: #Xpr holds my data
    #skipping over what I don't want to plot
    if not key[0] == '5': continue
    if key[1] == '0': continue
    if key[1] == 'a': continue
    x = Xpr[key]
    y = Ypr[key] #Ypr holds the Y axis and is created when Xpr is created
    ax.scatter(x,y,color=colors[count],marker='.',label=key)
    count += 1

ax.set_xlabel(r'$z/\mu$')
ax.set_ylabel(r'$\rho(z)$')
ax.set_xlim(0,10)
leg = ax.legend()

#Now I wish to create the inset
ax_inset=fig.add_axes([0.7,0.7,0.3,0.3])
count =0
for key  in Xpr: #Xpr holds my data
    if not key[0] == '5': continue
    if key[1] == '0': continue
    if key[1] == 'a': continue
    x = Xpr[key]
    y = Ypr[key]
    ax_inset.plot(x,y,color=colors[count],label=key)
    count +=1

ax_inset.legend()

rawDescription: creating inset in matplot lib

description: Creating inset in matplot lib


code:
def triangle(n):
   for x in range(n):
        print ('*'*x)
   for x in range(n):
        print ('*'*n)
        n -= 1

height = int(input("Enter an odd number greater than 4: "))

triangle(height)

rawDescription: How to combine these two functions in python

description: Combine these two functions in python


code:
def add_renderer_globals(event):
    request, context = event['request'], event['context']
    event['user'] = authenticated_userid(request)

rawDescription: Username available in all templates

description: Username available in all templates


code:
from werkzeug.contrib.cache import MemcachedCache
cache = MemcachedCache(['127.0.0.1:11211'])

def get_my_item():
    rv = cache.get('my-item')
    if rv is None:
        rv = calculate_value()
        cache.set('my-item', rv, timeout=5 * 60)
    return rv

rawDescription: Storing simple key value pairs with Flask Cache and memcached


code:
from google.appengine.ext import ndb

class _Foo(ndb.Model):
  message = ndb.StringProperty()
  emailid = ndb.StringProperty(indexed=True)
  date = ndb.DateTimeProperty(auto_now_add=True)

  @classmethod
  def query_book(cls,key):
    return cls.query(ancestor=key).order(-cls.date)

key = ndb.Key(_Foo, '1')
message = """class asd
{
public void fun()
{
    printf ("hello world!!!");

}

}    """
f = _Foo(key=key)

f.message = message
f.put()

assert key.get().message == message  # no error here, means they are equal

rawDescription: Semi-colon terminates storing string to datastore


code:
mylist='d.complex.1\n24\n25\n67\n123\n764\nd.complex.200\n23\n54\n35\n64\nd.complex.302'.split("\n")
res=[]
for line in mylist:
 if line.startswith("d.complex"):
  res.append([])
 res[-1].append(line)

res

rawDescription: Splitting list in python

description: Splitting list in python


code:
from sqlalchemy.sql.expression import bindparam
stmt = addresses.update().\
    where(addresses.c.id == bindparam('_id')).\
    values({
        'user_id': bindparam('user_id'),
        'email_address': bindparam('email_address'),
    })

conn.execute(stmt, [
    {'user_id': 1, 'email_address' : 'jack@yahoo.com', '_id':1},
    {'user_id': 1, 'email_address' : 'jack@msn.com', '_id':2},
    {'user_id': 2, 'email_address' : 'www@www.org', '_id':3},
    {'user_id': 2, 'email_address' : 'wendy@aol.com', '_id':4},
])

rawDescription: Bulk update in SQLAlchemy Core using WHERE


code:
__author__ = 'Johan'
import optparse
from socket import *

def connScan(tgtHost, tgtPort):
    try:
        connSkt = socket(AF_INET, SOCK_STREAM)
        connSkt.connect((tgtHost, tgtPort))
        connSkt.send('ViolentPython\r\n')
        results = connSkt.recv(100)
        print('[+]%d/tcp open'% tgtPort)
        print('[+] ' + str(results))
        connSkt.close()

    except:
        print('[-]%d/tcp closed'% tgtPort)

def portScan(tgtHost, tgtPorts):
    try:
        tgtIp = gethostbyname(tgtHost)
    except:
        print ('[-] Can not resolve '': Unknown host' % tgtHost)
        return
    try:
        tgtName = gethostbyaddr(tgtIp)
        print('\n[+] Scan Results for: ' + tgtName[0])
    except:
        print('\n[+] Scan Results for: ' + tgtIp.
            setdefaulttimeout(1))
        for tgtPort in tgtPorts:
            print ('Scanning Port ' + tgtPort)
            connScan(tgtHost. int(tgtPort))

def main():

    parser = optparse.OptionParser('usage%prog ' + \
        '-H <target host> -p <target port>')

    parser.add_option('-H', dest='tgtHost', type=str, \
        help='specify target host')
    parser.add_option('-p', dest='tgtPort', type='int', \
                      help='specify target port[s] separated by comma')
    (options, args) = parser.parse_args()
    tgtHost = options.tgtHost
    tgtPorts = options.tgtPort
    if(tgtHost is None) | (tgtPorts[0] is None):
        print('[-] You must specify a target host and port[s]')
        exit(0)
        portScan(tgtHost, tgtPorts)

if __name__== '__main__':
    main()

rawDescription: python program will not execute eventhoug no errors

description: Python program will not execute eventhoug no errors


code:
TYPE_CHOICES = (
  ('equation', 'equation'),
  ('text', 'text'),
  ('image', 'image'),
  ('table', 'table')
)

type = models.CharField(choices=TYPE_CHOICES)

rawDescription: How to present some combination of text, images, equations in Django?

description: Present some combination of text, images, equations in Django


code:
for i in range(200):
    matrix = complex_calculation()
    plt.set_cmap("gray")
    plt.imshow(matrix)
    plt.savefig("frame{0}.png".format(i))
    plt.clf()

rawDescription: pyplot: really slow creating heatmaps

description: Pyplot: really slow creating heatmaps


code:
import os

root = '/foo/'

for directory, subdirectories, files in os.walk(root):
  for file in files:
     if os.path.splitext(file)[-1].lower() == '.sh':
       os.system('sh ' + os.path.join(directory, file))

rawDescription: Python, step through folders (to run scripts)


code:
import numpy as np
from odeintw import odeintw

def right_part(rho, t, w_p):
    hamiltonian = (1. / 2) * np.array(
        [[0.1, 0.01, 1.0 / 2.0 * np.sin(t * w_p)],
        [0.01, 0.0, 0.0],
        [1.0 / 2.0 * np.sin(t * w_p), 0.0, 0.0]],
        dtype=np.complex128)
    return (np.dot(hamiltonian, rho) - np.dot(rho, hamiltonian)) / (1j)

psi_init = np.array([[1.0, 0.0, 0.0],
                     [0.0, 0.0, 0.0],
                     [0.0, 0.0, 0.0]], dtype=np.complex128)

t = np.linspace(0, 10, 101)
sol = odeintw(right_part, psi_init, t, args=(0.25,))

rawDescription: Solve ode in python with complex matrix as initial value


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

x = [datetime.datetime(2010, 12, 1, 10, 0),
    datetime.datetime(2011, 1, 4, 9, 0),
    datetime.datetime(2011, 5, 5, 9, 0)]
y = [4, 9, 2]

ax = plt.subplot(111)
ax.bar(x, y, width=10)
ax.xaxis_date()

plt.show()

rawDescription: matplotlib bar chart with dates

description: Matplotlib bar chart with dates


code:
keys = ['RemoteService', 'RemoteApi']
values = 'Weather:getWeather'.split(':')
service_metrics = dict(zip(keys, values))

rawDescription: Python 2 member list to dict

description: Python 2 member list to dict


code:
def inner_subplots_adjust(axes, xmargin=0.1, ymargin = 0.1):
    xmin, xmax = axes.get_xbound()
    ymin, ymax = axes.get_ybound()
    xscale = 1 + xmargin
    yscale = 1 + ymargin
    axes.set_xbound((xmin*xscale, xmax*xscale))
    axes.set_ybound((ymin*yscale, ymax*yscale))

rawDescription: Python: Add x-y margins automatically with autoscale (pyplot)


rawDescription: Is it possible to introspect actual attributes/methods of an object which overrides `__dir__` and `__getattribute__`?


code:
article_count = len(articles)
output = "There are {} articles.".format(article_count)

rawDescription: What am I doing wrong with my function within this django view?


code:
from scipy.stats import norm
from scipy import sqrt
import matplotlib.pyplot as plt
def Euler_disc(S0, mu, sigma, T, n):
    dt = ((float(T)/n))
    for i in range(0, 10):
        times = [0]
        stocks = [S0]
        for x in range(0, n):
            times.append(times[x] + dt)
            stocks.append(stocks[x] + mu * stocks[x] * dt \
            + sigma * stocks[x] * sqrt(dt) * norm.rvs(0, 1, 1))
        plt.plot(times, stocks)

rawDescription: plotting multiple graphs in python onto one image

description: Plotting multiple graphs in python onto one image


code: re.findall('CREATE TABLE[^;]+;', s)

rawDescription: Multiline python regex fails

description: Multiline python regex fails


code:
class CreateServer(ModelForm):
    def __init__(self, g, *args, **kwargs):
        super(CreateServer, self).__init__(*args, **kwargs)

        if g.boolean_clients:
            self.fields['clients'].queryset = Clients.objects.filter(game=g)
        else:
            self.fields.pop('clients')

    class Meta:
        model = Server
        queryset = Server.objects.filter()
        fields = ['hostname', 'clients', 'map']

rawDescription: How not to display a field in form if the boolean field in database is False


code:
class NewProtocol(Packet):
     def __init__(self, _pkt="", post_transform=None, _internal=0, _underlayer=None, **fields):
          self.name = "myNewAwesomeProto"
          if _pkt != "":
               global frameSize
               frameSize = len(_pkt)
               fields_desc=[
                    BitField("startingField", None, 8),
                    BitField("payload", None, (frameSize - (8+2))*8),
                    BitField("endingField", None, 2*8)
               ]
          super(NewProtocol, self).__init__(_pkt, post_transform, _internal, _underlayer)

rawDescription: creating new protocol in scapy with fields depending on the packet total length

description: Creating new protocol in scapy with fields depending on the packet total length


code:
from functools import wraps

def recfun(f):
    @wraps(f)
    def _f(*a, **kwa): return f(_f, *a, **kwa)
    return _f

@recfun
# it's a decorator, so a separate class+method don't need to be defined
# for each function and the class does not need to be instantiated,
# as with Alex Hall's answer
def fact(self, n):
    if n > 0:
        return n * self(n-1)  # doesn't need to be self(self, n-1),
                              # as with lkraider's answer
    else:
        return 1

print(fact(10))  # works, as opposed to dursk's answer

rawDescription: Python - can function call itself without explicitly using name?


code:
import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)

rawDescription: Editing the date formatting of x-axis tick labels in matplotlib


code:
from collections import namedtuple

class Profile(namedtuple("Profile", "name")):
    def __init__(self, name):
        # don't set self.name, it's already set!
        self.friends = set({})
        self.statuses = list([])

    # ... and all the rest the same.  Only the base class changes.

rawDescription: typecast classes in python: how?

description: Typecast classes in python: how


code:
from PIL.ImageQt import ImageQt
image2 = Image.open('./Images/Cache/Cache.png')
qimage = ImageQt(image2)
pixmap = QtGui.QPixmap.fromImage(qimage)

rawDescription: QPixmap(): argument 1 has unexpected type 'PngImageFile'


code:
class TicketAdmin(admin.ModelAdmin):
    ...
    def has_add_permission(self, request):
        return request.user.groups.filter(name='Developers').exists()

    def has_change_permission(self, request, obj=None):
        return request.user.groups.filter(name='Developers').exists()

    def has_delete_permission(self, request, obj=None):
        return request.user.groups.filter(name='Developers').exists()

rawDescription: django admin - group permissions to edit or view models

description: Django admin - group permissions to edit or view models


rawDescription: Greedy match with negative lookahead in a regular expression


code:
from scapy.all import *
import sys
from cStringIO import StringIO
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
pkt = DNS()
pkt.show()
sys.stdout = old_stdout
mystdout.getvalue()

rawDescription: Converting a DNS packet to a string using Scapy


code:
B = np.ndarray(shape=(10, 20), dtype=A.dtype, buffer=A, offset=880,
               strides=(8, 800))

rawDescription: Get a view of a ndarray satisfying certain shape and strides constraint


code:
def find_primes(start_or_stop, stop_or_none=None, primes=None):
    """
    find_primes([start], stop, [primes])
    """
    # ^ Communicate the semantics of the signature by the docstring,
    # like `range` does.
    if primes is None:
        primes = []
    if stop_or_none is None:
        start, stop = 1, start_or_stop
    else:
        start, stop = start_or_stop, stop_or_none

rawDescription: Pass a default value to a function before a required value


rawDescription: Encoding ☺ as IBM-437 fails while other valid characters like é succeed


code:
def copypart(src,dest,start,length,bufsize=1024*1024):
    with open(src,'rb') as f1:
        f1.seek(start)
        with open(dest,'wb') as f2:
            while length:
                chunk = min(bufsize,length)
                data = f1.read(chunk)
                f2.write(data)
                length -= chunk

if __name__ == '__main__':
    GIG = 2**30
    copypart('test.bin','test2.bin',1*GIG,8*GIG)

rawDescription: Python: slicing a very large binary file


code:
from collections import defaultdict

d = defaultdict(list)

# Every time you try to access the value of a key that isn't in the dict yet,
# d will call list with no arguments (producing an empty list),
# store the result as the new value, and give you that.

for line in myDatasetFile:
    d[int(line[-1])].append([line[2],float(line[3])])

rawDescription: A "pythonic" strategy to check whether a key already exists in a dictionary


code:
import re

xml = re.search(r"<(\w+).*</\1>", console_output, flags=re.DOTALL).group()

rawDescription: Can I get lxml to ignore non-XML content before and after the root tag?

description: Get lxml to ignore non-XML content before and after the root tag


code:
fig, ax = plt.subplots()
df[[0, 1, 2, 3]].plot(kind='box', ax=ax)
ax2 = ax.twinx()
ax2.boxplot(df[4], positions=[4])
ax.set_xlim(0, 5)

rawDescription: Pandas secondary y axis for boxplots

description: Pandas secondary y axis for boxplots


code:
pdf_im = pyPdf.PdfFileReader(file('multi_page.pdf', "rb"))
npage = pdf_im.getNumPages()
for p in npage:
    im = PythonMagick.Image('multi_page.pdf['+ str(p) +']')
    im.write('file_out-' + str(p)+ '.png')

rawDescription: How to handle multi-page images in PythonMagick?

description: Handle multi-page images in PythonMagick


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

plt.plot(range(10), marker='o', ms=20, clip_on=False)

axes = plt.gca()
axes.spines['right'].set_color('none')
axes.spines['top'].set_color('none')
axes.xaxis.set_ticks_position('bottom')
axes.spines['bottom'].set_position(('axes', -0.05))
axes.yaxis.set_ticks_position('left')
axes.spines['left'].set_position(('axes', -0.05))
axes.tick_params(axis='x', direction='out')
axes.tick_params(axis='y', direction='out')

plt.show()

rawDescription: Fixing matplotlib plot

description: Fixing matplotlib plot


rawDescription: pandas indexing using multiple isin clauses

description: Pandas indexing using multiple isin clauses


code:
gg.bind('myprefix1', ns1)
gg.bind('myprefix2', ns1)

rawDescription: Force rdflib to define a namespace

description: Force rdflib to define a namespace


code:
def iter_email(self):
    for k in sorted(self.fields.keys()):
        if k.startswith('email_'):
            yield self[k]

rawDescription: Django "Instance" Form Fields Not Rendering


code:
def_ids = ['165153','165239']
Maxbs = ['3900','1800']
for def_id,Maxb in zip (def_ids, Maxbs):
    cards = func.search(definitionId=def_id, maxb=Maxb)
    for card in cards:
        print ('{0} for {1}'.format(card.assetId, card.buyNowPrice))

rawDescription: Iterating over two lists

description: Iterating over two lists


code:
from selenium import webdriver

p = webdriver.FirefoxProfile()
p.set_preference("webdriver.log.file", "/tmp/firefox_console")
driver = webdriver.Firefox(p)

rawDescription: How to save the logs generated using selenium with python

description: Save the logs generated using selenium with python


code:
result = df.groupby(['ID'])['t'].agg(['min', 'max', 'count'])
result['elapsed'] = result['max']-result['min']
result['1/f'] = result['elapsed']/result['count']
result = result[['elapsed','count', '1/f']].rename(columns={'count':'visits'})
result = result.reset_index()
result

rawDescription: Derived/metadata about logs in pandas

description: Derived/metadata about logs in pandas


code:
def askquestion(title=None, message=None, **options):
    "Ask a question"
    return _show(title, message, QUESTION, YESNO, **options)

def askyesno(title=None, message=None, **options):
    "Ask a question; return true if the answer is yes"
    s = _show(title, message, QUESTION, YESNO, **options)
    return s == YES

rawDescription: Python Tkinter messagebox difference between askquestion and askyesno


code:
from sympy import *

x, y = symbols("x y")
f = (x ** 2 + y ** 2)
res = integrate(f, (y, 20, x-2), (x, 22, 30))

rawDescription: Double integral with variable boundaries in python Scipy + sympy (?)


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

x = np.arange(0, 4)
y = np.arange(0, 4)

# vectors x coordinate values
fx = (0, 1, 1, 2)
# vectors y coordinate values
fy = (1, 0, 1, 2)

Q = plt.quiver(x, y, fx, fy)
plt.xlim(-1, 4)
plt.ylim(-1, 4)

plt.show()

rawDescription: Use quiver to plot a 2D vector map

description: Use quiver to plot a 2D vector map


code:
class PersonnelManager(models.Manager):
    def create(self, username, email, phone, address, **kwargs):
        user = User.objects.get_or_create(username=username, email=email)
        return super(PersonnelManager, self).create(user=user, phone=phone, address=address, **kwargs)

class Personnel(models.Model):
    ...
    objects = PersonnelManager()

rawDescription: Manager for a user profile to create and delete both user and the profile


rawDescription: raw_input based integer to binary program

description: Raw_input based integer to binary program


code:
class Columns:
    pass

def f(row_number):
    c = Columns()
    c.power = retrieve_avg_power(row_number) * 2.5
    c.speed = math.sqrt(power) / 2
    return c.__dict__

rawDescription: Alternative to locals() in printing a table with a header


code:
with open("tmp.json") as json_file:
    json_data = json.load(json_file)
    for i, data_item in enumerate(json_data['data']):
        fname = 'data_%s' % i
        with open(fname, 'w') as outfile:
            json.dump(data_item, outfile)

rawDescription: Python program to extract data from JSON files


code:
s = 'hello'
s.rfind('l')

rawDescription: Find String index from last in Python

description: Find String index from last in Python


code:
class MetaModel(type):
    def __new__(cls, name, bases, attrs):
        attrs['_restricted_fields'] = [attrs.get('has_many')]
        return type.__new__(cls, name, bases, attrs)

class Model(object):
    __metaclass__ = MetaModel
    has_many = None
    def __new__(cls, *args, **kwargs):
        instance = object.__new__(cls, *args, **kwargs)
        instance.instance_var = ['spam']
        return instance

class SubModel(Model):
    has_many = True
    def __init__(self):
        # No super call here.
        self.attr = 'eggs'

s = SubModel()
assert s._restricted_fields == [True]  # Added by MetaModel
assert s.instance_var == ['spam']  # Added by Model.__new__
assert s.attr == 'eggs'  # Added by __init__

# instance_var is added per instance.
assert SubModel().instance_var is not SubModel().instance_var

rawDescription: Set instance variables from metaclass

description: Set instance variables from metaclass


code:
n = random.randint(1, 8)
res = random.randint(1, 25)

if n == 1: pass
elif 2<=n<=5: res += 25
elif 6<=n<=7: res += 50
else: res +=75

return res

rawDescription: python generating random number with sub-ranges

description: Python generating random number with sub-ranges


code:
loga = [(912, "Message A1") , (1000, "Message A2") , (988, "Message A3") , (1012, "Message A4") , (1002, "Message A5")]

logb = [(926, "Message B1") , (1008, "Message B2") , (996, "Message B3") , (1019, "Message B4") , (1100, "Message B5")]

logc = [(1056,"Message C1") , (1033, "Message C2") , (999, "Message C3") , (1054, "Message C4") , (1086, "Message C5")]

logs = [loga, logb, logc]
final=[]
for log in logs:
    for tup in log:
        final.append(tup[0])
lowest_number=min(int(x) for x in final)
return lowest_number

rawDescription: Python - Pulling lowest integer from a list and then "pop"ing it to another


code:
from django.conf.urls.i18n import i18n_patterns

urlpatterns += i18n_patterns('',
   url(r'^admin/', include(admin.site.urls)),
   #your urls
)

rawDescription: django i18n url setting

description: Django i18n url setting


code:
cmd = subprocess.Popen('ls', stdout=subprocess.PIPE)
cmd_out, cmd_err = cmd.communicate()

rawDescription: Can I have subprocess.call write the output of the call to a string?

description: Have subprocess.call write the output of the call to a string


code:
import xbmcgui
import xbmc
import os
import shutil

TARGETFOLDER = xbmc.translatePath(
    'special://home/userdata/addon_data/01'
    )
YESNOWINDOW = xbmcgui.Dialog().yesno(
    "This Will Delete a folder",
    "Click yes to delete",
    "Click No to exit")

if YESNOWINDOW:
    _MSG = None
    if os.path.exists(TARGETFOLDER):
        try:
            shutil.rmtree(TARGETFOLDER, ignore_errors=False)
            xbmc.executebuiltin("Notification(Folder has been deleted, All done,()")
            xbmc.executebuiltin("ActivateWindow(10000,return)")
        except OSError as rmerr:
            _MSG = ("Error with delete dir: {}".format(rmerr))
        except Exception as err:
            _MSG = ("Error with XBMC call: {}".format(err))
    else:
        _MSG = ("Folder {} does not appear to be a directory"
                .format(TARGETFOLDER))
    if _MSG:
        xbmc.executebuiltin("Notification({},()".format(_MSG)) # ***
        xbmc.executebuiltin("ActivateWindow(10000,return)")

rawDescription: Folder Missing But No confirmation

description: Folder Missing But No confirmation


code:
import dateutil.parser as parser
text = 'Thu, 16 Dec 2010 12:14:05 +0000'
date = (parser.parse(text))
print(date.isoformat())
# 2010-12-16T12:14:05+00:00

rawDescription: Python - Convert date to ISO 8601

description: Python - Convert date to ISO 8601


code: "my request url was {0}".format(request.get_full_path())

rawDescription: python string format calling a function

description: Python string format calling a function


code:
import os
import pandas as pd
directory_contents = os.listdir(your_directory)
experiment_files = [fn for fn in directory_contents if '.csv' in fn]
df = pd.DataFrame()

for filename in experiment_files:
    experiment_df = pd.read_csv(filename)
    experiment_df['experiment_name'] = file_name
    df = pd.concat([df,experiment_df])

rawDescription: Processing Experimential Measurements in Python


code: li = [[0,0] for i in range(players)]

rawDescription: List updates in two places

description: List updates in two places


code:
def defaultsAndArbitrary(arr, *modifiers, **kwargs):
    example1 = kwargs.get('example1',True)
    example2 = kwargs.get('example2',13)

rawDescription: How to create a function with both default and arbitrary arguments

description: Create a function with both default and arbitrary arguments


code:
for i in xrange(1,101):
   name = 'folder_%03d' % (i)
   if not os.path.exists(name):
      os.mkdir(name)

rawDescription: Python - create directories that don't exist from list


code:
from distutils.core import setup, Extension

module1 = Extension('demo',
                    define_macros = [('MAJOR_VERSION', '1'),
                                     ('MINOR_VERSION', '0')],
                    include_dirs = ['/usr/local/include'],
                    libraries = ['tcl83'],
                    library_dirs = ['/usr/local/lib'],
                    sources = ['demo.c'])

setup (name = 'PackageName',
       version = '1.0',
       description = 'This is a demo package',
       author = 'Martin v. Loewis',
       author_email = 'martin@v.loewis.de',
       url = 'http://docs.python.org/extending/building',
       long_description = '''
This is really just a demo package.
''',
       ext_modules = [module1])

rawDescription: Accessing c++ class from python

description: Accessing c++ class from python


code:
def tile1Func():
    return "tile 1"

def tile2Func():
    return "tile 2"

tileTypes = {
    1: {
        "color": "red",
        "func": tile1Func
    },
    2: {
        "color": "green",
        "func": tile2Func
    }
}

class tile():
    def __init__(self, type):
        self.color = tileTypes[type]["color"]
        self.func = tileTypes[type]["func"]

t1 = tile(1)
print("color: " + t1.color + ", name: " + t1.func())

rawDescription: Python dynamic methods

description: Python dynamic methods


code:
import wx

class main(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Testing an app")
        self.Maximize()
        panel = wx.Panel(self, -1)
        textList = wx.StaticText(panel, -1, "Text1")
        self.listBox = wx.ListBox(panel, -1, choices=["Some large text", "another large text"], size=(400, 400))
        text = wx.StaticText(panel, -1, "Content")
        self.text = wx.TextCtrl(panel, -1, "", style=wx.TE_READONLY|wx.TE_MULTILINE, size=(500, 500))

        listbox = wx.BoxSizer(wx.HORIZONTAL)
        listbox.Add(textList)
        listbox.Add(self.listBox)

        textbox = wx.BoxSizer(wx.HORIZONTAL)
        textbox.Add(text)
        textbox.Add(self.text)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(listbox)
        sizer.Add(textbox)
        panel.SetSizer(sizer)
  # Some stuff here...
if __name__ == "__main__":
    app = wx.App()
    frame = main().Show()
    app.MainLoop()

rawDescription: Shows WxPython widgets on the Screen

description: Shows WxPython widgets on the Screen


code:
new_list = readCountries()
def printCountry(name):
    lo, hi = 0, len(new_list) - 1
    while lo <= hi:
        mid = lo + (hi - lo) // 2
        country = new_list[mid]
        test_name = country[0]
        if name > test_name:
            lo = mid + 1
        elif name < test_name:
            hi = mid - 1
        else:
            return country[0] + ", Area: " + str(country[1]) + ",    Population: " + str(country[2])
    return "Sorry Can not find " + str(name)

rawDescription: performing a Binary search with python

description: Performing a Binary search with python


code:
max_dict = {}

def keep_row(row):
    if row.calls > max_dict.get((row.ID, row.SerialNo), 0):
        max_dict[(row.ID, row.SerialNo)] = row.calls
        return True
    else:
        return False

Table1_mod = Table1[Table1.apply(keep_row, axis=1)]

rawDescription: Deleting a row based values of of a column using pandas


code:
y_interp = scipy.interpolate.interp1d(
    np.concatenate((np.array([0]), Misc)),
    np.concatenate((np.array([0]), Misc_Center))
)

new_vals = y_interp(np.random.rand(100))

rawDescription: Vectorizing a series of CDF samples in Python with NumPy


code:
from itertools import tee, izip
from collections import defaultdict

def pairwise(iterable): # recipe from itertools docs
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)
d = defaultdict(int)
phrase_words = ['red car', 'no lake', 'newjersey turnpike']
lines = ['i have a red car which i drove on newjersey',
         'turnpike. when i took exit 39 there was no',
         'lake. i drove my car on muddy roads which turned my red',
         'car into brown. driving on newjersey turnpike can be confusing.']

for line1, line2 in pairwise(lines):
    both_lines= ' '.join((line1, line2))
    for phrase in phrase_words:
        # counts phrases in first line and those that span to the next
        d[phrase] += both_lines.count(phrase) - line2.count(phrase)
for phrase in phrase_words:
    d[phrase] += line2.count(phrase) # otherwise last line is not searched

rawDescription: Python: String counting memory error

description: Python: String counting memory error


code:
def contact(request, sender=None, append_message=None, context=None):

   if not sender:
       sender = settings.DEFAULT_FROM_EMAIL  # i hope that you can access settings here

   # The context arg is a dictionary where you can put all the others argument and
   # you can use it like so :

   subj_tmpl = context.get('subj_tmpl', 'contato/subject.txt')
   # ....

rawDescription: Python function with too many arguments with default values, how to make it cleaner?


code: image = image.convert("RGBA")

rawDescription: Python PIL How do I convert 1 bit deep images to RGBA?


code:
usr_pts = 0
cmp_pts = 0

while (usr_pts < 5 and cmp_pts < 5):
    solved_word = False
    # set up word
    user_turn = False
    user_correct_guess = 0
    ai_correct_guess = 0
    while not solved_word:
        user_turn = not user_turn
        if user_turn:
            guess = play_user(...)
        else:
            guess = computer_play(...)
        # what ever accounting you need to do
        is_guess_in_word = test_guess_in_word(guess, ...)
        if is_guess_in_word:
            if user_turn:
                user_correct_guess += 1
            else:
                ai_correct_guess += 1
        solved_word = sort_out_if_word_solved(...)

    if user_correct_guess > ai_correct_guess:
        usr_pts += 1
    elif user_correct_guess < ai_correct_guess:
        cmp_pts +=1
    else:
        # a tie
        pass

rawDescription: python loops, 2 player game

description: Python loops, 2 player game


code:
import csv, sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("CREATE TABLE t (col1, col2);")

with open('data.csv','rb') as fin: # `with` statement available in 2.5+
    # csv.DictReader uses first line in file for column headings by default
    dr = csv.DictReader(fin) # comma is default delimiter
    to_db = [(i['col1'], i['col2']) for i in dr]

cur.executemany("INSERT INTO t (col1, col2) VALUES (?, ?);", to_db)
con.commit()

rawDescription: Importing a CSV file into a sqlite3 database table using Python


code:
def minmax(seq):

    def byTwos(seq):
        # yield values from sequence two at a time
        # if an odd number of values, just return
        # the last value twice (won't hurt minmax
        # evaluation)
        seq = iter(seq)
        while 1:
            last = next(seq)
            yield last,next(seq,last)

    seqByTwos = byTwos(seq)
    # initialize minval and maxval
    a,b = next(seqByTwos,(None,None))
    if a < b:
        minval,maxval = a,b
    else:
        minval,maxval = b,a

    # now walk the rest of the sequence
    for a,b in seqByTwos:
        if a < b:
            if a < minval:
                minval = a
            if b > maxval:
                maxval = b
        else:
            if b < minval:
                minval = b
            if a > maxval:
                maxval = a
    return minval, maxval

rawDescription: Why the maxmin divide and conquer implementation is slower than the others maxmin algorithms?


code:
winver = GetVersionEx()
maj,min,buildno,plat,csd = winver
version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF)
if hasattr(winver, "service_pack"):
    if winver.service_pack != "":
        csd = 'SP%s' % winver.service_pack_major
else:
    if csd[:13] == 'Service Pack ':
        csd = 'SP' + csd[13:]

if plat == VER_PLATFORM_WIN32_WINDOWS:
    regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
    # Try to guess the release name
    if maj == 4:
        if min == 0:
            release = '95'
        elif min == 10:
            release = '98'
        elif min == 90:
            release = 'Me'
        else:
            release = 'postMe'
    elif maj == 5:
        release = '2000'

elif plat == VER_PLATFORM_WIN32_NT:
    regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
    if maj <= 4:
        release = 'NT'
    elif maj == 5:
        if min == 0:
            release = '2000'
        elif min == 1:
            release = 'XP'
        elif min == 2:
            release = '2003Server'
        else:
            release = 'post2003'
    elif maj == 6:
        if hasattr(winver, "product_type"):
            product_type = winver.product_type
        else:
            product_type = VER_NT_WORKSTATION
            # Without an OSVERSIONINFOEX capable sys.getwindowsversion(),
            # or help from the registry, we cannot properly identify
            # non-workstation versions.
            try:
                key = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
                name, type = RegQueryValueEx(key, "ProductName")
                # Discard any type that isn't REG_SZ
                if type == REG_SZ and name.find("Server") != -1:
                    product_type = VER_NT_SERVER
            except WindowsError:
                # Use default of VER_NT_WORKSTATION
                pass

        if min == 0:
            if product_type == VER_NT_WORKSTATION:
                release = 'Vista'
            else:
                release = '2008Server'
        elif min == 1:
            if product_type == VER_NT_WORKSTATION:
                release = '7'
            else:
                release = '2008ServerR2'
        else:
            release = 'post2008Server'

else:
    if not release:
        # E.g. Win3.1 with win32s
        release = '%i.%i' % (maj,min)
    return release,version,csd,ptype

rawDescription: How can I be sure of the possible return values for platform.release()

description: Be sure of the possible return values for platform.release()


code:
sql = ('select field1, field2, field3, field4 '
       'from table '
       'where condition1=1 '
       'and condition2=2 ')

rawDescription: Python SQL query string formatting

description: Python SQL query string formatting


code:
def render(template_path, template_dict, debug=False):
  """Renders the template at the given path with the given dict of values."""
  t = load(template_path, debug)
  return t.render(Context(template_dict))

template_cache = {}
def load(path, debug=False):
  abspath = os.path.abspath(path)

  if not debug:
    template = template_cache.get(abspath, None) # <---- CACHING!
  else:
    template = None

  if not template:
    directory, file_name = os.path.split(abspath)
    ...

rawDescription: Caching pre-rendered templates with GAE Memcache API


code:
df = pd.DataFrame([dict1, dict2])
df

rawDescription: How to convert data in to a format suitable to be used for a multi-class classification task, using scikit-learn?

description: Convert data in to a format suitable to be used for a multi-class classification task, using scikit-learn


code:
# blog/models.py

class Blog(Model):
    owner = ForeignKey(User, related_name="blogs")
    name = Charfield()

class Post(Model):
    blog = ForeignKey(Blog, related_name="posts")
    #Other fields ...

class Comment(Model):
    post = ForeignKey(Post, related_name="comments")
    #Other fields ...

rawDescription: App as foreign key

description: App as foreign key


code:
import pygame.font

font = pygame.font.Font(None, 36) # None can be a font file instead
text = font.render("Welcome to Earth", 1, (0, 0, 0))
# Determine the location that should be allocated for the text
text_box = text.get_rect(centerx=DISPLAYSURF.get_width()/2)
# Draw the text onto the background
background.blit(text, text_box)

rawDescription: Displaying text with pygame

description: Displaying text with pygame


rawDescription: Permalinks with Russian/Cyrillic news articles


code:
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        with open('test.pdf', 'rb') as f:
            self.set_header("Content-Type", 'application/pdf; charset="utf-8"')
            self.set_header("Content-Disposition", "attachment; filename=test.pdf")
            self.write(f.read())

rawDescription: How to handle MIME type in tornado?

description: Handle MIME type in tornado


code:
import re

def num_decimal_places(value):
    m = re.match(r"^[0-9]*\.([1-9]([0-9]*[1-9])?)0*$", value)
    return len(m.group(1)) if m is not None else 0

rawDescription: How to get number of decimal places

description: Get number of decimal places


code: from A1.models import M1

rawDescription: common models in django

description: Common models in django


code:
class GetRouteDriver(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    def get(self, request, username, origin, destination):
        origin_lat, origin_lng = origin.split(',')
        destination_lat, destination_lng = destination.split(',')

        url = 'https://maps.googleapis.com/maps/api/directions/json?origin=' + origin + '&destination=' + destination + '&key'+ GOOGLE_KEY
        request_data = urllib2.urlopen(url)
        #serialized_data = request_data.read()

        serialized_data = json.dumps( { 'ride_id': 1 , 'route': json.loads(request_data.read()) })
        route = json.loads(serialized_data)
        return Response( route, status=status.HTTP_200_OK )

rawDescription: How to add Variable to JSON Python Django

description: Add Variable to JSON Python Django


code: Data.Close.resample('W', how ='last')

rawDescription: pandas csv resampling not working

description: Pandas csv resampling not working


code:
from collections import defaultdict

game_dict = {}  # keyed by (game, player, round) tuple
game_player_ix = defaultdict(list)
game_round_ix = defaultdict(list)

def add_action(game, player, round):
    game_dict[(game, round, player)] = action # track the action in the main dict
    game_player_ix[(game, player)].append(round)  # keep an index for lookups by player
    game_round_ix[(game, round)].append(player) # another index for lookups by round

def get_all_player_actions(game, player):
    return (game_dict[(game,player,round)] for round in game_round_ix[(game, player)]) # iterator

def get_all_round_actions(game, round):
    return (game_dict[(game,player,round)] for player in game_player_ix[(game, round)]) # iterator

rawDescription: Alternative data structure needed for deeply nested dictionary/map situation


code:
def notify(s):
    print(s)

d = {"notify": notify}

d["notify"]("Hello, world!")

rawDescription: How to call a function based on list entry?

description: Call a function based on list entry


code:
res = urllib.urlopen("http://www.iana.org/assignments/language-subtag-registry" )
http_message = res.info()
full = http_message.type # 'text/plain'
main = http_message.maintype # 'text'

rawDescription: Python: How to get the Content-Type of an URL?


code:
...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

rawDescription: How to set the range of y-axis for a seaborn boxplot?

description: Set the range of y-axis for a seaborn boxplot


code:
import math
import random

def rand_multiple(fac, a, b):
    """Returns a random multiple of fac between a and b."""
    min_multi = math.ceil(float(a) / fac)
    max_multi = math.floor(float(b) / fac)
    return fac * random.randint(min_multi, max_multi)

rawDescription: Generate a random number in that falls into a multiple range


code:
class Page(BaseModel):
    raw_html = TextField(unique=True)

rawDescription: Which Field to choose for storing Raw HTML inside a Peewee Model


rawDescription: Multiplying tuples in Python

description: Multiplying tuples in Python


code: help(repr)

rawDescription: Generate variable definition code from runtime data structure


code:
import numpy as np

recordtype = np.dtype([('name', 'S24'),
                       ('ra', np.float32),
                       ('dec', np.float32),
                       ('z',np.float32),
                       ('rmag',np.float32),
                       ('rmag_error',np.float32),
                       ('gmag',np.float32),
                       ('gmag_error',np.float32)])

def ratodeg(string):
    hh, mm, ss = string.split()

    return (int(hh) * 15) + (int(mm) * 0.25) + (float(ss)  * 0.0042)

def dectodeg(string):
    return

qData = np.loadtxt("sample",
                   skiprows=1,
                   dtype=recordtype,
                   delimiter = '|',
                   usecols = (1, 2, 3, 4, 5, 6, 7, 8),
                   converters = {1:str,
                                 2:ratodeg,
                                 3:dectodeg})

rawDescription: Reading structured column data with numpy


code:
currentRow = 2
while 1:
    thisRow = worksheet.row_values(currentRow)

    if (thisRow[1] == ""):
        break

    username = thisRow[3] + "@obfuscated.com"
    personalExtension = thisRow[1]

    #email sending code goes here
    print(username, personalExtension)
    currentRow += 1

rawDescription: Pulling Data from a Live Google Sheet and Emailing It


code:
import pylab as plt

plt.imshow([[1,2,3],[4,5,6]])

cbar_options = {'extend':'both',
                'orientation':"horizontal",
                'shrink':0.75,
                'fraction':.10,
                'pad':.07}

cb1 = plt.colorbar(**cbar_options)
cb1.set_label('Increase in Black Carbon')

cb2 = plt.colorbar(**cbar_options)
cb2.set_label('Decrease in Black Carbon')

plt.show()

rawDescription: How can I shrink the area the colourbar takes up?

description: Shrink the area the colourbar takes up


code:
festivalCmd = '(SayText "%s")' % text.replace('"', '')
subprocess.Popen(['/usr/bin/festival', '-b', festivalCmd])

rawDescription: Python String Literal Inside Popen command


rawDescription: Python: reverse a string

description: Python: reverse a string


code:
string_values = 'abc|xyz|mno'.split('|')

for obj in queryset.iterator():
     writer.writerow([smart_str(obj.code)] + string_values)

rawDescription: How to print csv from list and string combination without delimiter of space?

description: Print csv from list and string combination without delimiter of space


rawDescription: Can a hashed password using BCrypt in Java be recognised by Python?


code:
pwok = 0
print ("You password must contain lower case and uppcase characters")
print ("It should also contain numbers as well")

while True:
    pw = input("Please enter a password to test: ")
    if pwok ==1:
        break
    caps = sum(1 for c in pw if c.isupper())
    lower = sum(1 for c in pw if c.islower())
    nums = sum(1 for c in pw if c.isnumeric())

    scr = ['weak', 'medium', 'strong']
    r = [caps, lower, nums]

    if len(pw) < 6:
        print("This password is too short please Re-Enter another password")
        continue # if you don't use continue all lines will be executed even if len < 6
    elif len(pw) > 12:
        print("This password is too long please Re-Enter another password")
        continue  # if you don't use continue all lines will be executed even if len > 12

    else:
        pwok = 1

    if caps >= 1:
         if lower >= 1:
              if nums >= 1:
                   print(scr[1])
              elif nums < 1:
                   print("your password is " + scr[1])
         elif lower < 1:
              print("your password strength is " + scr[1])
    elif caps < 1:
         print("your password strength is " + scr[1])
    if caps < 1:
         if lower < 1:
              if nums <1:
                  print(scr[3])

rawDescription: How do I loop this program in python?

description: Loop this program in python


code:
IPTCFormSet = modelformset_factory(IPTCForm)
formset = IPTCFormSet(queryset=IPTC.objects.all())

rawDescription: Why doesn't a formset provide values like a form in Django?


rawDescription: Meaning of using commas and underscores with Python assignment operator?


code:
import csv
from xlsxwriter.workbook import Workbook

workbook = Workbook("test.xlsx")
worksheet = workbook.add_worksheet("Raw_Data")

with open("C:\Console2\\csv.test",'r') as f:
    reader = csv.reader(f)
    for r, row in enumerate(reader):
        for c, col in enumerate(row):
            worksheet.write(r, c, col)

workbook.close()

rawDescription: csv to xlsx - when import its always blank?

description: Csv to xlsx - when import its always blank


code:
class Foo(object):
    pass

rawDescription: what does 'objects being subclassable' mean?

description: What does 'objects being subclassable' mean


code:
c.execute('''
CREATE TABLE Student (
    StudentID integer PRIMARY KEY,
    Forename text,
    Surname text,
    FormNumber text,
    YearGroup text,
    Date text,
    FormTutor text)''')

c.execute('''
CREATE TABLE Behaviour (
    BehaviourID integer PRIMARY KEY,
    BehaviourType text,
    BehaviourDescription text)''')

c.execute('''
CREATE table Incident (
    StudentID integer,
    BehaviourID integer,
    Date text,
    FOREIGN KEY(StudentID) REFERENCES Student(StudentID),
    FOREIGN KEY(BehaviourID) REFERENCES Behaviour(BehaviourID))''')

rawDescription: How do I make Student & Behaviour table link via Incident table?

description: Make Student & Behaviour table link via Incident table


code:
try: all
except NameError:
    def all(iterable):
        for value in iterable:
            if not value: return False
        return True

rawDescription: Can't call all() built-in function in IronPython


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

import csv

csvFile = 'myCSVfile.csv'
xmlFile = 'myXMLfile.xml'

csvData = csv.reader(open(csvFile))
xmlData = open(xmlFile, 'w')
xmlData.write('<?xml version="1.0" encoding="utf-8"?>' + "\n")
# there must be only one top-level tag
xmlData.write('<Catchment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">' + "\n")
xmlData.write('<CatchmentParamters>' + "\n")
rowNum = 0

for row in csvData:
    if rowNum == 0:
        tags = row
        # replace spaces w/ underscores in tag names
        for i in range(0, 2):
            tags[i] = tags[i].replace(' ', '_')

    else:
      for i in range(0, 2):
            xmlData.write('    ' + '<' + tags[i] + '>' \
                          + row[i] + '</' + tags[i] + '>' + "\n")

      xmlData.write('</CatchmentParameters>' + "\n")
      xmlData.write('<VegetationZone>' + "\n")
      xmlData.write('<VegetationZoneParameters>' + "\n")

      for i in range(2, 4):
            xmlData.write('    ' + '<' + tags[i] + '>' \
                          + row[i] + '</' + tags[i] + '>' + "\n")

      xmlData.write('</VegetationZoneParameters>' + "\n")
      xmlData.write('</VegetationZone>' + "\n")

    rowNum +=1

xmlData.write('</Catchment>' + "\n")
xmlData.close()

rawDescription: Converting CSV to XML

description: Converting CSV to XML


code: masterList = pd.Dataframe('GOOG/NYSE_' + nyseList['Ticker'].astype(str))

rawDescription: Downloading Quandl data to pandas using Quandl google finance dataset code tags


code:
import sys
p = subprocess.getoutput("'{}' ./file.py < input.txt".format(sys.executable))

rawDescription: Subprocess "python file.py" – how to ensure runs in python3?


code:
h = "#a7bd7a"
t = 167,189,122
"#%02x%02x%02x" % t                              # color tuple to hex string
[int(h[i:i+2], 16) for i in range(1, len(h), 2)] # hex string to color tuple

rawDescription: How to grab all the lines with readline function in python?

description: Grab all the lines with readline function in python


code:
data = np.core.records.fromrecords([[1.], [2.], [3.]],names=['Time'])
data
data['Time']

rawDescription: Numpy array - append named column

description: Numpy array - append named column


code:
class AbstractUser(AbstractBaseUser, PermissionsMixin):
    """
An abstract base class implementing a fully featured User model with
admin-compliant permissions.

Username, password and email are required. Other fields are optional.
"""
    username = models.CharField(_('username'), max_length=30, unique=True,
        help_text=_('Required. 30 characters or fewer. Letters, digits and '
                    '@/./+/-/_ only.'),
        validators=[
            validators.RegexValidator(r'^[\w.@+-]+$', _('Enter a valid username.'), 'invalid')
        ])

rawDescription: How can I allow spaces in a Django username?

description: Allow spaces in a Django username


code:
while True:
    x = {i: set(range(1,7)) for i in range(1,7)}

    a = [random.choice(range(1,7))]  # start with a random number
    last = a[-1]
    while x[last]:
        next = random.choice(list(x[last]))
        x[last].remove(next)
        a.append(next)
        last = next

    if len(a) == 37:
        # We get to length 37 if and only if each set above is exhausted.
        # In this case, the first item will always equal the last item
        # (proof left as an exercise for the reader), so remove it.
        a = a[:-1]
        break

print(''.join(str(i) for i in a))

rawDescription: Numpy array item order - equal distribution of sequences


code: tree.bind('<Double-1>', lambda e: 'break')

rawDescription: How to prevent ttk.Treeview item from opening when double clicked

description: Prevent ttk.Treeview item from opening when double clicked


code:
class Meta(DeclarativeMeta):
    def __init__(cls, *args, **kw):
        if getattr(cls, '_decl_class_registry', None) is None:
            return # they use this in the docs, so maybe its not a bad idea
        cls.__mapper_args__ = {'polymorphic_identity': cls.__name__}
        return super(Meta, cls).__init__(*args, **kw)

class Experiment(Entity):
    __metaclass__ = Meta

rawDescription: Enhance SQLAlchemy syntax for polymorphic identity


code:
import struct

def to_float(int_):
    return struct.unpack('d', struct.pack('q', int_))[0]

def to_long(float_):
    return struct.unpack('q', struct.pack('d', float_))[0]

data = 0.2345
long_data= to_long(data) #4597616773191482474
new_data = to_float(long_data) #0.2345

rawDescription: Python - Convert a signed float to Unsigned Long( DWORD for win32 )


code:
class OneToThreeInline(admin.StackedInline):
    fk_name = 'three'
    model = One

class TwoToThreeInline(admin.StackedInline):
    fk_name = 'three'
    model = Two

rawDescription: Django admin inline display but foreign key has opposite relation


code:
def __init__(self, **kwargs): # kwargs is a dict containing text
    '''
    Constructor
    '''
    super(spot,self).__init__(**kwargs)
    self.ismine=False
    self.text=kwargs['text'] # you need to assign it here

rawDescription: __init__ values vs instantiation value

description: __init__ values vs instantiation value


code:
num1 = int(input("Please enter a number between 1 and 10: "))
num2 = int(input("Please enter a number between 11 and 20: "))
the_sum = 0

start = num1
end = num2 + 1

m = start
while m  < end:
    the_sum += m
    m += 1

print ("Your total price comes to ", the_sum)

rawDescription: Python While Loop- Addition between two numbers


code:
orig = "bla bla"
str(map(ord, orig))

description: Turn "abc" to "[97, 98 99]"


code:
import sqlite3 as sql

con = sql.connect(r"E:\Users.db")
c = con.cursor()
con.row_factory = sql.Row
username = input("What is your username: ")

readdata = input("Select the message you wish to read: ")
c.execute("SELECT Sender, Recipient, Subject, Message FROM Mail WHERE (Subject LIKE ?) AND   (Recipient LIKE ?)", (readdata, username))

component = c.fetchall()

for row in component:
    (sent, rec, subject, msg) = tuple(row)
    print()
    print("Sender: " + sent)
    print("Recipient: " + rec)
    print("Subject: " + subject)
    print()
    print("Message: " + msg)

rawDescription: Reading raw data from an sqlite table in python


code:
if 'X' not in line:
   print(line)
line = infile.readline()

rawDescription: Reading lines in a file

description: Reading lines in a file


code: map( Something, [1,2,3,4] )

rawDescription: python: map( new object, [arguments] )

description: Python: map( new object, [arguments] )


rawDescription: Matrix of lists - Python

description: Matrix of lists - Python


code:
platform.system = lambda: "whatever"
platform.system()

rawDescription: Give python "platform" library fake platform information?


code:
...
def tableshow2(self):
    self.table5 = CustomTableSearch(self)
    self.table5.show()
...

rawDescription: How can I choose which classes run in Python?

description: Choose which classes run in Python


code:
if json.encoder.ESCAPE_DCT.get('/') != '/':
    json.encoder.ESCAPE_DCT['/'] = '/'

rawDescription: Google App Engine Python simplejson escaping?


code:
from datetime import datetime, timedelta
import time

tick = datetime.now()
time.sleep(1.5)
tock = datetime.now()
diff = tock-tick
diff = timedelta(seconds=round(diff.total_seconds(), 2))
print(diff)  # 0:00:01.500000

rawDescription: How to round datetime()?

description: Round datetime()


code:
import cmd

class WithAliasCmd(cmd.Cmd):

    def default(self, line):
        cmd, arg, line = self.parseline(line)
        func = [getattr(self, n) for n in self.get_names() if n.startswith('do_' + cmd)]
        if func: # maybe check if exactly one or more elements, and tell the user
            func[0](arg)

rawDescription: Aliases for commands with Python cmd module


code:
def splitNoEscapes(string, char):
    sections = string.split(char)
    sections = [i + (char if i[-1] == "\\" else "") for i in sections]
    result = ["" for i in sections]
    j = 0
    for s in sections:
        result[j] += s
        j += (1 if s[-1] != char else 0)
    return [i for i in result if i != ""]

rawDescription: Python split string without splitting escaped character


code:
'"abcd'.strip( '"\'' )
'\'blahblah'.strip( '"\'' )
print( '"abcd'.strip( '"\'' ) )
print( '\'blahblah'.strip( '"\'' ) )

rawDescription: python reading strings

description: Python reading strings


code:
# coding=utf8

import pprint

class MyPrettyPrinter(pprint.PrettyPrinter):
    def format(self, object, context, maxlevels, level):
        if isinstance(object, unicode):
            return (object.encode('utf8'), True, False)
        return pprint.PrettyPrinter.format(self, object, context, maxlevels, level)

d = {'foo': u'işüğçö'}

pprint.pprint(d)              # {'foo': u'i\u015f\xfc\u011f\xe7\xf6'}
MyPrettyPrinter().pprint(d)   # {'foo': işüğçö}

rawDescription: Unable to encode/decode pprint output

description: Unable to encode/decode pprint output


code:
def main():
    succedents = load_succedents('ABCD_reddob_cases.raw')
    supercedents = load_supercedents('/shared/voom_e_plink_cases')
    with open('/shared/succedentsupercedent_stats', 'w') as stats_out:
        for cols in range(len(succedents[0])):
            for colg in range(len(supercedents[0])):
                xy_array = [[0] * 2 for _ in range(len(supercedents))]
                for user in range(len(supercedents)):
                    s1, s2 = succedents[user][cols], supercedents[user][colg]
                    if is_valid_double(s1) and is_valid_double(s2):
                        xy_array[user] = to_double(s1), to_double(d2)
                sumx = sum(row[0] for row in xy_array)
                sumy = sum(row[1] for row in xy_array)
                append(stats_out, cols, colg, sumx, sumy)

def load_supercedents(path):
    with open(path) as file:
        # perform whatever you need to do for loading the supercedents
        # some sort of data conversion may need to take place here
        supercedents = tuple(file)
    return supercedents

def load_succedents(path):
    with open(path) as file:
        # perform whatever you need to do for loading the succedents
        # some sort of data conversion may need to take place here
        succedents = tuple(file)
    return succedents

def is_valid_double(data):
    # determine if the data is a valid double or not
    return True or False

def to_double(data):
    # convert the data into whatever a double happens to be
    return data

def append(file, s, g, x, y):
    # write the data to your file
    print('cols = {s}, colg = {g}, sumx = {x}, sumy = {y}'.format(**locals()),
          file=file, flush=True)

if __name__ == '__main__':
    main()

rawDescription: Understanding pseudo-code for Python implementation


code:
import os
import shutil

filenames = [ '000101 FL - Project Title Page.DOC']

for filename in filenames:
    folder = 'Div' + filename[:2]       # 'Div00'

    # Create the folder if doesn't exist
    if not os.path.exists(folder):
        os.makedirs(folder)

    # Copy the file to `folder`
    if os.path.isfile(filename):
        shutil.copy2(filename, folder)  # metadata is copied as well

rawDescription: Creating folders by checking numbers at beginning of a string with python


code:
import Queue

import memcache

# See http://stackoverflow.com/questions/9539052/python-dynamically-changing-base-classes-at-runtime-how-to
# Don't inherit client from threading.local so that we can reuse clients in
# different threads
memcache.Client = type('Client', (object,), dict(memcache.Client.__dict__))
# Client.__init__ references local, so need to replace that, too
class Local(object): pass
memcache.local = Local

class PoolClient(object):
    '''Pool of memcache clients that has the same API as memcache.Client'''
    def __init__(self, pool_size, pool_timeout, *args, **kwargs):
        self.pool_timeout = pool_timeout
        self.queue = Queue.Queue()
        for _i in range(pool_size):
            self.queue.put(memcache.Client(*args, **kwargs))

    def __getattr__(self, name):
        return lambda *args, **kw: self._call_client_method(name, *args, **kw)

    def _call_client_method(self, name, *args, **kwargs):
        try:
            client = self.queue.get(timeout=self.pool_timeout)
        except Queue.Empty:
            return

        try:
            return getattr(client, name)(*args, **kwargs)
        finally:
            self.queue.put(client)

rawDescription: Memcache client with connection pool for Python?


code:
data = {}
for filepath in files:
  f = open(filepath, "r")
  f.readline()
  for line in f.readlines():
    info = line.strip().split("\t")
    id, feature, total, percent = info[0], info[1], int(info[2]), int(info[3])
    if id in data:
      data[id].total += total * (percent / 100.0)
      data[id].count += total
    else:
      data[id] = {"feature": feature, "total": total * (percent / 100.0), "count": total}

# Output
out = open("outfile", "w")
out.write("ID\tFeature\tAveragePercentage")
for id in data:
  out.write(str(id) + "\t" + data.feature + "\t" + str(data.total / data.count) + "\n")

rawDescription: Python: Get Average values from multiple columns in multiple files


code:
import inspect
import peewee
import tables
models = [
    obj for name, obj in inspect.getmembers(
        tables, lambda obj: type(obj) == type and issubclass(obj, peewee.Model)
    )
]
peewee.create_model_tables(models)

rawDescription: How to create all tables defined in models using peewee

description: Create all tables defined in models using peewee


code:
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, gh_url, 'user', 'pass')

auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)

rawDescription: Extremely strange Web-Scraping issue: Post request not behaving as expected


code:
import lxml.etree as et

doc = '''
<a>
   <b>
       <c>h</c>
   </b>
   <b>
       <c>j</c>
   </b>
</a>
'''

tree = et.fromstring(doc)

tree.xpath("/a/b/c[text()='j']")

rawDescription: python ElementTree find child with certain text value

description: Python ElementTree find child with certain text value