code:
import ctypes
from ctypes.wintypes import *
import win32clipboard
from win32con import *
import sys

class BITMAPFILEHEADER(ctypes.Structure):
    _pack_ = 1  # structure field byte alignment
    _fields_ = [
        ('bfType', WORD),  # file type ("BM")
        ('bfSize', DWORD),  # file size in bytes
        ('bfReserved1', WORD),  # must be zero
        ('bfReserved2', WORD),  # must be zero
        ('bfOffBits', DWORD),  # byte offset to the pixel array
    ]
SIZEOF_BITMAPFILEHEADER = ctypes.sizeof(BITMAPFILEHEADER)

class BITMAPINFOHEADER(ctypes.Structure):
    _pack_ = 1  # structure field byte alignment
    _fields_ = [
        ('biSize', DWORD),
        ('biWidth', LONG),
        ('biHeight', LONG),
        ('biPLanes', WORD),
        ('biBitCount', WORD),
        ('biCompression', DWORD),
        ('biSizeImage', DWORD),
        ('biXPelsPerMeter', LONG),
        ('biYPelsPerMeter', LONG),
        ('biClrUsed', DWORD),
        ('biClrImportant', DWORD)
    ]
SIZEOF_BITMAPINFOHEADER = ctypes.sizeof(BITMAPINFOHEADER)

win32clipboard.OpenClipboard()
try:
    if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_DIB):
        data = win32clipboard.GetClipboardData(win32clipboard.CF_DIB)
    else:
        print('clipboard does not contain an image in DIB format')
        sys.exit(1)
finally:
    win32clipboard.CloseClipboard()

bmih = BITMAPINFOHEADER()
ctypes.memmove(ctypes.pointer(bmih), data, SIZEOF_BITMAPINFOHEADER)

if bmih.biCompression != BI_BITFIELDS:  # RGBA?
    print('insupported compression type {}'.format(bmih.biCompression))
    sys.exit(1)

bmfh = BITMAPFILEHEADER()
ctypes.memset(ctypes.pointer(bmfh), 0, SIZEOF_BITMAPFILEHEADER)  # zero structure
bmfh.bfType = ord('B') | (ord('M') << 8)
bmfh.bfSize = SIZEOF_BITMAPFILEHEADER + len(data)  # file size
SIZEOF_COLORTABLE = 0
bmfh.bfOffBits = SIZEOF_BITMAPFILEHEADER + SIZEOF_BITMAPINFOHEADER + SIZEOF_COLORTABLE

bmp_filename = 'clipboard.bmp'
with open(bmp_filename, 'wb') as bmp_file:
    bmp_file.write(bmfh)
    bmp_file.write(data)

print('file "{}" created from clipboard image'.format(bmp_filename))

rawDescription: How to save image to file from clipboard without PIL?

description: Save image to file from clipboard without PIL


code:
with open("/dev/sda",'rb') as f:
    with open("~/imagingtest.dd", "wb") as i:
        while True:
            if i.write(f.read(512)) == 0:
                break

rawDescription: Python Disk Imaging

description: Python Disk Imaging


code:
from matplotlib import pyplot as p
from mpl_toolkits.mplot3d import Axes3D    # @UnusedImport

import numpy as np
from math import pi, cos, sin

z = np.arange(0, 1, 0.02)
theta = np.arange(0, 2 * pi + pi / 50, pi / 50)

fig = p.figure()
axes1 = fig.add_subplot(111, projection='3d')
for zval in z:
    x = zval * np.array([cos(q) for q in theta])
    y = zval * np.array([sin(q) for q in theta])
    axes1.plot(x, y, -zval, 'b-')
axes1.set_xlabel("x label")
axes1.set_ylabel("y label")
axes1.set_zlabel("z label")

axes1.invert_zaxis()

p.show()

rawDescription: Reverse Z Axis on matplotlib 3D Plot

description: Reverse Z Axis on matplotlib 3D Plot


code:
import ipaddress
import csv
from csv import DictReader, DictWriter
from itertools import filterfalse

with open(r'file1.csv', newline='') as fin3,\
     open(r'file2.csv', newline='') as fin4,\
     open(r'file3.csv', 'w', newline='') as fout3:

    read3 = DictReader(fin3) # fin 3 and 4 are copies of the same file
    read4 = DictReader(fin4)

    writenum3 = DictWriter(fout3, fieldnames=read3.fieldnames)
    writenum3.writeheader()

    lst4=[] # To prevent duplicate lines

    for line3 in read3:
        line3['Range']=ipaddress.ip_network(line3['Range']) # Convert IP ranges to ip network object
        fin4.seek(0) # Reset iterator
        read4 = DictReader(fin4) # Read again to prevent errors
        for line4 in read4:
            line4['Range']=ipaddress.ip_network(line4['Range']) # Convert IP ranges to ip network object
            if line3 not in lst4: # To prevent duplicate lines
                if line3['Range'].overlaps(line4['Range']): # Tests for IP overlap
                    if line3['Range'].netmask < line4['Range'].netmask: # To avoid "Not contained in" errors
                        lst=list(line3['Range'].address_exclude(line4['Range'])) # List of subnets excluding line4 subnet
                        for val in lst:
                            line3['Range']=val # New range
                            line3[' IPStart']=val.network_address #New net address
                            line3[' IPStop']=val.broadcast_address #New broadcast address
                            lst4.append(line3)
                            writenum3.writerow(line3) # Write lines

                    else:
                        lst4.append(line3)
                        writenum3.writerow(line3) # Write lines
                else:
                    lst4.append(line3)
                    writenum3.writerow(line3) # Write lines

rawDescription: Editing csv file to edit subnets so there is no overlap in IP ranges (ipaddress module in Python 3.3)


code:
coords = numpy.meshgrid(*(numpy.linspace(0, (n-1)*delta, n) for i in range(d)))
# coords is a Python list of numpy arrays
coords = [c.flatten() for c in coords]
# now coords is a Python list of 1-d numpy arrays
coords = numpy.array(coords).transpose()
# now coords is a numpy array, one row per point
g = graph_tool.generation.geometric_graph(coords, e*(1+1e-9))

rawDescription: Proximity Graph in python

description: Proximity Graph in python


code:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = patterns('',
    url(r'^static/blueprints/(?P<blueprint>[\w-]+)/(?P<path>.+)', 'my_view_name'),
    ...
)
if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns()

rawDescription: Django: a custom view inside /static/ directory


code: from scons.config import whatever

rawDescription: python: naming a module that has a two-word name

description: Python: naming a module that has a two-word name


rawDescription: Setting the value of an <input> dropdown in Selenium with Python


code: def print_dictionary(d): print (d['a']).rjust(10)

rawDescription: How to print a string value of a dicionary without the quotes?

description: Print a string value of a dicionary without the quotes


code:
tick = np.linspace(min(your_variable),max(your_variable),3)

plt.tight_layout(pad=0.5, w_pad=2.5, h_pad=2.0)
ax1 = plt.subplot(131) # creates first axis
ax1.set_xticks([0,2000,500,1000,1500])
ax1.set_yticks([0,2000,500,1000,1500])
i1 = ax1.imshow(U,cmap='hot',extent=(X.min(),2000,Y.min(),2000))
plt.colorbar(i1,ax=ax1,ticks=tick)

ax1.set_title("$ \mathrm{Ux_{mes} \/ (pix)}$")
ax2 = plt.subplot(132) # creates second axis
ax2.set_xticks([0,2000,500,1000,1500])
ax2.set_yticks([0,2000,500,1000,1500])
i2=ax2.imshow(UU,cmap='hot',extent=(X.min(),2000,Y.min(),2000))
ax2.set_title("$\mathrm{Ux_{cal} \/ (pix)}$")
plt.colorbar(i2,ax=ax2,ticks=tick)

ax3 = plt.subplot(133) # creates first axis
ax3.set_xticks([0,2000,500,1000,1500])
ax3.set_yticks([0,2000,500,1000,1500])
i3 = ax3.imshow(resU,cmap='hot',extent=(X.min(),2000,Y.min(),2000))
ax3.set_title("$\mathrm{\mid Ux - Ux \mid \/ (pix)}$ ")
plt.colorbar(i3,ax=ax3,ticks=tick)

plt.show()

rawDescription: Python - add colorbars in multiple plots for each plot


code:
B_inv = scipy.linalg.inv(B)
C = (A.transpose().dot(B_inv.transpose())).transpose()

rawDescription: Efficient numpy / lapack routine for product of inverse and sparse matrix?


code: df = df.reset_index(drop=True)

rawDescription: Shrink down row numbers in a Pandas Dataframe when removing rows in Python


code:
import lxml.etree

data = '''
I want to use a track-bar to change a form's opacity.

This is my code:

decimal trans = trackBar1.Value / 5000; this.Opacity = trans;

When I try to build it, I get this error:

Cannot implicitly convert type 'decimal' to 'double'.

I tried making trans a double.
'''

html = lxml.etree.HTML(data)
code_blocks = html.xpath('//code/text()')
text_blocks = html.xpath('//*[not(descendant-or-self::code)]/text()')

rawDescription: Parse Code from Text - Python

description: Parse Code from Text - Python


code:
modlines = []
with open(fname) as f:
    for line in f:
        if 'AC_CONFIG_FILES' in line:
            modlines.append(rstring + '\n')
        else:
            modlines.append(line)

with open(fname, 'w') as out:
    for line in modlines:
        out.write(line)

rawDescription: Replacing a line in a file using Python

description: Replacing a line in a file using Python


code:
def get() : return [ (lambda x: lambda: x)(i) for i in [ 1, 2, 3 ] ]
for f in get() : print( f() )

rawDescription: Weird closure behavior in python

description: Weird closure behavior in python


code:
try:
    exrate = exchangeRates.objects.get(date=obj.invoiceDate)
    xeuroRate = exrate.euroRate
    xdollarRate = exrate.dollarRate
except:
    xeuroRate = 0.0 # set default value
    xdollarRate = 0.0 # set default value

obj.euroRate = xeuroRate
obj.dollarRate = xdollarRate
obj.save()

rawDescription: Get value from another model based on matching dates


code: c = pickle.load( open( "fromserver.p" ) )

rawDescription: how would i have python check to see if a list was sent to/from socket server?

description: How would i have python check to see if a list was sent to/from socket server


code:
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures

x = 10 * np.random.random(100)
y = -4 + 2 * x - 3 * x ** 2

model = make_pipeline(PolynomialFeatures(2), Ridge(alpha=1E-8, fit_intercept=False))
model.fit(x[:, None], y)
ridge = model.named_steps['ridge']
print(ridge.coef_)
# array([-4.,  2., -3.])

rawDescription: How to extract equation from a polynomial fit?

description: Extract equation from a polynomial fit


code:
import Tkinter

main_window=Tkinter.Tk()
text_widget = Tkinter.Text(main_window)
text_widget.insert('insert',"text  message will display here")
text_widget.pack(anchor = "w", padx = 50, pady = 50)

main_window.mainloop()

rawDescription: placing text box widget onto the screen using tkinter

description: Placing text box widget onto the screen using tkinter


code:
def split_len(seq, length):
    return [seq[i:i + length] for i in range(0, len(seq), length)]

def encode(key, plaintext):

    order = {
        int(val): num for num, val in enumerate(key)
    }

    ciphertext = ''
    for index in sorted(order.keys()):
        for part in split_len(plaintext, len(key)):
            try:
                ciphertext += part[order[index]]
            except IndexError:
                continue

    return ciphertext

print(encode('3214', 'IHAVETWOCATS'))
#>>> HTAAWTIECVOS

rawDescription: Encrypting a columnar transposition cipher


code: qs = models.SomeTable.objects.filter(foo='bar', site__contained=some_polygon).values('site').distinct()

rawDescription: SELECT DISTINCT ON (geometry column) equivalent with GeoDjango


code:
import time
matches = ['01','06','11','16','21','26','31','36','41','46','51','56']
while True:
    seconds = time.strftime('%S')
    if seconds in matches:
        print('YES')
    else:
        print(seconds)
    time.sleep(1)

rawDescription: How check a string value inside a list on a if statement?


code:
f = open('test.txt', 'r')
f.read()
f.close()
f = open('test.txt', 'wua')
print >> f, 'writing'
f.close()
f = open('test.txt', 'r')
f.read()
f.close()
f = open('test.txt', 'auw')
print >> f, 'appending'
f.close()
f = open('test.txt', 'r')
f.read()
f.close()

rawDescription: What is "wua" mode when opening a file in python?


code:
file.write('''
<html>
<head>
</head>
<style>
some styling stuff ..
<\style>
<body>
many more lines of code ...
</body>
</html>''')

rawDescription: Is there a way of writing several lines at a time to a file in python?


code:
import sys

old_raw_input = raw_input
def raw_input(*args):
    old_stdout = sys.stdout
    try:
        sys.stdout = sys.stderr
        return old_raw_input(*args)
    finally:
        sys.stdout = old_stdout

rawDescription: How to redirect the raw_input to stderr not stdout

description: Redirect the raw_input to stderr not stdout


code:
def func(num_a, num_b):
    a_sums = sum(a_inner for a_inner in product(someList, repeat=num_a))
    b_sums = sum(b_inner for b_inner in product(someOtherList, repeat=num_b))
    return (a - b for a, b in product(a_sums, b_sums))

rawDescription: Python How Can I Put Nested For Loops Into a Function?


code: foo, bar, baz = [random.choice(list) for i in range(3)]

rawDescription: Assigning mulitple variables to a random item in list. Python


code: pd.melt(df.reset_index(), id_vars=['id', 'date'], value_vars=['value', 'value2'], var_name='var_name', value_name='value')

rawDescription: Set column names when stacking pandas DataFrame


code:
name = 'foo'
zip = 123
unused = 'whoops!'
locals()
'%(name)s %(zip)i' % locals()

rawDescription: Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?


code:
#!/usr/bin/python3

from multiprocessing import *
import time

def nic_process( q ):
    while True:
        job = q.get()
        # perform task
        print(job)

        # add a delay to make timing happy
        time.sleep(1)

        # Put the job back into the queue.
        q.put(job)

if __name__ == '__main__':
    job_q = Queue()
    proc_count = cpu_count()

    pool = [ Process(target=nic_process, args=(job_q,)) for p in range(proc_count) ]
    for p in pool:
        p.start()

    # Fill the job queue.
    job_q.put(['job1','params',0,999])
    job_q.put(['job2','params',1000,1999])
    job_q.put(['job3','params',2000,2999])
    # ...

rawDescription: Python - parallelize a list of tasks while adding completed tasks back to the list


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

data = np.random.random((10,10))

fig, ax = plt.subplots()
im = ax.imshow(data)
cbar = fig.colorbar(im)
ax.set_title('Click on the colorbar')

highlight = ax.imshow(np.ma.masked_all_like(data), interpolation='nearest',
                      vmin=data.min(), vmax=data.max())

def on_pick(event):
    val = event.mouseevent.ydata
    selection = np.ma.masked_outside(data, val - 0.05, val + 0.05)
    highlight.set_data(selection)
    fig.canvas.draw()

cbar.ax.set_picker(5)
fig.canvas.mpl_connect('pick_event', on_pick)

plt.show()

rawDescription: onclick method on a colorbar matplotlib python

description: Onclick method on a colorbar matplotlib python


code:
def someFunc(a,b,p):
    if b==0 or a!=1:
        part1 = str(a)
    else:
        part1 = ''
    if p==0:
        part2 = ''
    else:
        if b!=1:
            part2 = c + '+'+str(b)
        else:
            part2 = ''
    return part1 + part2

rawDescription: What does those return mean in Python?

description: What does those return mean in Python


code:
from dateutil.parser import parse
parse('24th of May 2016        04:00')

rawDescription: string to datetime.datetime type format

description: String to datetime.datetime type format


code:
from collections import OrderedDict
import numpy as np

def get_data(number):
   my_data = OrderedDict()
   for i in range(1, number+1):
       my_data['data_{}'.format(i)] = np.genfromtxt('measurement_{}.out'.format(i), delimiter='\t')
   return my_data

rawDescription: Create a new array of data in each loop step in Python 3.4


code:
import urllib
from xml.dom import minidom
from google.appengine.api import urlfetch

params = urllib.urlencode({'p': loc_param, 'u': units,})
full_uri = '?'.join([url, params,])

result = urlfetch.fetch(full_uri)
if result.status_code == 200:
    return minidom.parseString(result.content)

rawDescription: Sending HTTP requests from App Engine

description: Sending HTTP requests from App Engine


code:
import os

files = os.listdir('.')
newfile = 'myfile.txt'
mystring = 'mystring'

found = []
for f in files:
    myfile = open(f, 'r')
    if mystring in myfile.read():
        found.append(f)
    myfile.close()

myfile = open(newfile, 'w')
myfile.write("\n".join(found))
myfile.close()

rawDescription: Scannin several text files

description: Scannin several text files


code:
tag_names = ["Open tag:","Parm:","Parm:"]
import re
# split on <,>,white space, and remove empty strings at
# the start and at the end of the resulting list.
tags = re.split(r'[<> ]','<b size=5 alt=ref>')[1:-1]
# zip tag_names list and with list of tags
print(list(zip(tag_names, tags)))

[('Open tag:', 'b'), ('Parm:', 'size=5'), ('Parm:', 'alt=ref')]

rawDescription: Python split tags based on regular expression


code:
output1 = {...}
outputs = (output1, output2, output3)

for index, output in enumerate(outputs):
    filename = 'output_data_{0}'.format(index)

    #this will write file in directory relative to script location
    with open(filename, 'w') as f:
        f.write('Example {0}:\r\n'.format(index))

        for issue in data["issues"]:
            # assumes issue is of type dict
            # assumes issues has appropriate keys
            # assumes values are of string type
            key = issue['key']
            summary = issue['fields']['summary']

            f.writelines((key, summary, "\r\n",))

rawDescription: How to print multiple txt files from a single output

description: Print multiple txt files from a single output


code:
import csv

final_out = [(['2893541', 'OVERALL', 'friendly and genuine.'], 77), (['2893382', 'SPEED', 'timely manner."'], 63)]

with open('text.txt', 'wb') as fh:
    writer = csv.writer(fh, delimiter='\t')

    for row in final_out:
        writer.writerow(row[0] + [row[1]])

rawDescription: Python List output troubleshooting

description: Python List output troubleshooting


code:
def test_post_endpoint(self):
   data = {'hello':'23'}
   c = Client() #above, from django.test import TestCase,Client
   #optional, but may be necessary for your configuration: c.login("username","password")
   response = c.post('/api/project',params=data)
   self.assertEqual(response.status_code, 200)

rawDescription: how do you include a csrf token when testing a POST endpoint in django?

description: Include a csrf token when testing a POST endpoint in django


rawDescription: Most efficient way to assign a value of zero to multiple variables at once


code:
noseargs = ['foo', '--with-xunit', '--xunit-file=output.xml', '--tests=mytest']
nose.run(argv=noseargs)

rawDescription: How to specify xml output for nose programatically

description: Specify xml output for nose programatically


code: sorted(j, key=lambda x: x.iloc[0,1], reverse=True)

rawDescription: sorting multiple dataframes in python

description: Sorting multiple dataframes in python


code:
class MyWSGIContainer(WSGIContainer):
    def __call__(self, request):
        if request.remote_ip in blacklist:
            self.write_redirect()
        else:
            super(MyWSGIContainer, self)(request)

rawDescription: Redirect all ips in config file to static address


code:
def mydefault(context):
    return context.current_parameters.get('name')

class Substance(Base):
    __tablename__ = "substances"
    id = Column(Integer, primary_key=True)
    code = Column(String, unique=True)
    name = Column(String, unique=True)
    long_name = Column(String, unique=True, default=mydefault)

rawDescription: SQLAlchemy set default value of one column to that of another column


code:
# Array B contains True/False for the condition and is subsequently
# used as Boolean index.
B = (active_layer >= al_upper_volume_limit)
inactive_layer_volume[B] += 20 * active_layer_proportion[B]
active_layer_volume[B] = (active_layer[B] - 20) * active_layer_proportion[B]

# The "not B" does the "else" part of the elif statement it replaces
B = ~B & (active_layer < al_lower_volume_limit) & (inactive_layer > 0)
active_layer_volume[B] += 20 * inactive_layer_proportion[B]
inactive_layer_volume[B] -= 20 * inactive_layer_proportion[B]

rawDescription: Numpy ndenumerate is incredibly slow. Is there a quicker way of using conditions on arrays in numpy?


code:
root = Tkinter.Tk()
var = Tkinter.IntVar()
chk = Tkinter.Checkbutton(root, text='foo', variable=var)
chk.pack(side=Tkinter.LEFT)
var.get()  #unchecked
var.get()  #checked

rawDescription: Getting Tkinter Check Box State

description: Getting Tkinter Check Box State


code:
url     = "http://host:8080/job/myproject/config.xml"
auth    = ('user','pass')
headers = {"Content-Type" : "application/xml"}
with open('new_config.xml', 'rb') as payload:
    r = requests.post(url, auth=auth, data=payload, headers=headers)

rawDescription: How to convert cURL in Python requests to change Jenkins config.xml file

description: Convert cURL in Python requests to change Jenkins config.xml file


code:
import win32com.client
import win32gui
import win32process

hwnd = win32gui.GetForegroundWindow()

_, pid = win32process.GetWindowThreadProcessId(hwnd)

shell = win32com.client.Dispatch("WScript.Shell")

shell.AppActivate('Console2')
shell.SendKeys('{UP}{ENTER}')

shell.AppActivate(pid)

rawDescription: Set focus to window based on ID using win32com.client's AppActivate


code:
def find_second_last(text, pattern):
  return text.rfind(pattern, 0, text.rfind(pattern))

find_second_last("abracadabra", "a")

rawDescription: Python 3: get 2nd to last index of occurence in string


code: xmlstr = ElementTree.tostring(et, encoding='utf8', method='xml')

rawDescription: How can I convert Python ElementTree to string?

description: Convert Python ElementTree to string


rawDescription: How to groupby an index as well as a column in pandas

description: Groupby an index as well as a column in pandas


code:
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"), # That's it!!
    '/var/www/static/',
)

rawDescription: Handling static files that dont pertain to an app in Django


code:
from datetime import datetime
s = '2014-12-11T20:46:12Z'
datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')

rawDescription: How to convert API timestamp into python datetime object

description: Convert API timestamp into python datetime object


code:
import itertools
[''.join(value) for key, value in itertools.groupby(my_str)]

rawDescription: How to find and split a string by repeated characters?

description: Find and split a string by repeated characters


rawDescription: split a list into two consisting of desired elements using python

description: Split a list into two consisting of desired elements using python


code:
import numpy as np
import pandas
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick, candlestick2
import matplotlib.dates as mdates
from pandas.io.data import DataReader

# get daily stock price data from yahoo finance for S&P500
SP = DataReader("^GSPC", "yahoo")
SP.reset_index(inplace=True)
print(SP.columns)
SP['Date2'] = SP['Date'].apply(lambda date: mdates.date2num(date.to_pydatetime()))
fig, ax = plt.subplots()
csticks = candlestick(ax, SP[['Date2', 'Open', 'Close', 'High', 'Low']].values)
plt.show()

rawDescription: Pandas DataFrame Matplotlib BoxPlot Boxes


rawDescription: how can I get filenames without directory name

description: Get filenames without directory name


code: column = [row[0] for row in matrix]

rawDescription: Python - Read nth line in a matrix

description: Python - Read nth line in a matrix


code:
from django.db.models import Sum
User.objects.all().annotate(total=Sum('submission__task__points'))

rawDescription: Getting total points for all of User's Submissions Django


code:
import tkinter as tk

class App(tk.Frame):

    def __init__(self, master):

        tk.Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):

        IpLabel = tk.Label(self, text='Device_A Ip')
        IpLabel.grid(row=0, column=0)
        IpEntry = tk.Entry(self, width=20)
        IpEntry.grid(row=0, column=1)
        IpEntry.insert(0, '10.0.0.5')

        #Checkbutton
        self.var = tk.BooleanVar()
        cb = tk.Checkbutton(self, text="Infinite Loop", variable=self.var)
        cb.deselect() #the Checkbutton default is unselected
        cb.grid(columnspan=2) #place of the Checkbutton

        listbox = tk.Listbox(self)
        listbox.insert(tk.END, "a list entry")
        for item in ["one", "two", "three", "four"]:
            listbox.insert(tk.END, item)
        listbox.grid(row=1, rowspan=19, column=0, columnspan=2, sticky="nsew")
        #run widget
        self.run_button = tk.Button(self, text='run')
        self.run_button.grid(row=20, column=0)

if __name__ == "__main__":

    #open gui file
    root = tk.Tk()
    root.title('ACM')
    app = App(root)
    root.mainloop()

rawDescription: How can I add Listbox using tkinter to my code

description: Add Listbox using tkinter to my code


code:
import matplotlib.pyplot as plt

BOX = 5
START = 365
changes = (8, -3, 4, -4, 12, -3, 7, -3, 5, -9, 3)

# one way to force dimensions is to set the figure size:
fig = plt.figure(figsize=(5, 10))

# another way is to control the axes dimensions
# for axes to have specific dimensions:
#                  [ x0,  y0,   w,   h]  in figure units, from 0 to 1
#ax = fig.add_axes([.15, .15, .7*.5, .7])
ax = fig.add_axes([.15, .15, .7, .7])

def sign(val):
    return val / abs(val)

pointChanges = []
for chg in changes:
    pointChanges += [sign(chg)] * abs(chg)

symbol = {-1:'o',
           1:'x'}

chgStart = START
for ichg, chg in enumerate(changes):
    x = [ichg+1] * abs(chg)
    y = [chgStart + i * BOX * sign(chg) for i in range(abs(chg))]
    chgStart += BOX * sign(chg) * (abs(chg)-2)
    ax.scatter(x, y,
               marker=symbol[sign(chg)],
               s=175)   #<----- control size of scatter symbol

ax.set_xlim(0, len(changes)+1)
fig.savefig('pointandfigure.png')
plt.show()

rawDescription: Point and figure chart with matplotlib

description: Point and figure chart with matplotlib


code:
urlpatterns = patterns('',
            url(r'^products/(?P<categ_name>\w+)/$', views.products, name='products_category'),
            url(r'^products/(?P<categ_name>\w+)/(?P<subcateg_name>\w+)/$', views.products, name='products_subcategory'),
            url(r'^logout/',views.logoutView, name='logout'),)

rawDescription: how to pass multiple url parameters in django

description: Pass multiple url parameters in django


code: a.x*np.tile(t, len(a)/len(t))

rawDescription: Apply function to pandas Series with argument (which varies for every element)


code:
end = False
flist = open('flist.txt','r')

print("SECURITY PASSED")
print("ENTERING DATABASE")

def choosefile():
    fcho = input("ENTER FILE CHOICE, VIEW FILE LIST, OR END: ")

    if (fcho == "view file list" or fcho == "VIEW FILE LIST"):
        print (flist.read())

    elif (fcho == "END"):
        return True

while (end == False):
    end = choosefile()

rawDescription: Python, Conditional Issues

description: Python, Conditional Issues


rawDescription: python data from excel dot in between letters

description: Python data from excel dot in between letters


code:
folder = 'whatever' #the folder you wish to save the files in
name = 'somefilename.txt'
filename = os.path.join(folder, filename)

rawDescription: How can I save sort .txt into files? Python or shell script

description: Save sort .txt into files? Python or shell script


code:
passw = ''

while len(passw) <= 12:
    char = chars[ord(os.urandom(1)) % 64]
    if char not in passw:
        passw += char

rawDescription: Python password generation: Count unique values in list, remove doubles and replace with new unique values for PW Gen


rawDescription: List of tuples to dictionary

description: List of tuples to dictionary


code:
source_document = Document('source.docx')
target_document = Document()

for paragraph in source_document.paragraphs:
    text = paragraph.text
    target_document.add_paragraph(text)

rawDescription: combine word document using python docx

description: Combine word document using python docx


code:
candy = ['a','b','c']
fruit = ['d','e','f']
snack = ['g','h','i']
name = 'fruit'
eval(name)

rawDescription: How to use string value as a variable name in Python?

description: Use string value as a variable name in Python


code:
import matplotlib
matplotlib.use('QT4Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

class MyAxes3D(axes3d.Axes3D):

    def __init__(self, baseObject, sides_to_draw):
        self.__class__ = type(baseObject.__class__.__name__,
                              (self.__class__, baseObject.__class__),
                              {})
        self.__dict__ = baseObject.__dict__
        self.sides_to_draw = list(sides_to_draw)
        self.mouse_init()

    def set_some_features_visibility(self, visible):
        for t in self.w_zaxis.get_ticklines() + self.w_zaxis.get_ticklabels():
            t.set_visible(visible)
        self.w_zaxis.line.set_visible(visible)
        self.w_zaxis.pane.set_visible(visible)
        self.w_zaxis.label.set_visible(visible)

    def draw(self, renderer):
        # set visibility of some features False
        self.set_some_features_visibility(False)
        # draw the axes
        super(MyAxes3D, self).draw(renderer)
        # set visibility of some features True.
        # This could be adapted to set your features to desired visibility,
        # e.g. storing the previous values and restoring the values
        self.set_some_features_visibility(True)

        zaxis = self.zaxis
        draw_grid_old = zaxis.axes._draw_grid
        # disable draw grid
        zaxis.axes._draw_grid = False

        tmp_planes = zaxis._PLANES

        if 'l' in self.sides_to_draw :
            # draw zaxis on the left side
            zaxis._PLANES = (tmp_planes[2], tmp_planes[3],
                             tmp_planes[0], tmp_planes[1],
                             tmp_planes[4], tmp_planes[5])
            zaxis.draw(renderer)
        if 'r' in self.sides_to_draw :
            # draw zaxis on the right side
            zaxis._PLANES = (tmp_planes[3], tmp_planes[2],
                             tmp_planes[1], tmp_planes[0],
                             tmp_planes[4], tmp_planes[5])
            zaxis.draw(renderer)

        zaxis._PLANES = tmp_planes

        # disable draw grid
        zaxis.axes._draw_grid = draw_grid_old

def example_surface(ax):
    """ draw an example surface. code borrowed from http://matplotlib.org/examples/mplot3d/surface3d_demo.html """
    from matplotlib import cm
    import numpy as np
    X = np.arange(-5, 5, 0.25)
    Y = np.arange(-5, 5, 0.25)
    X, Y = np.meshgrid(X, Y)
    R = np.sqrt(X**2 + Y**2)
    Z = np.sin(R)
    surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)

if __name__ == '__main__':
    fig = plt.figure(figsize=(15, 5))
    ax = fig.add_subplot(131, projection='3d')
    ax.set_title('z-axis left side')
    ax = fig.add_axes(MyAxes3D(ax, 'l'))
    example_surface(ax) # draw an example surface
    ax = fig.add_subplot(132, projection='3d')
    ax.set_title('z-axis both sides')
    ax = fig.add_axes(MyAxes3D(ax, 'lr'))
    example_surface(ax) # draw an example surface
    ax = fig.add_subplot(133, projection='3d')
    ax.set_title('z-axis right side')
    ax = fig.add_axes(MyAxes3D(ax, 'r'))
    example_surface(ax) # draw an example surface
    plt.show()

rawDescription: Changing position of vertical (z) axis of 3D plot (Matplotlib)?


code:
def Split():
  separate = []
  with open('myFile1.txt','r') as inFile:
    for line in inFile:
      separate.append(line.split())
  return(separate)

rawDescription: Python Text Files to list of strings

description: Python Text Files to list of strings


rawDescription: How to Slice A List by Passing A List or A Tuple Returned By A Function in Python?


code:
import win32com.client as win32
excel = win32.Dispatch("Excel.Application")
workbook = excel.Workbooks.Add()
workbook.SaveAs(new_file_path+'/UpdatedSheet.xls')

rawDescription: Creating a new Excel File in pywin32

description: Creating a new Excel File in pywin32


code:
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self, a, b):
        self.write("a:%s b:%s" % (a, b))

if __name__ == "__main__":
    application = tornado.web.Application([
        (r"/([a-z]+)/([a-z]+)/", MainHandler),
    ])
    application.listen(8888)
    tornado.ioloop.IOLoop.current().start()

rawDescription: Hot to use Tornado to get the url parameter?


code:
def read_multi_shp(path):
    """
    copied from read_shp, but allowing MultiDiGraph instead.
    """
    try:
        from osgeo import ogr
    except ImportError:
        raise ImportError("read_shp requires OGR: http://www.gdal.org/")

    net = nx.MultiDiGraph() # <--- here is the main change I made

    def getfieldinfo(lyr, feature, flds):
            f = feature
            return [f.GetField(f.GetFieldIndex(x)) for x in flds]

    def addlyr(lyr, fields):
        for findex in xrange(lyr.GetFeatureCount()):
            f = lyr.GetFeature(findex)
            flddata = getfieldinfo(lyr, f, fields)
            g = f.geometry()
            attributes = dict(zip(fields, flddata))
            attributes["ShpName"] = lyr.GetName()
            if g.GetGeometryType() == 1:  # point
                net.add_node((g.GetPoint_2D(0)), attributes)
            if g.GetGeometryType() == 2:  # linestring
                attributes["Wkb"] = g.ExportToWkb()
                attributes["Wkt"] = g.ExportToWkt()
                attributes["Json"] = g.ExportToJson()
                last = g.GetPointCount() - 1
                net.add_edge(g.GetPoint_2D(0), g.GetPoint_2D(last), attr_dict=attributes) #<--- also changed this line

    if isinstance(path, str):
        shp = ogr.Open(path)
        lyrcount = shp.GetLayerCount()  # multiple layers indicate a directory
        for lyrindex in xrange(lyrcount):
            lyr = shp.GetLayerByIndex(lyrindex)
            flds = [x.GetName() for x in lyr.schema]
            addlyr(lyr, flds)
    return net

rawDescription: NetworkX - How to create MultiDiGraph from Shapefile?


code:
import wx

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

        self.panel = wx.Panel(self)
        self.button = wx.Button(self.panel, label="Test")

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.button)

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

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

rawDescription: Confused on how to structure the GUI (wxpython)


code:
def x_in_y(query, base):
    try:
        l = len(query)
    except TypeError:
        l = 1
        query = type(base)((query,))

    for i in range(len(base)):
        if base[i:i+l] == query:
            return True
    return False

rawDescription: How to check subsequence exists in a list?

description: Check subsequence exists in a list


code:
for key, value in dict_of_defaults.items():
    dict_maybe_without_defaults.setdefault(key, value)

rawDescription: How to update a python dict with default key:value pairs given in another dict

description: Update a python dict with default key:value pairs given in another dict


code:
from BeautifulSoup import BeautifulSoup
from markdown import markdown

html = markdown(some_html_string)
text = ''.join(BeautifulSoup(html).findAll(text=True))

rawDescription: Python : How to convert markdown formatted text to text


code:
def extract_args(expr):
    paren = 0
    start = 0
    ret = []
    for i, c in enumerate(expr):
        if c=='(':
            paren+=1
            if paren==1:
                start=i+1
        elif c==')':
            if paren==1 and start:
                ret.append(expr[start: i])
            paren-=1
        elif c==',' and paren==1:
            ret.append(expr[start:i])
            start=i+1
    return ret

rawDescription: Regular Expression to Extract Expression from Function?


code:
import glob
from win32com.client import Dispatch

Sheet = 'OUTPUT'
excel = Dispatch("Excel.Application")

for filename in glob.glob("D:/apera/Workspace/Sounding/sounding*.xlsx"):
    source = excel.Workbooks.Open(filename)
    source.Worksheets(Sheet).Range('F1:H500').Copy()
    source.Worksheets(Sheet).Range('I1:K500').PasteSpecial(Paste=-4163)

rawDescription: open multiple excel files with win32com python

description: Open multiple excel files with win32com python


code:
f = open('file.txt','r')
print(f.readlines())

rawDescription: readlines() function in Python

description: Readlines() function in Python


code:
df[['word2', 'tag2']] = df.shift(-1)
df

rawDescription: Pandas: Add new columns using iterative values of other columns


code: B1 = [(float(a[1]),float(a[-2])) for a in (b.split("'") for b in B)]

rawDescription: How do I extract int values from string?

description: Extract int values from string


code:
def quickSrt(lst):
    if len(lst) < 2:
        return lst
    pivot = lst[0]
    l = quickSrt([x for x in lst[1:] if x < pivot])
    r = quickSrt([x for x in lst[1:] if x >= pivot])
    return l + [pivot] + r

k = [1,2,3,5,3,1,6,3]
d = {}
for i in k:
 if i in d:
   d[i] += 1
 else:
   d[i] = 1

values = [value for key, value in d.items()]
val = quickSrt(values)

for x,y in d.items():
  if y == val[-1]:
    print(x)

rawDescription: Python 2.7 Mode of list without using built-in functions


code: imp_obj = __import__('re')

rawDescription: Python if_py and VIM: exec('import re') does not work


code:
billdate = datetime.datetime(billdate.year, billdate.month, billdate.day)
billdate

rawDescription: python substract months from datetime object

description: Python substract months from datetime object


code:
class BorgLike:
    _shared = 'default'
    def __init__(self, unique):
        self.unique = unique
    @property
    def shared(self):
        return BorgLike._shared
    @shared.setter
    def shared(self, value):
        BorgLike._shared = value

rawDescription: Creating a slightly borg-like class

description: Creating a slightly borg-like class


code:
t = 0
fig = plt.figure()
axes_list = []
while t < 16 :
     ax = fig.add_subplot(4,4,t+1)
     axes_list.append(ax)
     p1 = plot(...)
     p2 = plot(...)
     p3 = plot(...)
     p4 = plot(...)
     t = t+1
multi = MultiCursor(fig.canvas, axes_list, color='r', lw=1)
show()

rawDescription: Matplotlib multicursor.py for loop-generated subplots


code:
def get_assigned_name(frame):
  ''' Checks the bytecode of *frame* to find the name of the variable
  a result is being assigned to and returns that name. Returns the full
  left operand of the assignment. Raises a `ValueError` if the variable
  name could not be retrieved from the bytecode (eg. if an unpack sequence
  is on the left side of the assignment).

      >>> var = get_assigned_frame(sys._getframe())
      >>> assert var == 'var'
  '''

  SEARCHING, MATCHED = 1, 2
  state = SEARCHING
  result = ''
  for op in dis.get_instructions(frame.f_code):
    if state == SEARCHING and op.offset == frame.f_lasti:
      state = MATCHED
    elif state == MATCHED:
      if result:
        if op.opname == 'LOAD_ATTR':
          result += op.argval + '.'
        elif op.opname == 'STORE_ATTR':
          result += op.argval
          break
        else:
          raise ValueError('expected {LOAD_ATTR, STORE_ATTR}', op.opname)
      else:
        if op.opname in ('LOAD_NAME', 'LOAD_FAST'):
          result += op.argval + '.'
        elif op.opname in ('STORE_NAME', 'STORE_FAST'):
          result = op.argval
          break
        else:
          message = 'expected {LOAD_NAME, LOAD_FAST, STORE_NAME, STORE_FAST}'
          raise ValueError(message, op.opname)

  if not result:
    raise RuntimeError('last frame instruction not found')
  return result

rawDescription: Use output of dis module?

description: Use output of dis module


rawDescription: Subtract two arrays, keep only values where the other has no data


code: [f() for f in flist]

rawDescription: Map function application over a list of functions without lambda in python


code:
import re
test = re.compile(r'(?:)(.*)(?:
)')
test.findall(input_string)

rawDescription: Python beautifulsoup match regex after string


code:
import boto.ec2

ec2 = boto.ec2.connect_to_region('us-west-2')
instance = get_all_instances(filters={'reservation-id': 'r-50b4f837'})[0].instances[0]

rawDescription: How to find the sequence number of a key value pair in a list

description: Find the sequence number of a key value pair in a list


code:
batchIDlist = []

for s3_file in bucket.list(prefix='Download/test_queue1/'):
    batchID = str((s3_file.name).split("/"))[32:-13]

    if batchID not in batchIDlist:
        batchIDlist.append(batchID)

rawDescription: How to get a unique list of objects from AWS S3 bucket

description: Get a unique list of objects from AWS S3 bucket


code:
import time

def worker(n):
    print('worker %d' % n)
    time.sleep(1)
    return

rawDescription: Is using the args syntax in Python multiprocessing always necessary?


code:
tkF.askopenfilename(initialdir='D:\\',
filetypes=myFormat,
title="Open a .mydoc",
defaultextension=".mydoc")

rawDescription: How to have windows automatically add an extension to a file? (Python, Tkinter)

description: Have windows automatically add an extension to a file? (Python, Tkinter)


code: DEBUG = (sys.argv[1] == 'runserver')

rawDescription: Determine if Django is running on localhost


code:
# Your test file
import os

class YourTest(...):

    def setUp(self):
        self.mox = mox.Mox()

    def tearDown(self):
        self.mox.UnsetStubs()

    # Your test
    def testFoo(self):
        self.mox.StubOutWithMock(os, 'listdir')

        # the calls you expect to listdir, and what they should return
        os.listdir("some path").AndReturn([...])

        self.mox.ReplayAll()
        # ... the rest of your test

rawDescription: mocking a variable using mox

description: Mocking a variable using mox


code:
# registering for app teardown to remove session
@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()

rawDescription: How does Flask start a new SQLAlchemy transaction at the start of each request?


code:
s = 'abacdaebfxxxxxxxxxxxxxxxxxxxxxabc'
finder = lambda lst, inds, x: [lst.index(x, i) for i in inds]
finder(s, [0, 2, 3, 10], 'a')

rawDescription: get the position of every element in a list after a certain position in another list in python

description: Get the position of every element in a list after a certain position in another list in python


code:
def save(self):

    import Image as pil
    import StringIO, time, os.path
    from django.core.files.uploadedfile import InMemoryUploadedFile

    # if avatar is uploaded, we need to scale it
    if self.files['avatar']:
        # opening file as PIL instance
        img = pil.open(self.files['avatar'])

        # modifying it
        img.thumbnail((150, 150), pil.ANTIALIAS)

        # saving it to memory
        thumb_io = StringIO.StringIO()
        img.save(thumb_io,  self.files['avatar'].content_type.split('/')[-1].upper())

        # generating name for the new file
        new_file_name = str(self.instance.id) +'_avatar_' +\
                        str(int(time.time())) + \
                        os.path.splitext(self.instance.avatar.name)[1]

        # creating new InMemoryUploadedFile() based on the modified file
        file = InMemoryUploadedFile(thumb_io,
                                    u"avatar", # important to specify field name here
                                    new_file_name,
                                    self.files['avatar'].content_type,
                                    thumb_io.len,
                                    None)

        # and finally, replacing original InMemoryUploadedFile() with modified one
        self.instance.avatar = file

    # now, when form will be saved, it will use the modified file, instead of the original
    super(UserForm, self).save()

rawDescription: How to resize uploaded file with PIL before saving it?

description: Resize uploaded file with PIL before saving it


code:
def seq(s):
    if all(s[0]==x for x in s[1:]):
        return True
    elif ord(s[0]) > ord(s[1]):
        s = s[::-1]
    first = ord(s[0])
    for i in s[1:]:
        if ord(i) != first + 1:
            return False
        else:
            first = ord(i)
    return True
In [19]: seq("aaaa")
Out[19]: True

In [20]: seq("4321")
Out[20]: True

In [21]: seq("1230")
Out[21]: False

In [22]: seq("edcb")
Out[22]: True

rawDescription: Python string iteration

description: Python string iteration


code:
import struct
za, zb, zc = struct.unpack('cc32s', data)

rawDescription: how convert bytes to structure in python?

description: How convert bytes to structure in python


code:
df
df.T.stack()

rawDescription: How can I (or should I) transform this DataFrame of DataFrames into a MultiIndexed DataFrame?


code:
from itertools import islice

with open(temp_filename, 'r', newline='') as inf, \
        open(local_filename, 'w', newline='') as outf:
    reader = csv.reader(inf)
    writer = csv.writer(outf)
    next(islice(reader, 32, 32), None)  # skip 32 rows

    # write to output file with extra column
    for row in (reader):
        writer.writerow([str(ASXCode)] + row)

rawDescription: modifying a csv file creates unwanted duplicate output using seek(0) method

description: Modifying a csv file creates unwanted duplicate output using seek(0) method


code:
p0_list = ['a', 'b', 'c']
p0_noarg1 = ['b']
sp0_noarg1 = set(p0_noarg1)
p0_arg1 = [x for x in p0_list if x not in sp0_noarg1]
p1_list = [5, 100]

total_list = [x for x in itertools.product(p0_arg1, p1_list)] + [x for x in itertools.product(p0_noarg1, p1_list[:1])]

rawDescription: Python itertools product, but conditional?


code:
str1 = 'section1.1:  this is a heading for section 1'
str2 = 'section1.1:  this is a heading for section 1.1'
str1.split(':', 1)[1]
str2.split(':', 1)[1]

rawDescription: python compare subsection of 2 strings and see if they match

description: Python compare subsection of 2 strings and see if they match


rawDescription: How to replace every item in a list except last

description: Replace every item in a list except last


rawDescription: Find and replace empty rows in list width Python


code:
from collections import Counter
l = [['foo', 9283], ['bar', 7172], ['bar', 9890], ['foo', 91], ['fuubar', 8291]]
Counter(item[0] for item in l)

rawDescription: Counting occurrence of non-specified values from 2d array in Python


code:
def choose_sets(l, k):
  if k == 0:
    return [[]]
  if len(l) == 0:
    return []
  l2 = l[1:]
  subsets = choose_sets(l2, k-1)
  for s in subsets:
    s.append(l[0])
  return subsets+ choose_sets(l2, k)

rawDescription: Calculating subsets of a given list recursively


code:
def makeAdjuster(name, attr, lower, upper, step):
    def doAdjust(par):
        setattr(Bikedrawing.p, attr, par.get_value())
        panelhoriz.queue_draw()

    val = getattr(Bikedrawing.p, attr)
    adjust = gtk.Adjustment(value=val, lower=lower, upper=upper, step_incr=step)

    label = gtk.Label(name)
    topcolumn1.pack_start(label, False, False)

    scale = gtk.HScale(adjustment=adjust)
    scale.set_value_pos(gtk.POS_LEFT)
    scale.connect("value-changed", doAdjust)
    topcolumn1.pack_start(scale, True, True)

for adj in (
    ('Bottom bracket height', 'bottomBracketHeight', 180., 400., 10.),
    ('Seat tube angle', 'seatTubeAngle', 60., 80., 0.5),
    ('Seat tube length', 'seatTubeLength', 300., 700., 10.),
    ('Top tube length', 'topTubeLength', 400., 700., 10.)
):
    makeAdjuster(*adj)

rawDescription: Generate blocks of Python code with for loop


code:
def single_source_shortest_path(G,source,cutoff=None):
    level=0                  # the current level
    nextlevel={source:1}       # list of nodes to check at next level
    paths={source:[source]}  # paths dictionary  (paths to key from source)
    if cutoff==0:
        return paths
    while nextlevel:
        thislevel=nextlevel
        nextlevel={}
        for v in thislevel:
            for w in G[v]:
                if w not in paths:
                    paths[w]=paths[v]+[w]
                    nextlevel[w]=1
        level=level+1
        if (cutoff is not None and cutoff <= level):  break
    return paths

rawDescription: Source algorithm for networkx shortest_path(G[, source, target, weight]) function


code:
for line2 in set2:
    exist = False
    for line1 in set1:
        if (line2.find(line1) == 1):
                exist = True
                break

    if exist == False:
        falsepositives.append(line2)
    else:
        truepositives.append(line2)

rawDescription: Comparing text files lists python

description: Comparing text files lists python


code:
_sentinel = object()

def change_logger(name):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*arg, **kwargs):
            old_logger = func.__globals__.get('logger', _sentinel)
            func.__globals__['logger'] = logging.getLogger(name)
            try:
                result = func(*arg, **kwargs)
            finally:
                if old_logger is not _sentinel:
                    func.__globals__['logger'] = old_logger
                else:
                    del func.__globals__['logger']
            return result
        return wrapper
    return decorator

rawDescription: Is possible to use decorator to monkey patch the global variables?


code:
import pynotify
import time

pynotify.init('app name')
n=pynotify.Notification("title","Something is happening")
n.show()
time.sleep(2)
n.update("new title","2 things are happening")
n.show()

rawDescription: Is it possible to change the title of a notification?


code:
s = "AATGCAGACCTTACGTAA"
s[1]
s[-2]
start = 1
stop = -2
s[start: stop+1]

rawDescription: Extracting part of a value from a dictionary


code:
def getRoundedThresholdv1(a, MinClip):
    return round(float(a) / MinClip) * MinClip

rawDescription: Round in numpy to Nearest Step

description: Round in numpy to Nearest Step


rawDescription: Python xlwt: preserve all styles but one


code:
def time_algo(sort_fun, input_seq, num=100):
    '''
    Time how long it takes to sort sequence 'input_seq' using
    function 'sort_fun'. Take min of 'num' times.
    '''
    foo = list(input_seq)
    wrapped = wrapper(sort_fun, foo)
    def reset_foo():
        foo[:] = list(input_seq)
    return min(timeit.timeit(wrapped, setup=reset_foo, number=1) for _ in range(num))

rawDescription: Python timeit: How to initialize arguments for timed function before every repetition?


code:
from M2Crypto import SSL, httpslib

context = SSL.Context("sslv3")

# Disable certificate checking
context.set_verify(0, depth = 0)

connection = httpslib.HTTPSConnection("somehostname", 443, ssl_context=context)

# Hack (!!!) for disabling host name check <CN> == <expected host name>.
# Will affect any future SSL connections made by M2Crypto!
SSL.Connection.postConnectionCheck = None

connection.connect() # <-- this would normally raise SSL verification errors
connection.request("GET", "/")

...

rawDescription: Turn SSLchecking off in M2Crypto in Python


code:
import nose2

test_run = nose2.discover(argv = ['-s', 'path-to-tests'], exit = False)
if test_run.result.wasSuccessful():
    do_something()
else:
    do_something_else()

rawDescription: How to check test run results in nose2?

description: Check test run results in nose2


code:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt,numpy as np
plt.clf()
fig = plt.figure(1)
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = ax.contourf(X, Y, Z, zdir='z', offset=-100,
        levels=np.linspace(-100,100,1200),cmap=plt.cm.jet)
cset = ax.contourf(X, Y, Z, zdir='x', offset=-40, cmap=plt.cm.jet)
cset = ax.contourf(X, Y, Z, zdir='y', offset=40, cmap=plt.cm.jet)
ax.set_xlabel('X')
ax.set_xlim(-40, 40)
ax.set_ylabel('Y')
ax.set_ylim(-40, 40)
ax.set_zlabel('Z')
ax.set_zlim(-100, 100)
plt.show()

rawDescription: Matplotlib: imshow in 3d plot

description: Matplotlib: imshow in 3d plot


code:
Lst =[]
if entData != "stop":
    Lst.append(entData)

rawDescription: How to create a list with inputs in python 3.4?

description: Create a list with inputs in python 3.4


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

matrix = np.random.rand(100, 200)
matrix[30, 50] = 5.0
matrix[80, 150] = 5.0

plt.imshow(matrix, cmap = cm.Greys_r)

ax = plt.gca()

x,y = numpy.array([[50, 150], [30, 80]])
line = plt.Line2D(x, y, lw=5., color='r', alpha=0.4)
line.set_clip_on(False)
ax.add_line(line)

plt.show()

rawDescription: Plot over a matrix plot

description: Plot over a matrix plot


code:
for d in directories:
    if os.fork():
        # parent
        continue
    else:
        # child
        # handle d...
        break # don't keep going

rawDescription: How to create a process for each directory?

description: Create a process for each directory


code:
from django.http import HttpResponse

def download(request, file_name):
    file = open('path/to/file/{}'.format(file_name), 'rb')
    response = HttpResponse(file, content_type='application/pdf')
    response['Content-Disposition'] = "attachment; filename={}".format(file_name)
    return response

rawDescription: download file in django 1.7

description: Download file in django 1.7


code:
self.valueLine = []
for key in dbgKeys:
    self.valueLine.append('{} => '.format(dbgValues[key]['name']))
    self.valueLine.extend(['{} '.format(value) for subkey, value in dbgValues[key].items() if subkey != 'name'])
    self.valueLine.append('\n')

self.valueLine = ''.join(self.valueLine)
self.dbgText = self.text.render(self.valueLine, True, fontColor)

rawDescription: Iterating thru Dictionary Subkey/subvalue pairs - Python


code:
s = pd.Series(range.date)
s
s[0]

rawDescription: Conversion of datetime64 to datetime.date object


code:
def main():
    root = Tk()
    root.overrideredirect(1)
    root.geometry('500x250+500+200')
    app = Application(root)
    app.parent.configure(background = 'gray32')
    root.resizable(width=FALSE, height=FALSE)
    app.mainloop()

rawDescription: Python/Tkinter make a custom window

description: Python/Tkinter make a custom window


code:
import time

import wx
import wx.lib.agw.pybusyinfo as PBI

def showmsg():
    app = wx.App(redirect=False)
    msg = 'this is a test'
    title = 'Message!'
    d = PBI.PyBusyInfo(msg, title=title)
    return d

if __name__ == '__main__':
    d = showmsg()
    time.sleep(3)
    d = None

rawDescription: WxPython: How to display any message window for a fixed time them let it automatically disappear


code:
import pdb
pdb.runcall(my_wonky_function, "arg1", "arg2", *myargs)

rawDescription: Can I initiate debugging from the interactive interpreter?

description: Initiate debugging from the interactive interpreter


rawDescription: Using headers with the Python requests library's get method


code:
import datetime
time1 = datetime.datetime.strptime("6:30",'%H:%M')
time2 = datetime.datetime.strptime("7:30",'%H:%M')
difference = time2-time1
difference
difference.seconds
"{:0>8}".format(datetime.timedelta(seconds=difference.seconds))
"{:0>8}".format(datetime.timedelta(seconds=666777))

rawDescription: python django subtract time field

description: Python django subtract time field


code:
from google.appengine.tools import dev_appserver

class MyHandler(dev_appserver.ApplicationLoggingHandler):

    def __init__(self, *a, **k):
        dev_appserver.ApplicationLoggingHandler.__init__(self, *a, **k)
        self.thefile = open('/tmp/mylog.txt', 'w')

    def emit(self, record):
        dev_appserver.ApplicationLoggingHandler(self, record)
        self.thefile.write(str(record) + '\n')
        self.thefile.flush()

rawDescription: Where does GoogleAppEngineLauncher keep the local log files?


rawDescription: create new column from conditional statement without mask pandas

description: Create new column from conditional statement without mask pandas


code:
import bisect

class HelperList(object):
    """Lazily computes l[i] - i to determine values."""
    def __init__(self, l):
        super(HelperList, self).__init__()
        self.l = l
    def __len__(self):
        return len(self.l)
    def __getitem__(self, i):
        return self.l[i] - i

def count_occur(l):
    helperlist = HelperList(l)
    leftmost = bisect.bisect_left(helperlist, 0)
    if l[leftmost] != leftmost:
        return 0
    return bisect.bisect_right(helperlist, 0) - leftmost

rawDescription: Count occurrence of a values with time complexity of O(log n)


code:
from subprocess import check_output
out = check_output('tr -d "\'" < /tmp/file_1.txt > /tmp/file_2.txt', shell=True)

rawDescription: From commands to subprocess

description: From commands to subprocess


code:
#! /usr/bin/python

# Trying to do things in a separate panel based on
# events that happen in another panel

import wx

# ----- Functions

# ----- Classes
class ChkbxPanel(wx.Panel):
    # This class defines the panel that will
    # contain the checkbox
    def __init__(self, parent):
        wx.Panel.__init__(self, parent=parent, id=-1)
        # Widgets
        choices = ['one', 'two', 'three']
        prompt = 'Please Make a Choice'
        self.chkBx = wx.CheckListBox(self, choices=choices, size=(-1, 200))
        self.PromptChkBx = wx.StaticText(self, label=prompt)

        # Page Sizers
        self.panel_vertSizer = wx.BoxSizer(wx.VERTICAL)
        self.panel_vertSizer.Add(self.PromptChkBx, proportion=0,
                                 flag=wx.ALIGN_LEFT)
        self.panel_vertSizer.Add(self.chkBx, proportion=0, flag=wx.ALIGN_LEFT)

        # Invoke Sizer
        self.SetSizer(self.panel_vertSizer)

        # Make 'self' (the panel) shrink to the minimum size
        # required by the controls
        self.Fit()
        # end __init__
    # ----- Functions

class ResultsPanel(wx.Panel):
    # This class define the panel that will
    # contain the textctrl
    def __init__ (self, parent):
        wx.Panel.__init__(self, parent=parent, id=-1)
        # Widgets
        resultsPanelTitle = 'Results:'
        self.resultsTitle = wx.StaticText(self, label=resultsPanelTitle)
        self.results = wx.TextCtrl(self, size=(300, 500),
                    style=(wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_DONTWRAP))
        self.CheckedBxs = ()

        lenofcb = len(self.CheckedBxs)
        typeofcb = type(self.CheckedBxs)
        self.results.AppendText('How Many Boxes are Checkd:\n')
        self.results.AppendText(str(lenofcb) + '\n')
        self.results.AppendText(str(typeofcb) + '\n')
        # Page Sizer
        self.panel_vertSizer = wx.BoxSizer(wx.VERTICAL)
        self.panel_vertSizer.Add(self.resultsTitle, proportion=0, flag=wx.ALIGN_LEFT)
        self.panel_vertSizer.Add(self.results, proportion=0, flag=wx.ALIGN_LEFT)

        # Invoke Sizer
        self.SetSizer(self.panel_vertSizer)

        # Make 'self' (the panel) shrink to the minimum size
        # required by the controls
        self.Fit()

        # end __init__

    # ----- Functions

# ----- Main Frame
class MainFrame(wx.Frame):
    # A 2-Control Class With BoxSizers
    def __init__(self):
        # Configure the Figure
        titleText = 'Wx Question'
        wx.Frame.__init__(self, None, title=titleText
                        , size=(600, 300), style=wx.DEFAULT_FRAME_STYLE)

        # First Frame Control automatically expands to the
        # Frame's client size
        frame_panel = wx.Panel(self)

        # Create the Controls
        leftPanel = ChkbxPanel(frame_panel)
        self.rightPanel = ResultsPanel(frame_panel)

        # Create Sizers and add the controls
        panelCtrls_horzSizer = wx.BoxSizer(wx.HORIZONTAL)
        panelCtrls_horzSizer.Add(leftPanel)
        panelCtrls_horzSizer.Add(self.rightPanel)

        framePanel_vertSizer = wx.BoxSizer(wx.VERTICAL)
        framePanel_vertSizer.Add(panelCtrls_horzSizer)

        frame_panel.SetSizer(framePanel_vertSizer)
        frame_panel.Fit()
        self.SetSize((600, 600))

        leftPanel.chkBx.Bind(wx.EVT_CHECKLISTBOX, self.onCheckBox)

    def onCheckBox(self, event):
        checked = event.EventObject.CheckedStrings
        self.rightPanel.results.AppendText(
            'Checked: {0}, Qty checked: {1}\n'.format(checked, len(checked)))

# Main if statement
if __name__ == '__main__':
    app = wx.App(redirect=False)
    appFrame = MainFrame().Show()
    app.MainLoop()

rawDescription: Passing a tuple between two Panels in wxPython


code:
yourhash = {'login': u'myemail (myemail@gmail.com)'}

email = yourhash['login'].split()[1].strip("()")

print(email)
# myemail@gmail.com

rawDescription: python regexp parse

description: Python regexp parse


code:
from itertools import product
t_e_f = dict.fromkeys(product(tokens_e_set,tokens_f_set),1.0/len(tokens_e_set))

rawDescription: Compile a dictionary in the least computational costly way


code:
if info['user'] == username:
  locations = (json.loads(info['locations']) +
    [{'place': '', 'description': ''}] * 5)[:5]

  return {'date': info['date'], 'locations': locations}

rawDescription: Dynamic form field generation in Django templates


code:
import pandas as pd
import numpy as np

df = pd.read_csv('/path/to/file/')          # Load a dataframe with your file
df.index = df['my_date_field']              # set the dataframe index with your date
dfg = df.groupby(pd.TimeGrouper(freq='M'))  # group by month / alternatively use MS for Month Start / referencing the previously created object

# Finally, find the max date in each month
dfg.agg({'my_date_field': np.max})

# To specifically coerce the results of the groupby to a list:
dfg.agg({'my_date_field': np.max})['my_date_field'].tolist()

rawDescription: Get the last date of each month in a list of dates in Python


code:
import argparse

p = argparse.ArgumentParser("a foo bar dustup", usage='%(prog)s [-h] [-i INI]')
p.add_argument('-i', '--ini', help="use alternate ini file", metavar='')
p.print_help()

rawDescription: argparse help without duplicate ALLCAPS

description: Argparse help without duplicate ALLCAPS


code:
from pylab import plot, show
import numpy as np

times = np.arange(0,100,0.1)
intensities = np.random.rand(len(times))

def window(size):
    return np.ones(size)/float(size)

plot(times,intensities,'k.')
plot(times,np.convolve(intensities,window(10),'same'),'r')
plot(times,np.convolve(intensities,window(100),'same'),'b')
show()

rawDescription: Time-series averaging in numpy/python

description: Time-series averaging in numpy/python


code:
import os
using_ssh = 'SSH_CONNECTION' in os.environ

rawDescription: How can I know if the user is connected to the local machine via ssh in my python script?

description: Know if the user is connected to the local machine via ssh in my python script


code:
def checks(a,b):
    for item in a:
        if b[1] == item[1]:
           return True

    return False

rawDescription: Check if item in list

description: Check if item in list


code:
counter = 130000        # number of particles in your cloud
change = 256 / counter  # in-/de-crement for each particle

rgb = [0, 255, 0]       # starting colour (green)

for i in range(0, counter):
    rgb = [rgb[0] + change, rgb[1] - change, rgb[2] + change]
    print("i: %04d; R: %03d, G: %03d, B: %03d" % (i, rgb[0], rgb[1], rgb[2])) # for debugging only, floats to integers for legibility

rawDescription: color scale to illustrate the temperature, Python script

description: Color scale to illustrate the temperature, Python script


code:
df1.groupby(["ID", pd.TimeGrouper("d")]).sum()
df1.groupby(["ID", pd.TimeGrouper("2d")]).sum()

rawDescription: Resampling aggregation per group in Pandas


code: max(test_string.rfind(i) for i in "([{")

rawDescription: find last occurence of multiple characters in a string in Python

description: Find last occurence of multiple characters in a string in Python


code:
import rdflib
from rdflib.Graph import Graph
g = Graph()
g.parse("http://www.w3.org/2000/10/rdf-tests/rdfcore/ntriples/test.nt",
        format="nt")
g.serialize("test.rdf", format="rdf/xml")

rawDescription: Writing RDF/XML file from rdf Triples in rdflib


rawDescription: Module doesn't define an attribute/class


code:
mapping = {
    1: 'www.mywebsite.com/page_one.html',
    2: 'www.mywebsite.com/page_two.html',
    3: 'www.mywebsite.com/page_three.html',
    4: 'www.mywebsite.com/page_four.html'
}

try:
    page = mapping[choice]
except KeyError:
    print ("Invalid choice. try again...")
    # TODO: try again? :)

username = raw_input("Please, type your username\n")

url = "http://{page}/{username}".format(page=page, username=username)
html_content = urllib2.urlopen(url)

rawDescription: Choose, type and Parse with BeautifulSoup and Python syntax?


code:
def notify(regex):
    def decorate(func):
        func.regex = regex
        return func
    return decorate

class Baz(object):
    @property
    def function_list(self):
        for attr in dir(self):
            obj = getattr(self, attr)
            if callable(obj) and hasattr(obj, "regex"):
                yield obj

class FooBar(Baz):
    @notify(".*")
    def everything(self, message):
        pass

    @notify("(\w+):.*")
    def reply(self, message):
        pass

for foo in FooBar().function_list:
    print("%s => %s" % (foo.regex, foo))

rawDescription: Python decorator which set class variable


code:
def island_lakes():
    lst=[]
    x=[int(i) for i in sys.stdin.readline().split()]
    lst.extend(x)

    print(lst)

    cur_height = lst[0]
    valley_found = false
    for i in range(1, len(lst)):
        if lst[i] >= cur_height and valley_found:
            print(cur_height)
            valley_found = false
        else:
            valley_found = true

        if lst[i] >= cur_height:
            cur_height = lst[i]

    cur_height = lst[-1]
    valley_found = false
    for i in range(len(lst)-2, -1, -1):
        if lst[i] >= cur_height and valley_found:
            print(cur_height)
            valley_found = false
        else:
            valley_found = true

        if lst[i] >= cur_height:
            cur_height = lst[i]

rawDescription: Island lake algorithm

description: Island lake algorithm


code:
def scrollToColumn(self, column=0):
    visible = self.itemAt(0, 0)
    if visible is not None:
        self.scrollToItem(self.item(visible.row(), column))

rawDescription: Scroll QTableWidget to specific column

description: Scroll QTableWidget to specific column


code:
import subprocess
subprocess.Popen(['xterm', '-hold', '-e', 'nmap -sV 74.125.130.100'])

rawDescription: Sub-process in Python execute two task?

description: Sub-process in Python execute two task


code:
f = open("test.txt", "r+") # Open your text file
content = f.readlines()    # Read the lines and make a list
var = content[0].split()   # Split the list into individual words
money = var[0]             # var[0] is the first letter in the text file

rawDescription: Simple Python Coding: How do I use text files as variables?


code:
import re, os

def expandEnvironmentStrings(s):
    r= re.compile('%([^%]+)%')
    return r.sub(lambda m: os.environ.get(m.group(1), m.group(0)), s)

rawDescription: Transferring Python modules

description: Transferring Python modules


rawDescription: Fastest way to find maximum value of a list in specific intervals


code:
df.groupby(['UserID', 'DeviceID', 'TicketID']).agg({
    'TicketStatus': 'last',
    'TicketStartTime': 'first',
    'TicketEndTime': 'last'
}).reset_index()

rawDescription: Grouping Pandas Dataframe with conditions


code:
class OrderListView(ListView):
    template_name = 'doors/orders/list.html'

    def get_queryset(self):
        user = self.request.user
        if user.user_type == 1:
            return Order.objects.all()
        return Order.objects.filter(creator=user.pk)

rawDescription: Where to control permission-style viewing in Django? In the url (via generic views), template, or view?


rawDescription: Python Timer Callback Method

description: Python Timer Callback Method


rawDescription: Different order sorting on different elements in a list of list


rawDescription: Increasing the space for x axis labels in Matplotlib


code:
import numpy as np
import scipy.misc as mpl

a = mpl.imread('01background.jpg')
b = mpl.imread('02testgray.jpg')

c = a/((b.astype('float')+1)/256)
d = c*(c < 255)+255*np.ones(np.shape(c))*(c > 255)

e = d.astype('uint8')

mpl.imshow(e)
mpl.imsave('output.png', e)

rawDescription: Python PIL - function to divide blend two images?


code:
nums = [1,2,3,4,5]
[(x,y) for x in nums for y in nums]
min(_, key=lambda pair: pair[0]/pair[1])

rawDescription: Python: For each list element apply a function across the list


code:
def calc_distspd(df):
    '''Broadcast pyproj distance calculation over pandas dataframe'''

    import pyproj
    import numpy as np

    def calcdist(x):
        '''Pandas broadcast function for pyproj distance calculations'''
        return g.inv(x['lons+1'], x['lats+1'], x['lons'], x['lats'])[2]

    # Define Earth ellipsoid for dist calculations
    g = pyproj.Geod(ellps='WGS84')

    # Create array of zeros to initialize new columns
    fill_data = np.zeros(df['date'].shape)

    # Create new columns for calculated vales
    df['dist'] = fill_data
    df['sog']  = fill_data
    df['lons+1'] = fill_data
    df['lats+1'] = fill_data

    # Get list of unique animal_ids
    animal_ids = np.unique(df.animal_id.values)

    # Peform function broadcast for each individual
    for animal_id in animal_ids:
        idx = df['animal_id']==animal_id

        # Add shifted position columns for dist calculations
        df['lons+1'] = df['lons'].shift(1) # lon+1 = origin position
        df['lats+1'] = df['lats'].shift(1) # lat+1 = origin position

        # Copy 1st position over shifted column nans to prevent error
        idx2 = (idx) & (np.isnan(df[lons+1]))
        df['lons+1'][idx2] = df['lons'][idx2]
        df['lats+1'][idx2] = df['lats'][idx2]

        df['dist'][idx] = df[idx].apply(calcdist, axis=1)
        df['sog'][idx]  = df['dist']/24. # Calc hourly speed

    # Remove shifted position columns from df
    del df['lons+1']
    del df['lats+1']

    return df

rawDescription: Performing pyproj.Geod calculations over a very large pandas dataframe


rawDescription: fill_between always below plot lines

description: Fill_between always below plot lines


code:
import re
people = ["Karen", "Peter", "Joan", "Joe", "Carmen", "Nancy", "Kevin"]

phonenumbers = ["201-222-2222", "201-555-1212", "201-967-1490", "201-333-3333","201-725-3444", "201-555-1222", "201-444-4656"]

name = input("Enter person's name:")
abc = "" # Will store the name and phone number
found = False
for i in range(0, len(people)):
   if people[i].lower() == name.lower(): #checks if input name match + use method to lower all char
          abc = people[i]+" Has the number "+phonenumbers[i]
   value = people[i]
   m = ("(" + name + ".*)",value)
   if m:
       found = True
       print (people[i], phonenumbers[i]) # missing letter "s"
   else:
       print ("No matching name was found.")

print("\n"+abc)

rawDescription: Searching Names and phonenumbers

description: Searching Names and phonenumbers


code:
import itertools
import pprint

L = [{"value1": "fssd", "value2": "dsfds", "value3": "abcd", "value4": "gk"},
    {"value1": "asdasd", "value2": "asdas", "value3": "dafdd", "value4": "sdfsdf"},
    {"value1": "sdfsf", "value2": "sdfsdf", "value3": "abcd", "value4": "gk"},
    {"value1": "asddas", "value2": "asdsa", "value3": "abcd", "value4": "gk"},
    {"value1": "asdasd", "value2": "dskksks", "value3": "ldlsld", "value4": "sdlsld"}]

getvals = operator.itemgetter('value3', 'value4')

L.sort(key=getvals)

result = []
for k, g in itertools.groupby(L, getvals):
    result.append(g.next())

L[:] = result
pprint.pprint(L)

rawDescription: remove duplicates from nested dictionaries in list

description: Remove duplicates from nested dictionaries in list


rawDescription: How to convert 2D float numpy array to 2D int numpy array?

description: Convert 2D float numpy array to 2D int numpy array


code: dict(zip(cities, numbers))

rawDescription: How to build dictionary from two lists

description: Build dictionary from two lists


code:
def get_notes(self, pcb_serial_no, note_type=None):
    ''' Get notes recorded against a PCB unit, optionally
        filtered by note_type. '''
    q = sql.select([
            pcb_notes_view.pcb_serial_no,
            pcb_notes_view.note_type,
            pcb_notes_view.description,
            pcb_notes_view.username,
            pcb_notes_view.note_time
        ]).where(
            pcb_notes_view.pcb_serial_no==pcb_serial_no
        )
    if note_type is not None:
        q = q.where(pcb_notes_view.note_type==note_type)
    rows = q.execute().fetch_all()
    return len(rows) > 0 and rows

rawDescription: Default arguments and SQL queries in Python - idioms / patterns?


code:
db_types = (d[1] for d in db1_cursor.description)
db2_cursor.setinputsizes(*db_types)

rawDescription: python and cx_Oracle - dynamic cursor.setinputsizes

description: Python and cx_Oracle - dynamic cursor.setinputsizes


code:
def get_response(self, context=None):
        self.template_context.update(context)
        return render_to_response(self.template_name, self.template_context,
                                 content_type=self.response_type)

rawDescription: django render to xml like html

description: Django render to xml like html


code: data = [int(x) for x in r.readlines()]

rawDescription: Select random group of items from txt file


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

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, A4
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

def GenerujPustyArkusz(c):
    pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf'))
    c.setFont("Verdana", 8)
    s = u"Załącznik nr 2 do Regulaminu"
    c.drawString(450,750, s)

def test():
    c = canvas.Canvas("test.pdf", pagesize=letter)
    GenerujPustyArkusz(c)
    c.showPage()
    c.save()

test()

rawDescription: Django reportlab latin2 encoding

description: Django reportlab latin2 encoding


code:
#!/usr/bin/env python

from PySide import QtCore, QtGui

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        widget = QtGui.QFrame()
        widget.setObjectName("centralwidget")

        self.setCentralWidget(widget)
        self.resize(480,320)

if __name__ == '__main__':

    import sys

    app = QtGui.QApplication(sys.argv)
    app.setStyleSheet("#centralwidget { background-color: qlineargradient(spread:pad, x1:0.683, y1:1, x2:1, y2:0, stop:0 rgba(103, 103, 103,255), stop:1 rgba(144, 144, 144, 255)); }")

    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

rawDescription: Pyside Qt centralwidget set stylesheet not working


code:
class getXYCoords:

    def __init__(self, textFile):

        self.textFile = textFile
        self.polygon = []
        self.rectangle = []

        with open(self.textFile) as f:

            for line in f:
                line = line.split() #strip EOL
                if line: #lines (ie skip them)

                    # Stores values into polygon list
                    if len(line) == 8:
                        line = [int(i) for i in line]
                        self.polygon.append(line)

                    # Stores values into rectangle list
                    elif len(line) == 4:
                        line = [int(i) for i in line]
                        self.rectangle.append(line)

# Example program

if __name__ == '__main__':

    # Get XY coordinates
    coords = getXYCoords('test.txt')

    print(coords.polygon,'\n')
    print(coords.rectangle)

rawDescription: Python read XY coords from text file

description: Python read XY coords from text file


code:
for posts in recent_posts, forum_posts, search_posts, rss_posts:
    posts.append("
" + string.replace(title, '#', '') + "
")
    posts.sort()
    posts.reverse()

rawDescription: How to sort, append, revese four lines that perform same task?

description: Sort, append, revese four lines that perform same task


code: {{ value.item_total|floatformat }}

rawDescription: Remove the decimal part of a floating-point number in django?


code:
class SomeDataSerializer(serializers.HyperlinkedModelSerializer):
    #url = serializers.HyperlinkedRelatedField(view_name='data', format='html')
    owner = serializers.Field(source='owner.username')
    thumbnail_image = serializers.ImageField(source='original_image')
    ...

rawDescription: Django rest framework saving thumbnail image


code:
import pickle
@ladonize(int,rtype=int)
def Add(self, num):
    Sum.logger.debug("Adding " + str(num))
    try:
        Sum.sum = pickle.load( open( "sum.p", "rb" ) )
    except:
        pass

    Sum.sum += num
    Sum.logger.debug("sum is now " + str(Sum.sum))
    pickle.dump( Sum.sum, open( "sum.p", "wb" ) )
    return Sum.sum

rawDescription: Remember state between method calls

description: Remember state between method calls


code: from existing.file import Foo as oldFoo

rawDescription: Create new class subclassing an existing class with same name


code:
def song_download(request, song_id):
    song = Song.objects.get(id=song_id)
    fsock = open('/path/to/file.mp3', 'r')
    response = HttpResponse(fsock, mimetype='audio/mpeg')
    response['Content-Disposition'] = "attachment; filename=%s - %s.mp3" % \
                                     (song.artist, song.title)
    return response

rawDescription: Django: Serving a Download in a Generic View


rawDescription: Is it possible to get jedi autocomplete for a C++ library binded to python?


code:
def main():
    seed(1234)
    x = uniform(-2,2,100)
    y = uniform(-2,2,100)
    data = vstack((x*exp(-x**2-y**2),0.5*x*exp(-x**2-y**2),0.2*x*exp(-x**2-y**2)))
    xi = linspace(min(x), max(x))
    yi = linspace(min(y), max(y))
    zi = []
    numframes = data.shape[0]
    for ii in range(numframes):
        zi.append(griddata((x, y), data[ii], (xi[None,:], yi[:,None]), method='cubic'))

    fig = plt.figure()
    im = plt.contour(xi, yi, zi[0], 15, linewidths=0.5, colors='k')
    ax = fig.gca()
    ani = animation.FuncAnimation(fig, update_contour_plot, frames=xrange(numframes), fargs=(zi, ax, fig, xi, yi), interval=100)
    plt.colorbar(im)
    plt.show()
    return ani

def update_contour_plot(i, data,  ax, fig, xi, yi):
    ax.cla()
    im = ax.contour(xi, yi, data[i], 15, linewidths=0.5, colors='k')
    plt.title(str(i))
    return im,

rawDescription: Animation with contours matplotlib

description: Animation with contours matplotlib


code:
#!/usr/bin/env python3
import tkinter
import tkinter.simpledialog

root = tkinter.Tk()
root.withdraw()

celsius = tkinter.simpledialog.askfloat(
  'Celsius converter',
  'Enter degree Celsius: '
)
fahrenheit = (celsius * 1.8) + 32
tkinter.messagebox.showinfo(
  'Celsius converter',
  '%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' % (celsius, fahrenheit)
)

rawDescription: Need help to make a simple Celsius converter


code:
class HelloPython:
    def on_window_destroy(self, widget, data=None):
        gtk.main_quit()

    def __init__(self):
        builder = gtk.Builder()
        builder.add_from_file("HelloPython.xml")
        self.window = builder.get_object("window")
        self.label = builder.get_object("label1") # get reference to the label
        builder.connect_signals(self)

    def on_button1_clicked(self, widget):
        #widget.set_label("Hello World!") this would set the button's text
        self.label.set_text("Hello World!") # this sets the label's text

rawDescription: Trouble Updating Label Text

description: Trouble Updating Label Text


code:
# Get the total length of the line
start_len = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5

# The desired length of the line is a maximum of 10
final_len = min(start_len, 10)

# figure out how much of the line you want to draw as a fraction
ratio = 1.0 * final_len / start_len

# Adjust your second point
x2 = x1 + (x2 - x1) * ratio
y2 = y1 + (y2 - y1) * ratio

rawDescription: how to draw dynamic line segments of the same length

description: Draw dynamic line segments of the same length


code:
import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)

rawDescription: Parsing JSON responses

description: Parsing JSON responses


code:
class MainHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        http = tornado.httpclient.AsyncHTTPClient()
        http.fetch("http://friendfeed-api.com/v2/feed/bret",
               callback=self.async_callback(self.on_response))

    def on_response(self, response):
        if response.error: raise tornado.web.HTTPError(500)
        json = tornado.escape.json_decode(response.body)
        self.write("Fetched " + str(len(json["entries"])) + " entries "
                   "from the FriendFeed API")
        self.finish()

rawDescription: How to implement Comet server side with Python?

description: Implement Comet server side with Python


code:
if (event.type==pygame.KEYDOWN):
    if (event.key == pygame.K_LEFT):
            direc1 = -5

rawDescription: KeyInput won't work in python (pygame.K_LEFT)


rawDescription: How to populate a 2-d array in python?

description: Populate a 2-d array in python


code:
###### QuerySet #######
def _filter_or_exclude(self, negate, *args, **kwargs):
    if 'username' in kwargs:
        kwargs['username__iexact'] = kwargs['username']
        del kwargs['username']
    if args or kwargs:
        assert self.query.can_filter(),\
        "Cannot filter a query once a slice has been taken."
    from django.db.models import Q
    clone = self._clone()
    if negate:
        clone.query.add_q(~Q(*args, **kwargs))
    else:
        clone.query.add_q(Q(*args, **kwargs))
    return clone

from django.db.models.query import QuerySet
QuerySet._filter_or_exclude = _filter_or_exclude
######################

rawDescription: Django : How to filter users with username__iexact by default?


code:
start_urls = []

for i in range(1, 100):
    if i % 2 == 1:
        start_urls.append("http://www.qchp.org.qa/en/_layouts/SCH_Website/PractitionerDetails.aspx?UserID=" + str(i) + "&IsDlg=1")

rawDescription: Scrapy python change url

description: Scrapy python change url


code:
times = [[1,3],[10,15],[2,7],[11,13],[12,16],[5,8]]
start = [(i[0], 0) for i in times]
end = [(i[1], 1) for i in times]
# Using 0 for start and 1 for end ensures that starts are resolved before ends
times = sorted(start + end)
span_count = 0
first_s = 0
for time, is_start in times:
    if first_s == 0:
        first_s = time
    if is_start == 0:
        span_count += 1
    else:
        span_count -= 1
        if span_count == 0:
            print [first_s, time]
            first_s = 0

rawDescription: Python: Algorithm

description: Python: Algorithm


code: setattr(p.image, entry, db.Blob(image))

rawDescription: How set a dynamically generated attribute name for a Blob?


code:
import numpy as np

a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

index = [1, 3]
n_b = a.shape[0] + len(index)

not_index = np.array([k for k in range(n_b) if k not in index])

b = np.zeros((n_b, n_b), dtype=a.dtype)
b[not_index.reshape(-1,1), not_index] = a

rawDescription: Inserting rows and columns into a numpy array


code:
import csv
with open('spreadsheet.csv', 'w') as outfile:
    fp = csv.DictWriter(outfile, list_of_dicts[0].keys())
    fp.writeheader()
    fp.writerows(list_of_dicts)

rawDescription: write a list of ordered dictionaries to a csv file in python

description: Write a list of ordered dictionaries to a csv file in python


code:
def add_or_update_score(name, class_group, score):
   with lite.connect('results.db') as conn:
      # Create the table, if doesn't exist yet
      conn.execute('CREATE TABLE IF NOT EXISTS scores (name TEXT, class_group INTEGER, score INTEGER)')
      # Check if a record already exists
      if list(conn.execute('SELECT * FROM scores where name = ?', (name,))):
         # A record already exists
         conn.execute('UPDATE scores SET score = ? WHERE (name = ? AND class_group = ?)', (score, name, class_group))
      else:
         # No record exists
        conn.execute('INSERT INTO scores VALUES (?, ?, ?)', (name, class_group, score))

rawDescription: How to print ordered scores in python using SQLite

description: Print ordered scores in python using SQLite


code:
def __iter__(self):
    if self.left:
        yield from self.left
    yield self
    if self.right:
        yield from self.right

rawDescription: Reading a Binary Tree using __iter__

description: Reading a Binary Tree using __iter__


code:
url(r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/'
    r'(?P<second_slug>[-\w]+?)/'
    r'(?P<third_slug>[-\w]+?).html/$',
    'apps.Discussion.views.pricing',)

rawDescription: How to specify long url patterns using Regex so that they follow PEP8 guidelines

description: Specify long url patterns using Regex so that they follow PEP8 guidelines


code:
class MyClassEmpty(object):
  pass

class MyClassInit(object):
  def __init__(self):
    super(MyClassInit).__init__()

import dill

dill.dumps(MyClassEmpty)
dill.dumps(MyClassInit)

class MyClassInit2(object):
  def __init__(self):
    super(MyClassInit, self).__init__()

dill.dumps(MyClassInit2)

rawDescription: Why can't dill/pickle class definition?

description: Why can't dill/pickle class definition


rawDescription: How do I find the difference between two values without knowing which is larger?

description: Find the difference between two values without knowing which is larger


rawDescription: python plot horizontal line for a range of values

description: Python plot horizontal line for a range of values


code: entranche = poeme.split()

rawDescription: iterate through function arguments supposede to be lists python

description: Iterate through function arguments supposede to be lists python


code:
import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE)
out, err = process.communicate()
print(out)

rawDescription: python getoutput() equivalent in subprocess

description: Python getoutput() equivalent in subprocess


code:
s = "this is a test string"
s.split()
len(s.split()) - 1

rawDescription: How many times split has been used in breaking a sentence


code:
vals_to_save = {KEY1:names}
np.savez(npzFilename, **vals_to_save)

rawDescription: use variables as key names when using numpy savez

description: Use variables as key names when using numpy savez


code:
re.split('(and|or)', 'this and this or that')
Out[18]: ['this ', 'and', ' this ', 'or', ' that']

rawDescription: Python regex for logical operators

description: Python regex for logical operators


rawDescription: How can I re-order the values of a dictionary in python?

description: Re-order the values of a dictionary in python


code:
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.graphics import Rectangle

class PongGame(Widget):

    def __init__(self, **kwargs):
        super(PongGame, self).__init__(**kwargs)

        label = Label(text = "0")
        label.font_size = 70
        label.center_x = Window.width / 4
        label.top = Window.height - 50
        self.add_widget(label)

        with self.canvas:
            Rectangle(pos = (Window.width/2 - 5, 0), size = (10,Window.height))

class PongApp(App):
    def build(self):
        return PongGame()

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

rawDescription: Kivy Pong Game Translation

description: Kivy Pong Game Translation


code:
def main():
        maxNumber = 5000
        diff = 1000

        p = {}
        quickCache = {}

        for i in range(maxNumber):
            p[i] = i * (3 * i - 1 ) / 2

        def quickCheck(n):
            if n in quickCache: return quickCache[n]
            partial_c = (sqrt(1 + 24 * (n)))/-6
            c = 1/6 + partial_c
            if int(c.real) == c.real:
                    quickCache[n] = True
                    return True
            c = c - 2*partial_c
            if int(c.real) == c.real:
                    quickCache[n] = True
                    return True
            quickCache[n] = False
            return False

        for i in range(1, maxNumber):
                mi = p[i]
                for g in range(i+1, maxNumber):
                        ma = p[g]
                        if ma - mi < diff and quickCheck(ma - mi) and quickCheck(ma + mi):
                                print('New couple ', ma, mi)
                                diff = ma - mi

rawDescription: Python code optimization (20x slower than C)


code:
def SearchIt(self,e):
    for i in range(self.rtb.GetNumberOfLines()):
        line = self.rtb.GetLineText(i)
        if self.text in line:
            print(line)

rawDescription: wxPython search word in TextCrl

description: WxPython search word in TextCrl


code:
server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

port = server_sock.getsockname()[1]

uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

advertise_service(server_sock, "SampleServer",
                  service_id = uuid,
                  service_classes = [ uuid, SERIAL_PORT_CLASS ],
                  profiles = [ SERIAL_PORT_PROFILE ],
                  )

rawDescription: Bluetooth server with Python 3.3

description: Bluetooth server with Python 3.3


code:
def uptime(series):
    return (series.max() - series.min()).total_seconds()

uptime_each_day = df.groupby(
    df.datetime.apply(lambda x: x.date())
).apply(lambda grp: uptime(grp.datetime))

rawDescription: pandas time range per day

description: Pandas time range per day


code:
class MainWindow(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)

        self.resize(800, 600)

        self.layout = QtGui.QVBoxLayout(self)
        self.tree_view = QtGui.QTreeView(self)
        self.layout.addWidget(self.tree_view)

        entry = FakeEntry('foo', 0, children=[])
        self.model = MyModel([entry])
        self.tree_view.setModel(self.model)
        self.tree_view.setFirstColumnSpanned(0, QtCore.QModelIndex(), True)

rawDescription: spanning multiple columns, using QTreeView and QAbstractItemModel

description: Spanning multiple columns, using QTreeView and QAbstractItemModel


code:
from datetime import datetime
class Article:
    published = datetime.now()

    def __init__(self):
        for propname in "year month day hour minute second".split():
            setattr(self, propname, getattr(self.published, propname))

rawDescription: Is using 'exec' under controlled conditions a security threat?


code:
#my python3 script
import subprocess
subprocess.call(["python2", "python2scipt.py"])

rawDescription: How to run python script from python with different interpreter version?

description: Run python script from python with different interpreter version


rawDescription: Working with relative paths

description: Working with relative paths


code:
import mcrypt
import base64

KEY = 'xxx'
IV = 'xxx'
ALGORITHM = 'tripledes'
MODE = 'ecb'

def encrypt(data):
    cryptor = mcrypt.MCRYPT(ALGORITHM, MODE)
    cryptor.init(KEY, IV)
    return base64.b64encode(cryptor.encrypt(data))

def decrypt(data):
    cryptor = mcrypt.MCRYPT(ALGORITHM, MODE)
    cryptor.init(KEY, IV)
    return cryptor.decrypt(base64.b64decode(data))

rawDescription: python equivalent for php mcrypt tripledes

description: Python equivalent for php mcrypt tripledes


code:
import os
from random import choice
from flask import url_for, render_template

@app.route('/random_image')
def random_image():
    names = os.listdir(os.path.join(app.static_folder, 'imgs'))
    img_url = url_for('static', filename=os.path.join('imgs', choice(names)))

    return render_template('random_image.html', img_url=img_url)

rawDescription: How to list all image files in Flask static subdirectory?

description: List all image files in Flask static subdirectory


code:
set_value(value, name=None, type=None, kind=None,
          id=None, nr=None,by_label=False,
          # by_label is deprecated
          label=None)

rawDescription: how do I set a field with a duplicate name of another field in mechanize?

description: Set a field with a duplicate name of another field in mechanize


code:
myList = ["Bob1", "Bob2", "Bob3", "Bob4"]
range(1, len(myList) + 1)

rawDescription: Converting string list into integer list beginning from 1


rawDescription: Beginner - GUI toggle button

description: Beginner - GUI toggle button


code:
with open('a.html', 'r') as report:
    data = report.read()
data = data.replace('$name', 'aakash')
with open('out.html', 'w') as newf:
    newf.write(data)

rawDescription: Conversion of shell script to python script


code:
for elem in doc.xpath('//*[@id]', namespaces={'leg':'http://www.lexis-nexis.com/glp/leg'}):
    elem.attrib['id'] = re.sub(r'([^a-zA-Z0-9\.\_])', '', elem.attrib['id'])

# don't forget to write changes back to the disk if necessary

rawDescription: getting attribute value updated by removing special characters using lxml

description: Getting attribute value updated by removing special characters using lxml


code:
from PyQt4 import QtGui
import sys

class Test(QtGui.QWidget):
    def __init__(self):
        super().__init__()
        layout = QtGui.QVBoxLayout(self)

        gBBackupFromIntExt = QtGui.QGroupBox()
        layout.addWidget(gBBackupFromIntExt)

        bGBackupFromIntExt = QtGui.QButtonGroup(self)

        self.rBBackupFromExt = QtGui.QRadioButton()
        bGBackupFromIntExt.addButton(self.rBBackupFromExt)
        layout.addWidget(self.rBBackupFromExt)

        self.rBBackupFromInt = QtGui.QRadioButton()
        bGBackupFromIntExt.addButton(self.rBBackupFromInt)
        layout.addWidget(self.rBBackupFromInt)

        gBBackupToIntExt = QtGui.QGroupBox()
        layout.addWidget(gBBackupToIntExt)

        bGBackupToIntExt = QtGui.QButtonGroup(self)

        self.rBBackupToExt = QtGui.QRadioButton()
        bGBackupToIntExt.addButton (self.rBBackupToExt)
        layout.addWidget(self.rBBackupToExt)

        self.rBBackupToInt = QtGui.QRadioButton()
        bGBackupToIntExt.addButton (self.rBBackupToInt)
        layout.addWidget(self.rBBackupToInt)

a = QtGui.QApplication(sys.argv)
t = Test()
t.show()
a.exec()

rawDescription: Multiple QButtonGroups in one window

description: Multiple QButtonGroups in one window


rawDescription: Replace single backslash into double backslash with Python


code:
items = []
for i in range(10):
    items.append(myClass())

rawDescription: Creating a variable number of class instances


code: returnValues = [foo() for x in xrange(5)]

rawDescription: Python - generate array of returns from function that changes its return value


code:
location_in  = 'London, Greater London, England, United Kingdom'
locations    = location_in.split(', ')
location_out = [', '.join(locations[n:]) for n in range(len(locations))]

rawDescription: Python - convert comma separated string into reducing string list


code:
"""
client module for memcached (memory cache daemon)

Overview
========

See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

Usage summary
=============

This should give you a feel for how this module operates::

    import memcache
    mc = memcache.Client(['127.0.0.1:11211'], debug=0)

    mc.set("some_key", "Some value")
    value = mc.get("some_key")

    mc.set("another_key", 3)
    mc.delete("another_key")

    mc.set("key", "1")   # note that the key used for incr/decr must be a string.
    mc.incr("key")
    mc.decr("key")

The standard way to use memcache with a database is like this::

    key = derive_key(obj)
    obj = mc.get(key)
    if not obj:
        obj = backend_api.get(...)
        mc.set(key, obj)

    # we now have obj, and future passes through this code
    # will use the object from the cache.

Detailed Documentation
======================

More detailed documentation is available in the L{Client} class.
"""

rawDescription: Good examples of python-memcache (memcached) being used in Python?


code: reload(three)

rawDescription: delete *.pyc

description: Delete *.pyc


code:
import codecs

# First create a Python UTF-8 string
st = "b%C3%BCrokommunikation"
encoded_string = urllib2.unquote(st).decode('utf-8')

# Write it to file keeping the encoding
with codecs.open('my_file.txt', 'w', 'utf-8') as f:
    f.write(encoded_string)

rawDescription: URL component % and \x

description: URL component % and \x


rawDescription: find common elements in lists

description: Find common elements in lists


code:
from datetime import datetime
a = datetime.strptime("Thu, 15 Jan 2015 06:35:37 GMT", "%a, %d %b %Y %H:%M:%S GMT", )
b = datetime.strptime("Fri, 16 Jan 2015 07:40:40 GMT", "%a, %d %b %Y %H:%M:%S GMT", )
c1 = b - a
c1
c1.days
c1.total_seconds()
c1.seconds

rawDescription: Compare date with current date in python


code:
import numpy
a = numpy.array(range(9)).reshape((3,3))
b = numpy.zeros(tuple(s+2 for s in a.shape), a.dtype)
b[tuple(slice(1,-1) for s in a.shape)] = a
b

rawDescription: How do I add a guard ring to a matrix in NumPy?

description: Add a guard ring to a matrix in NumPy


code: da_ms = da.resample('MS', dim='time', how='mean')

rawDescription: Pandas Panel resampling alternatives

description: Pandas Panel resampling alternatives


code:
a=np.array([np.nan,1,2,3,4,np.nan])
mask=~np.isnan(a)
maskedA=a[mask]

#... Plot maskedA here, continue working with a as you normally would.

rawDescription: matplotlib issues when nan first in list

description: Matplotlib issues when nan first in list


code:
query = (
    session.query(Post)
           .join(Post.tags)     # It's necessary to join the "children" of Post
           .filter(Post.date_out.between(start_date, end_date))
           # here comes the magic:
           # you can filter with Tag, even though it was not directly joined)
           .filter(Tag.accepted == 1)
)

rawDescription: SQLAlchemy how to filter by children in many to many


code:
from wsgiref.simple_server import make_server
import datetime

def application(environ, start_response):
    start_response('200 OK', [('Content-type', 'text/plain')])
    retval = [
            str(environ),
            "\n",
            "Hello world!\n",
            str(datetime.datetime.now())
            ]
    return retval

make_server('localhost', 6548, application).serve_forever()

rawDescription: Run a little HTTP server to check callback


rawDescription: Unique items in python list

description: Unique items in python list


rawDescription: Importing module with a local name using importlib


code:
ind = np.where(~np.isnan(a))[0]
first, last = ind[0], ind[-1]
a[:first] = a[first]
a[last + 1:] = a[last]

rawDescription: Replace NaN's in NumPy array with closest non-NaN value