code:
from datetime import datetime
import webbrowser

name = raw_input("What's your name?")
print ("Hello %s! Let me set an alarm for you. Please answer the following questions about when you want to wake up.")%(name)
alarm_h = raw_input("--> Please enter the hour when I should wake you up:")
alarm_m = raw_input("--> Please enter the exact minute of the hour:")
alarm_sound = raw_input("--> Please enter the Youtube-URL of your favorite song:")

now = datetime.today()

print ("It's now %s h : %s m. We'll wake you up at %s h : %s m." %(now.hour, now.minute, alarm_h, alarm_m))

webbrowser.open(alarm_sound, new=2) #Added temporarily to test webbrowser functionality

if str(now.hour) == alarm_h and str(now.minute) == alarm_m: #Converted integer type to string type to match datatype of alarm_h and alarm_m
    webbrowser.open(alarm_sound, new=2)

rawDescription: Very basic alarm clock does not open webbrowser


code:
thr = 0.95
# Is cumulative sum exceeds some threshold
is_exceeds = np.cumsum(sklearn_pca.explained_variance_ratio_) >= thr
# Which minimal index provides such variance
# We need to add 1 to get minimum number of eigenvectors for saving this variance
k = np.min(np.where(is_exceeds))+1
# Or you can just initialize your model with thr parameter
sklearn_pca = PCA(n_components = thr)

rawDescription: project PCA back into original scales with explained_variance_ratio_ condition

description: Project PCA back into original scales with explained_variance_ratio_ condition


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import kde

np.random.seed(1977)

# Generate 200 correlated x,y points
data = np.random.multivariate_normal([0, 0], [[1, 0.5], [0.5, 3]], 200)
x, y = data.T

nbins = 20

fig, axes = plt.subplots(ncols=2, nrows=2, sharex=True, sharey=True)

axes[0, 0].set_title('Scatterplot')
axes[0, 0].plot(x, y, 'ko')

axes[0, 1].set_title('Hexbin plot')
axes[0, 1].hexbin(x, y, gridsize=nbins)

axes[1, 0].set_title('2D Histogram')
axes[1, 0].hist2d(x, y, bins=nbins)

# Evaluate a gaussian kde on a regular grid of nbins x nbins over data extents
k = kde.gaussian_kde(data.T)
xi, yi = np.mgrid[x.min():x.max():nbins*1j, y.min():y.max():nbins*1j]
zi = k(np.vstack([xi.flatten(), yi.flatten()]))

axes[1, 1].set_title('Gaussian KDE')
axes[1, 1].pcolormesh(xi, yi, zi.reshape(xi.shape))

fig.tight_layout()
plt.show()

rawDescription: Scatterplot Contours In Matplotlib

description: Scatterplot Contours In Matplotlib


code:
from collections import defaultdict
import re

filedict = defaultdict(list)
for filename in glob.glob( "*.csv" ) :
    result = re.match(r'([^\d]+)', filename)
    if result:
        filedict[result.group(1)].append(filename)

rawDescription: Loop over file list into dictionary; based on string


code: bytes = struct.pack('4s','name')

rawDescription: passing large number of arguments to struct.pack

description: Passing large number of arguments to struct.pack


code:
from PIL import Image
from PIL import ImageChops

a = Image.open("pict1.jpg")
b = Image.open("pict2.jpg")
diff = ImageChops.difference (a, b)
RED = ('red')
RL = Image.new('RGB', diff.size, RED) # Make a red layer the same size
RedDiff = ImageChops.multiply(RL, diff)
Result = ImageChops.blend(RedDiff, b, 0.7)
Result.show()

rawDescription: Color in red diffrencies between two pictures


rawDescription: how to make the bar long as much as the main windows

description: Make the bar long as much as the main windows


code:
br.select_form()  # <----- pick a form
br['format'] = 'plain_text'

rawDescription: How to use mechanize in python to input a string into a certain part of a form?

description: Use mechanize in python to input a string into a certain part of a form


code:
soup = BeautifulSoup(data, "lxml")  # needs lxml to be installed
soup = BeautifulSoup(data, "html5lib")  # needs html5lib to be installed
soup = BeautifulSoup(data, "html.parser")  # uses built-in html.parser

rawDescription: Beautiful Soup filter function fails to find all rows of a table


code:
from scrapy.http import Request
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from fundPrice.items import FundPriceItem

class PruSpider(BaseSpider):
    name = "prufunds"
    allowed_domains = ["prudential.com.hk"]
    start_urls = ["http://www.prudential.com.hk/PruServlet?module=fund&purpose=searchHistFund&fundCd=MMFU_U"]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        funds_U = hxs.select('//table//table//table//table//select[@class="fundDropdown"]//option//@value').extract()
        funds_U = [x for x in funds_U if x != (u"#" and u"MMFU_U")]

        for fund_U in funds_U:
            yield Request(
                url="http://www.prudential.com.hk/PruServlet?module=fund&purpose=searchHistFund&fundCd=" + fund_U,
                callback=self.parse_fund,
                meta={'fund': fund_U})

    def parse_fund(self, response):
        hxs = HtmlXPathSelector(response)
        item = FundPriceItem()
        item['fund'] = response.meta['fund']
        item['data'] = hxs.select(
            '//table//table//table//table//td[@class="fundPriceCell1" or @class="fundPriceCell2"]//text()').extract()
        return item

rawDescription: Newbie: How to scrape multiple web pages with only one start_urls?


code:
import pkg_resources

class Sound():
    def __init__(self):
        sound_path = pkg_resources.resource_filename(
            'my_application', 'sound.mp3')
        self.cmd = ['mplayer', sound_path]

    ...

rawDescription: How can I make sure that python finds the necessary data files?

description: Make sure that python finds the necessary data files


code:
def nest(d):
    rv = {}
    for key, value in d.iteritems():
        node = rv
        for part in key.split('/'):
            node = node.setdefault(part, {})
        node.update(value)
    return rv

rawDescription: Need to create a layered dict from a flat one


code:
import sys

def get_location(name):
    fullpath = 'locations.' + name
    package = __import__(fullpath)
    module = sys.modules[fullpath]
    return getattr(module, name.title() + 'Location')

rawDescription: python metaprogramming

description: Python metaprogramming


code:
from bs4 import BeautifulSoup
import requests
import sys

r  = requests.get("http://evamsharma.finosus.com/beatles/index.html")

data = r.text

soup = BeautifulSoup(data)
counter = 0
for table in soup.find_all('table'):
    for row in soup.find_all('tr'):
        # try:
        #     td = row.find_all('td')[0]
        # except IndexError:
        #     continue
        # for link in td.find_all(["a","p"]):
        #     title = str(link.contents)
        #     title = list(title)
        #     i = 0
        #     while i <= 2:
        #         del title[0]
        #         i += 1
        #     i = 0
        #     while i <= 1:
        #         del title[-1]
        #         i += 1
        #     title = ''.join(title)
        #     print(title)

        try:
            tdyear = row.find_all('td')[1] #This is the faulty index
        except IndexError:
            print("whoops darn!")
            continue
        year = ''.join(tdyear.contents)
        print(year)

rawDescription: Python BeautifulSoup sorting `td` tags by index, [0] and [2] work but not [1]


code:
import graphlab
sf = graphlab.SFrame.read_csv('my_data.csv')
m = graphlab.recommender.create(data)
recs = m.recommend()

rawDescription: Collaborative filtering in Python

description: Collaborative filtering in Python


code: self.root.after(100, self.execute) # 100ms = 0.1 second

rawDescription: Tkinterr, Remove focus from execute button so app doesn't appear frozen


code:
import pandas as pd

df = pd.DataFrame(range(4),index=['Andrew', 'Bob', 'Calvin','yosef'])

df.ix[[x for x in df.index if x=='Bob']]

df.ix[[x for x in df.index if x[0]=='A']]

df.ix[[x for x in df.index if x.islower()]]

rawDescription: Pandas - filter and regex search the index of DataFrame


code:
import xml.dom.minidom

xml = xml.dom.minidom.parse(xml_fname)
# or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = xml.toprettyxml()

rawDescription: Create/parse an xml file using python

description: Create/parse an xml file using python


rawDescription: How to call a python function with no parameters in a jinja2 template

description: Call a python function with no parameters in a jinja2 template


code:
from multiprocessing import Pool
import socket
import time

def lookup(host):
    return socket.gethostbyname(host)

if __name__ == "__main__":
    pool = Pool(processes=4)
    result = pool.apply_async(lookup, ("google.com",))
    done = 0
    while done < 60: # Here we do something weird while domain lookups work in background
        print(done)
        done += 1
        time.sleep(1)

    # Now we need the domain details so we get em
    print(result.get(1)) # 1 second timeout since it already had 60 seconds to process

rawDescription: Non-blocking hostname resolving?

description: Non-blocking hostname resolving


code:
version = '1.0'
parser.add_argument('--version', action='version', version='%(prog)s {}'.format(version))

rawDescription: Inserting variables inside .add_argument version


code:
i = [a,b,c,d,e,f,g,h]
base = [a,b,c,d,e,f,g,h]
random.shuffle(i)

j = [1,2,3,4,5,6,7,8]

del j[base.index(i[0])]

rawDescription: Python: Deleting a list element based on elements from another list


code:
import psutil

# spawn children and/or launch process pool here

parent = psutil.Process()
parent.nice(psutil.BELOW_NORMAL_PRIORITY_CLASS)
for child in parent.children():
    child.nice(psutil.BELOW_NORMAL_PRIORITY_CLASS)

rawDescription: Lowering process priority of multiprocessing.Pool on Windows


code:
from random import randint

class Map:
    def __init__(self, width, height):
        self.width  = width
        self.height = height
        self.map    = [[randint(0, 100) for y in range(height)] for x in range(width)]

    def neighbor_fn(self, i, j, fn=lambda x: x > 50):
        left     = i - 1
        right    = i + 1
        above    = j - 1
        below    = j + 1
        do_left  = left >= 0
        do_right = right < self.width
        do_above = above >= 0
        do_below = below < self.height
        return (
              (do_left  and do_above  and fn(self.map[left][above]))
            + (do_above               and fn(self.map[i][above]))
            + (do_right and do_above  and fn(self.map[right][above]))
            + (do_left                and fn(self.map[left][j]))
            + (do_right               and fn(self.map[right][j]))
            + (do_left  and do_below  and fn(self.map[left][below]))
            + (do_below               and fn(self.map[i][below]))
            + (do_right and do_below  and fn(self.map[right][below]))
        )

rawDescription: python checking surrounding points list of lists index out of range

description: Python checking surrounding points list of lists index out of range


code:
fileRecord = ['Raj,Joy', 'Smith,John', 'Campbell,Michelle']
fileScores = [[9, 8, 1], [8], [5, 7, 9]]
comb = []
for record, scores in zip(fileRecord, fileScores):
    for score in scores:
        comb.append((record, score))

comb

comb.sort(key=lambda item: item[1], reverse=True)
comb

rawDescription: Outputting items in two combined lists in descending numerical order?


code:
import wx
app = wx.PySimpleApp()
frame = wx.Frame(None, -1, 'Test')
sizer = wx.BoxSizer(wx.VERTICAL)
panel = wx.Panel(frame, -1, size=(100,100), style=wx.BORDER_RAISED)
sizer.Add(panel)
frame.SetSizer(sizer)
frame.Show()
app.MainLoop()

rawDescription: wx.Panel scales to fit entire parent Frame despite giving it a size

description: Wx.Panel scales to fit entire parent Frame despite giving it a size


rawDescription: python: multiply two colums of nd-arrays to get the vector of same dimensions?

description: Python: multiply two colums of nd-arrays to get the vector of same dimensions


code:
class Jambi(object):
    def do_something(self):
        print(type(self))

class User(Jambi):
    def __init__(self):
        pass

x = User()

x.do_something()

rawDescription: Looking for a way to have class method that is aware of which subclass called it


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

for t in range(0,10):
    imshow(a)
    show()

    for i in range(0,a.shape[0]):
        for j in range(0,a.shape[1]):
            a[i][j] += 1

rawDescription: Display numpy array in a for loop using matplotlib imshow


code:
import collections
def shiftMatrix(matrix, layers, num,rotate_direction):
    for count in range(layers):
        temp1 = []
        i = count
        for j in range(count, num - count):
            temp1.append(matrix[i][j])
        j = num - 1 - count
        for i in range(1 + count, num - count -1):
            temp1.append(matrix[i][j])
        i = num - 1 - count
        for j in range(num - 1 - count, -1 + count, -1):
            temp1.append(matrix[i][j])
        j = count
        for i in range(num - 1 - count - 1, 0 + count, -1):
            temp1.append(matrix[i][j])
        temp = collections.deque(temp1)
        temp.rotate(rotate_direction)
        temp1 = list(temp)
        counter = 0
        i = count
        for j in range(count, num - count):
            matrix[i][j] = temp1[counter]
            counter += 1
        j = num - 1 - count
        for i in range(1 + count, num - count -1):
            matrix[i][j] = temp1[counter]
            counter += 1
        i = num - 1 - count
        for j in range(num - 1 - count, -1 + count, -1):
            matrix[i][j] = temp1[counter]
            counter += 1
        j = count
        for i in range(num - 1 - count - 1, 0 + count, -1):
            matrix[i][j] = temp1[counter]
            counter += 1
        return matrix

if __name__ == '__main__':
    num = int(raw_input())
    op_type = raw_input()
    matrix = []
    for i in range(num):
        temp = []
        input_string = raw_input().split()
        for element in input_string:
            temp.append(int(element))
        matrix.append(temp)
    if(num >= 3):
        layers = num - 3 + 1
    else:
        layers = 1
    if(op_type == "CW"):
        matrix_result = shiftMatrix(matrix,layers,num,1);
    else:
        matrix_result = shiftMatrix(matrix,layers,num,-1);
    print(" ".join((" ".join(map(str,element))) for element in matrix_result))

rawDescription: Clockwise Shifting a Matrix

description: Clockwise Shifting a Matrix


code:
def myKeyFunc( aString ):
    stuff, x, label = aString.partition(' x ')
    return label

aList.sort( key= myKeyFunc )

rawDescription: python, sorting a list by a key that's a substring of each element

description: Python, sorting a list by a key that's a substring of each element


code:
mydict = {'foo':'bar'}
next(iter(mydict))

rawDescription: Given dictionary as function argument, need to get its key


code: sys.ps1 = type('PS1', (object,), {'__repr__': lambda self: datetime.datetime.now().strftime('%H:%M:%S')})()

rawDescription: Write a one-off or anonymous class in Python?


code:
from Tkinter import *
from functools import partial

events = []  # place to store the instances

class agendaEvent:

    ...

def addOne(master):
    events.append(agendaEvent(master))  # store the new instance in the list

def addEvent():
    ...

def done(windowInstance):
    for event in events:
        ...  # use event.time, event.date, etc.
    windowInstance.destroy()
    windowInstance = ""

root = Tk()

addEventButton = Button(root, text="Add Events", command=addEvent)
addEventButton.pack()

root.mainloop()

rawDescription: Store class variable in dictionary

description: Store class variable in dictionary


code:
def welcome_message(c):
    if isinstance(c, Customer):
        msg.send("Hi %s", c.first_name)
    else:
        raise TypeError("Class must be of type `Customer`")

rawDescription: Define method in python with an object as input


code:
input = open("c:\\test.txt", "r")
output = open("c:\\result.txt", "w")
for line in input:
    if (line.count(",") == 1):
        print (line)
        output.writelines(line)
input.close()
output.close()

rawDescription: Removing Lines that: do not contain a comma, or contain more then one comma (in Python)


code: np.column_stack((a, b))

rawDescription: How to create a multidimensional list from list with Python Numpy?

description: Create a multidimensional list from list with Python Numpy


rawDescription: Convert unicode string to byte string

description: Convert unicode string to byte string


code:
chars = console.get("insert linestart", "insert")
# [Do some analysis on "chars" to detect >>> and prevent a backspace]

if DO_BACKSPACE:
    console.delete("insert-1c", "insert")

# "break" is important so that the Text widget's backspace handler doesn't get called
return "break"

rawDescription: unremovable text in tkinter

description: Unremovable text in tkinter


code:
import random
def rand_sum(i, j):
    sum_list = []
    for rand_num in range(i, j+1):
        sum_list.append(random.random()) # Check random docs for a function that returns
    return sum(sum_list)                 # a different set of randoms if this isn't
                                         # appropriate

rawDescription: How to generate random variables and sum all them in python

description: Generate random variables and sum all them in python


code:
def list_to_string(lst):
    return "\0".join(l) + "\0"

def string_to_list(s):
    return s.split("\0")[:-1]

rawDescription: python array.array with strings as data type

description: Python array.array with strings as data type


code:
width = 0.35       # the width of the bars
cr_lst = ['A', 'B', 'C', 'D']
x = range(len(cr_lst)) # the x locations for the groups
A_lst = [1, 2, 3, 4]
B_lst = [2, 2, 6, 7]
C_lst = [8, 8, 6, 7]
f, axarr = plt.subplots(3, sharex=False)
axarr[0].set_title('Three plots\n')
axarr[0].set_ylabel('A')
axarr[1].set_ylabel('B')
axarr[2].set_ylabel('C')
axarr[0].set_ylim(ymin=0.001,ymax=max(A_lst)*1.10)
axarr[1].set_ylim(ymin=0.001,ymax=max(B_lst)*1.10)
axarr[2].set_ylim(ymin=0.001,ymax=max(B_lst)*1.10)
axarr[0].grid()
axarr[1].grid()
axarr[2].grid()
rects1 = axarr[0].bar(x, A_lst, width, color='r', align='center', linewidth=1,alpha=0.8)
rects2 = axarr[1].bar(x, B_lst, width, color='y', align='center', linewidth=1,alpha=0.8)
rects3 = axarr[2].bar(x, C_lst, width, color='blue', align='center', linewidth=1, alpha=0.8)
for ax in axarr:
    ax.set_xticks(x)
    ax.set_xticklabels(cr_lst)

plt.savefig("ByC.png")

rawDescription: Plotting three sub plot bar chart with correct labelling


code:
import subprocess

p=subprocess.Popen('./Cprogram', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write('1\n')
p.stdin.write('3\n')
out, err = p.communicate()
print(out)

rawDescription: python subprocess blocked by while loop

description: Python subprocess blocked by while loop


code:
for item in list(somelist):
  ...
  somelist.remove(item)

rawDescription: Python: Removing list element while iterating over list


code:
from pptx.dml.color import RGBColor
from pptx.enum.dml import MSO_THEME_COLOR
from pptx.util import Pt

p = tf.add_paragraph()
run = p.add_run()
run.text = 'hello'
font = run.font
font.name = 'Calibri'
font.size = Pt(18)
font.bold = True
font.color.theme_color = MSO_THEME_COLOR.ACCENT_1

run = p.add_run()
run.text = ' is red and the rest is blue'
run.font.color.rgb = RGBColor(0, 0, 255)

rawDescription: text color in python-pptx module

description: Text color in python-pptx module


rawDescription: Pasrse API Response CSV to List without writing to file


code:
import xml.dom.minidom as mdom
text = mdom.Text()
# Start with unicode
text.data = u'\xae'

f = open('reg1.html', 'w')
f.write("header saying the file is ascii")
uxml = text.toxml()
bxml = uxml.encode('ascii', 'xmlcharrefreplace')
f.write(bxml)
f.close()

f = open('reg2.html', 'w')
f.write("header saying the file is UTF-8")
xml = text.toxml(encoding='UTF-8')
f.write(xml)
f.close()

rawDescription: How can I disable 'output escaping' in minidom

description: Disable 'output escaping' in minidom


code:
d1.groupby('ExamenYear').agg({'Participated': len,
                              'Passed': lambda x: sum(x == 'yes')})

rawDescription: Frequency tables in pandas (like plyr in R)


rawDescription: How to extend a fixed-length Python list by variable number of characters?

description: Extend a fixed-length Python list by variable number of characters


code:
import feedparser
d = feedparser.parse('http://feedparser.org/docs/examples/atom10.xml')
d['feed']['title']

rawDescription: Parsing an Itunes Podcast Feed with Python/Django


code:
d2 = datetime.datetime.strptime(d1,'%d.%m.%y').strftime('%Y-%m-%d')
d2

rawDescription: Convert date with format dd.mm.yy to yyyy-mm-dd in python


code:
my_text = """{ ATTR_u,
  READ_WRITE | ATR_DFLAG_SELEQ | ATR_DFLAG_SCGALT,
  ATR_TYPE_ARST,
  NULL_VERIFY_DATATYPE_FUNC,
  verify_value_user_list
 }"""

my_text = my_text.strip("{}")
my_list = [item.strip() for item in my_text.split(",")]
my_dict = {my_list[0]:my_list[1:]}

rawDescription: Creating a dictionary by using a C structure as an input in Python 2.3


rawDescription: Programmatically sync the db in Django

description: Programmatically sync the db in Django


code:
Multiprocessing
#!/usr/bin/python2

import multiprocessing
import subprocess
import os

def pinger( job_q, results_q ):
    DEVNULL = open(os.devnull,'w')
    while True:
        ip = job_q.get()
        if ip is None: break

        try:
            subprocess.check_call(['ping','-c1',ip],
                                  stdout=DEVNULL)
            results_q.put(ip)
        except:
            pass

if __name__ == '__main__':
    pool_size = 255

    jobs = multiprocessing.Queue()
    results = multiprocessing.Queue()

    pool = [ multiprocessing.Process(target=pinger, args=(jobs,results))
             for i in range(pool_size) ]

    for p in pool:
        p.start()

    for i in range(1,255):
        jobs.put('192.168.1.{0}'.format(i))

    for p in pool:
        jobs.put(None)

    for p in pool:
        p.join()

    while not results.empty():
        ip = results.get()
        print(ip)

rawDescription: Fast ping sweep in python

description: Fast ping sweep in python


code:
import sys
from io import BytesIO
from scapy.all import Ether, IP, ICMP, Net
packets = Ether()/IP(dst=Net("google.com/30"))/ICMP()
old_stdout, sys.stdout = sys.stdout, BytesIO()
try:
    packets.show()
    output = sys.stdout.getvalue()  # retrieve written string
finally:
    sys.stdout = old_stdout  # Restore sys.stdout

output[:10]

rawDescription: Putting Packet.show() representation in string variable


code:
#!/usr/bin/env python

import gobject
import pygtk
pygtk.require('2.0')
import gtk
import time

class CalendarExample:
    def __init__(self):
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_title("Calendar Example")
        window.set_border_width(5)
        window.set_size_request(200, 100)
        window.set_resizable(False)
        window.stick()
        window.connect("destroy", lambda x: gtk.main_quit())

        vbox = gtk.VBox(False, 10)
        window.add(vbox)

        # Could have used WINDOW_POPUP to create below window, but trying to emulate the same properties as the window
        # in applet.
        cal_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        cal_window.set_decorated(False)
        cal_window.set_resizable(False)
        cal_window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DOCK)
        cal_window.stick()
        cal_vbox = gtk.VBox(False, 10)
        cal_window.add(cal_vbox)
        cal_vbox.pack_start(gtk.Calendar(), True, False, 0)
        cal_vbox.pack_start(gtk.Button("Dummy locations"), True, False, 0)

        toggle_button = gtk.ToggleButton("Show Calendar")
        vbox.pack_start(toggle_button, False, True, 10)
        toggle_button.connect("toggled", self.on_toggle, cal_window)

        # Track movements of the window to move calendar window as well
        window.connect("configure-event", self.on_window_config, toggle_button, cal_window)
        window.show_all()

    # Calendar window co ordinates without off-screen correction:
    #         Window origin (x, y)
    #          |
    #          V
    #          ---------------------------------
    #          | Main Window                   |
    #          |                               |
    #          |                               |
    #          |Toggle button's (x, y)         |
    #          |(relative to parent window)    |
    #          | |                             |
    #          | V                             |
    #          |  .........................    |
    # Calendar | |  Toggle Button          |   |
    # window's | |                         |   |
    # (x, y)---+> .........................    |
    #          |(Calendar window will be here) |
    #          |                               |
    #          |                               |
    #          ---------------------------------
    #  Calendar Window's screen coordinates:
    #   x = Window's origin x + Toggle Button's relative x
    #   y = Window's origin y + Toggle Button's relative y + Toggle Button's height

    # "toggle" callback which shows & hides calendar window.
    def on_toggle(self, toggle_button, cal_window):
        if toggle_button.get_active():
            rect = toggle_button.get_allocation()
            main_window = toggle_button.get_toplevel()
            [win_x, win_y] = main_window.get_window().get_origin()
            cal_x = win_x + rect.x
            cal_y = win_y + rect.y + rect.height
            [x, y] = self.apply_screen_coord_correction(cal_x, cal_y, cal_window, toggle_button)
            cal_window.move(x, y)
            cal_window.show_all()
            toggle_button.set_label("Hide Calendar")
        else:
            cal_window.hide_all()
            toggle_button.set_label("Show Calendar")

    # "configure-event" callback of main window, try to move calendar window along with main window.
    def on_window_config(self, widget, event, toggle_button, cal_window):
        # Maybe better way to find the visiblilty
        if cal_window.get_mapped():
            rect = toggle_button.get_allocation()
            cal_x = event.x + rect.x
            cal_y = event.y + rect.y + rect.height
            [x, y] = self.apply_screen_coord_correction(cal_x, cal_y, cal_window, toggle_button)
            cal_window.move(x, y)

    # This function "tries" to correct calendar window position so that it is not obscured when
    # a portion of main window is off-screen.
    # Known bug: If the main window is partially off-screen before Calendar window
    # has been realized then get_allocation() will return rect of 1x1 in which case
    # the calculations will fail & correction will not be applied
    def apply_screen_coord_correction(self, x, y, widget, relative_widget):
        corrected_y = y
        corrected_x = x
        rect = widget.get_allocation()
        screen_w = gtk.gdk.screen_width()
        screen_h = gtk.gdk.screen_height()
        delta_x = screen_w - (x + rect.width)
        delta_y = screen_h - (y + rect.height)
        if delta_x < 0:
            corrected_x += delta_x
        if corrected_x < 0:
            corrected_x = 0
        if delta_y < 0:
            corrected_y = y - rect.height - relative_widget.get_allocation().height
        if corrected_y < 0:
            corrected_y = 0
        return [corrected_x, corrected_y]

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

rawDescription: Showing a gtk.Calendar in a menu?

description: Showing a gtk.Calendar in a menu


code:
from PIL import Image

im = np.array(Image.open('input_image.jpg').convert('L'))

xpixels = im.shape[1]
ypixels = im.shape[0]

dpi = 72
scalefactor = 1

xinch = xpixels * scalefactor / dpi
yinch = ypixels * scalefactor / dpi

fig = plt.figure(figsize=(xinch,yinch))

ax = plt.axes([0, 0, 1, 1], frame_on=False, xticks=[], yticks=[])

contour(im, levels=[240], colors='black', origin='image')

plt.savefig('same_size.png', dpi=dpi)

rawDescription: Convert contour (MatplotLib or OpenCV) to image of the same size as the original


code:
import pandas as pd
import io

csv = """foo,1234567,a,1
foo,2345678,b,3
bar,3456789,b,5
"""

df = pd.read_csv(io.StringIO(csv),
        names = ["fb", "num", "ab", "x"],
        dtype = {"fb" : object, "num" : np.int64, "ab" : object, "x" : np.int8})
print(df)

rawDescription: pandas string data types

description: Pandas string data types


code:
import os
import sys
from PIL import Image
import PIL.ImageOps
import glob

path = "/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/"
print(path)
files = glob.glob(path+"*.JPG")
n = [int(i) for i in map(lambda x: x.split('/')[-1].split('.jpg')[0], files)]
files = [x for (y, x) in sorted(zip(n, files))]
print(files)

rawDescription: Python sorted order of files

description: Python sorted order of files


code:
db = bsddb.hashopen("/home/neeraj/public_html/database/mydb.db","r")
for key in db.keys():
    print('{}: {}'.format(key, db[key]))

rawDescription: How do i view data in database which i have stored in Berkeley db?

description: View data in database which i have stored in Berkeley db


code:
numbers = '0123456789'
next = raw_input('> ')
isanumber = True
for character in next:
    if character not in numbers:
        isanumber = False
        break

rawDescription: Learn Python the Hard Way, Ex35, drill 5


code:
from functools import partial
lambdas = [partial(lambda x: x, i) for i in range(3)]

rawDescription: How to generate a list of different lambda functions with list comprehension?

description: Generate a list of different lambda functions with list comprehension


code:
br = mechanize.Browser()
response = br.open('http://example.com')
soup = BeautifulSoup(response.get_data())
img = soup.find('img', id='id_of_image')
image_response = br.open_novisit(img['src'])
image = image_response.read()

rawDescription: How to get generated captcha image using mechanize

description: Get generated captcha image using mechanize


code:
def join_struct_arrays(arrays):
    sizes = numpy.array([a.itemsize for a in arrays])
    offsets = numpy.r_[0, sizes.cumsum()]
    n = len(arrays[0])
    joint = numpy.empty((n, offsets[-1]), dtype=numpy.uint8)
    for a, size, offset in zip(arrays, sizes, offsets):
        joint[:,offset:offset+size] = a.view(numpy.uint8).reshape(n,size)
    dtype = sum((a.dtype.descr for a in arrays), [])
    return joint.ravel().view(dtype)

rawDescription: Numpy: Joining structured arrays?

description: Numpy: Joining structured arrays


code:
data = [[4,5],[4,7]]
search = 5
found = false
for sublist in data:
    if search in sublist:
        print("there", sublist)
        found = true
if found == false:
    print("not there")
    print(data)

rawDescription: Search for Multiple Sublists of Same List in Python


code:
def create_label(parent, text, row, column, colspan):
    label = Tkinter.Label(parent, text=text, anchor='e', fg='white', bg="black")
    label.grid(column = column, row = row, columnspan = colspan, padx=(2,10), pady=(1,20), sticky = 'E')
    return label
...
self.team2Recordlabel = create_label(self, "", 1, rColLStart, colRSpan)

rawDescription: Creating classes in Python for Tkinter Labels


code:
for sub in reversed(list(t.subtrees())):
    if sub.height() == 2 and sub[0].startswith("*"):  # abbreviated test
        parent = sub.parent()
        while parent and len(parent) == 1:
            sub = parent
            parent = sub.parent()
        print(sub, "will be deleted")
        del t[sub.treeposition()]

rawDescription: How to identify and remove trace trees from nltk.trees?

description: Identify and remove trace trees from nltk.trees


code:
next_scene_name = current_scene.text()

if next_scene_name in self.map_scenes.scenes:
    current_scene = self.map_scenes.next_scene(next_scene_name)

rawDescription: Classes are scenes. Trying to repeat the scene if the answer is not consider


code:
num_evens = {}
for combination in itertools.product(*li):
    even_counter = len([ y for y in combination if y & 1 == 0 ])
    num_evens.setdefault(even_counter,[]).append(combination)

import pprint
pprint.pprint(num_evens)

rawDescription: Create x lists in python dynamically

description: Create x lists in python dynamically


code:
paths = ["/some/where", "/some/where/else", "/another/location", "/tmp"]
file_name = "foo.bar"
joined = (join(p, file_name) for p in paths)
next((abspath(f) for f in joined if exists(f)), '')

rawDescription: Find first occurrence of file in list of directories


code:
import re

pattern = re.compile(r"regex1.*?regex2", re.DOTALL)

rawDescription: How do you delete a lines within a file where range is determined using regular expressions in python?

description: Delete a lines within a file where range is determined using regular expressions in python


rawDescription: Pandas DataFrame column concatenation

description: Pandas DataFrame column concatenation


rawDescription: Python Regex - Match a character without consuming it


code:
def bounding_box(iterable):
    min_x, min_y = numpy.min(iterable[0], axis=0)
    max_x, max_y = numpy.max(iterable[0], axis=0)
    return numpy.array([(min_x, min_y), (max_x, min_y), (max_x, max_y), (min_x, max_y)])

rawDescription: Calculating bounding box of numpy array

description: Calculating bounding box of numpy array


code:
import subprocess, time, signal

p = subprocess.Popen(['python', '-u', 'myscript.py'], stdout=subprocess.PIPE)
time.sleep(5)
p.send_signal(signal.SIGTERM)
output = p.communicate()[0]

print('Process has exited with code %d' % p.wait())
print('Output is %s' % str(output))

rawDescription: Controlling a "daemon-like" linux script from Python


code: getattr(obj, key)

rawDescription: get django value from django queryset where column name is a variable

description: Get django value from django queryset where column name is a variable


code:
import numpy as np

a = np.array([True, False, True])
b = np.array([[1,1,1],[2,2,2],[3,3,3]])

# index rows of b where a is True (i.e. the first and third row of b)
print(b[a])
# [[1 1 1]
#  [3 3 3]]

# take the sum over all elements in these rows
print(b[a].sum())
# 12

rawDescription: Numpy Summation for Index in Boolean Array


code:
import json

def loadlist(path):
    try:
        with open(path, 'r') as listfile:
            saved_list = json.load(listfile)
    except Exception:
            saved_list = []
    return saved_list

def savelist(path, _list):
    try:
        with open(path, 'w') as listfile:
            json.dump(_list)
    except Exception:
        print("Oh, no! List wasn't saved! It'll be empty tomorrow...")

rawDescription: Python - Store variables in a list that save each time program restarts


code:
def add_path(parent, path, value=None):
    end = len(path) - 1
    for index, component in enumerate(path):
        if index < end or value is None:
            parent = parent.setdefault(component, {})
        else:
            parent[component] = value

rawDescription: Setting values in nested dictionary

description: Setting values in nested dictionary


code:
class Memory(models.Model):
    partNum = models.CharField()
    capacity = models.CharField()

class Computer(models.Model):
    name = models.CharField()
    memory = models.ManyToManyField(Memory, through='ComputerMemory')

class ComputerMemory(models.Model):
    memory = models.ForeignKey(Memory)
    computer = models.ForeignKey(Computer)
    count = models.IntegerField()

rawDescription: Django manytomany: adding multiple, non-unique relationships?


code:
from flask import Flask
app = Flask(__name__)

@app.route("/arbitrary/<path:my_path>")
def arbitrary_path(my_path):
    return my_path

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

rawDescription: How can I securely pass an arbitrarily deep path to a webapp (Flask, in this case)?

description: Securely pass an arbitrarily deep path to a webapp (Flask, in this case)


code:
from django.forms.formsets import formset_factory
ImageFormSet = formset_factory(ImageForm)

rawDescription: Django and multi-image upload form

description: Django and multi-image upload form


code:
class BaseQuery(Query):
    def fulltext(self, terms):
        # assuming query is always created with `cls.query` or `DBSession.query(cls)`
        cls = self._entities[0].type
        ...

rawDescription: Find class being queried on from custom Query class in SQLAlchemy?


code:
inv = cmap_map(lambda x: 1-x, cm.PRGn)  # the "transformation" = 1-x

#  plot the original or modified for comparison
x,y=mgrid[1:2,1:10:0.1]
plt.imshow(y, cmap=cm.PRGn)
plt.title("original")
plt.figure()
plt.imshow(y, cmap=inv)
plt.title("inverted")
plt.show()

rawDescription: What is a good converging colourmap for matplotlib


code:
import Tkinter as tk

class MyApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.text = tk.Text(self)
        self.text.pack(side="top", fill="both", expand=True)
        self.text.tag_configure("current_line", background="#e9e9e9")
        self._highlight_current_line()

    def _highlight_current_line(self, interval=100):
        '''Updates the 'current line' highlighting every "interval" milliseconds'''
        self.text.tag_remove("current_line", 1.0, "end")
        self.text.tag_add("current_line", "insert linestart", "insert lineend+1c")
        self.after(interval, self._highlight_current_line)

app = MyApp()
app.mainloop()

rawDescription: How to highlight the current line of a Text widget?

description: Highlight the current line of a Text widget


code:
import xlwt
custom_fmts = (
    '_(* (#,##0);_(* "-");(@)',
    '_(#0_);(#0);"-"_)', # positive;negative;zero
    '#0;-#0;"-"', # positive;negative;zero
    )
xfs = [xlwt.easyxf('', fmt) for fmt in custom_fmts]
wb = xlwt.Workbook()
ws = wb.add_sheet('x')
for colx, xf in enumerate(xfs):
    for rowx, value in enumerate((1234567, 0, -1234567)):
        ws.write(rowx, colx, value, xf)

wb.save('demo_custom_format.xls')

rawDescription: Formatting number so that zeros are dashes (-) with xlwt


code:
pipeline = Pipeline([
  ('fs', RandomizedLogisticRegression()),
  ('clf', LogisticRegression())
])

params = {'fs__C':[0.1, 1, 10]}

grid_search = GridSearchCV(pipeline, params)

rawDescription: Regularization parameter setting for Randomized Regression in sklearn


code:
class msh_finalSpider(Spider):
    name = 'msh_final'
    start_urls = ['http://www.mediamarkt.be/mcs/productlist/_Telefoon-Navigatie,98952,509451.html?langId=-17']

    def parse(self, response):
        items = response.xpath('//ul[@class="infield cf"]//div[@class="infield-wrapper"]/h2/a/@href')
        for item in items:
            link = item.extract()
            yield Request(complete_url(link), callback=self.parse_category)

    def parse_category(self, response):
        items = response.xpath("//ul[@class='products-list']/li/div")
        for item in items:
            msh = CrawlerMshFinalItem()
            msh['item_price'] = encode(item.xpath('normalize-space(.//aside/div/div/div/text())').extract()[0])
            msh['item_name'] = encode(item.xpath('normalize-space(.//div/h2/a/text())').extract()[0])
            yield msh

        new_link = response.xpath('//li[@class="pagination-next"]/a/@href').extract()[0]
        yield Request(
            complete_url(new_link),
            callback=self.parse_category
        )

rawDescription: How to call the next page in my parse - Scrapy

description: Call the next page in my parse - Scrapy


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import spline

y = [1.0, 0.7071067811865476, 0.5, 0.3535533905932738, 0.25, 0.1767766952966369]
x = range(0,6)

y = np.array(y)
x = np.array(x)

xsmooth = np.linspace (x.min(),x.max(),20) # an x vector with more intermediate values
ysmooth = spline(x,y,xsmooth)

plt.plot(xsmooth ,ysmooth)
plt.plot(x,y,'o')
plt.show()

rawDescription: Scipy to make the graph smoother

description: Scipy to make the graph smoother


rawDescription: Python sorting by the max of the first element, then the min of the second element


code:
import os
from os.path import walk

mydict = {"":"", "":"</h>", "
":"
"}

for (path, dirs, files) in os.walk('./'):
    for f in files:
        if f.endswith('.html'):
            filepath = os.path.join(path,f)
            s = open(filepath).read()
            for k, v in mydict.iteritems():
                s = s.replace(k, v)
            f = open(filepath, 'w')
            f.write(s)
            f.close()

rawDescription: Run multiple find and replaces in Python (on every file in the folder and sub-folder)


code:
import urllib2, sys

def chunk_report(bytes_so_far, chunk_size, total_size):
   percent = float(bytes_so_far) / total_size
   percent = round(percent*100, 2)
   sys.stdout.write("Downloaded %d of %d bytes (%0.2f%%)\r" %
       (bytes_so_far, total_size, percent))

   if bytes_so_far >= total_size:
      sys.stdout.write('\n')

def chunk_read(response, chunk_size=8192, report_hook=None):
   total_size = response.info().getheader('Content-Length').strip()
   total_size = int(total_size)
   bytes_so_far = 0

   while 1:
      chunk = response.read(chunk_size)
      bytes_so_far += len(chunk)

      if not chunk:
         break

      if report_hook:
         report_hook(bytes_so_far, chunk_size, total_size)

   return bytes_so_far

if __name__ == '__main__':
   response = urllib2.urlopen('http://www.ebay.com');
   chunk_read(response, report_hook=chunk_report)

rawDescription: Python urllib2 Progress Hook

description: Python urllib2 Progress Hook


code:
l=[]
n = int(input())
s = 0
k = 0
i = 1
while s<n:
    s = s+i
    if (s<n):
        l.append(i)
        k = k + 1
        i = i+1
    elif (s>n):
        l.remove(s-n)
        l.append(i)
    elif (s==n):
        l.append(i)
        k = k + 1
print(k)
for i in range(0,k):
    print(l[i],end=' ')

rawDescription: Different natural items [python]

description: Different natural items [python]


code:
def limited_cumsum(x, limit):
    y = []
    sm = 0
    for item in x:
        sm += item
        if sm > limit:
            return y
        y.append(sm)
    return y

rawDescription: Breaking early when computing cumulative products or sums in numpy


code:
def mydist(x, y):
    return np.sum((x-y)**2)
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
nbrs = NearestNeighbors(n_neighbors=4, algorithm='ball_tree',
           metric='pyfunc', func=mydist)
nbrs.fit(X)
nbrs.kneighbors(X)

rawDescription: Sklearn kNN usage with a user defined metric


code:
from __future__ import print_function
import httplib
conn = httplib.HTTPConnection("localhost")
conn.request("GET", "/sse.php")
response = conn.getresponse()

while True:
    data = response.fp.readline()
    print(data)

rawDescription: Reading SSE data in python

description: Reading SSE data in python


code:
def List_To_Tree(lst):
    if(not isinstance(lst, basestring)):
        if(len(lst) == 2 and isinstance(lst[0], basestring) and isinstance(lst[1], basestring)):
            lst = Tree(str(lst[0]).split('+')[0],[str(lst[1])])
        elif(isinstance(lst[0], basestring) and not isinstance(lst[1], basestring)):
            lst = Tree(str(lst[0]).split('+')[0],map(List_To_Tree, lst[1: len(lst) ]))
    return lst

rawDescription: NLTK parse complex list into tree

description: NLTK parse complex list into tree


code: cursor.execute("INSERT INTO rfid(tagname, weight) VALUES (%s, 30)", (txt))

rawDescription: Python: Insert a dynamic value along with static value?


code:
url = 'https://api.kenshoo.com/v2/reports/5233/runs/?ks=105'
values = {'dateRange': {'from':'2015-09-22', 'to':'2015-09-22'}}
req = urllib2.Request(url)
req.add_header('Content-Type', 'application/json')

response = urllib2.urlopen(req, json.dumps(values))

rawDescription: Am I sending a date object correctly to the request body? Python


code:
from tkinter import *
from tkinter import ttk

def newwindow():

    def function():
        var.set(text.get()+text2.get())
        print(var.get())

    main=Toplevel(root)

    text=DoubleVar()
    text2=DoubleVar()
    var=StringVar()

    ttk.Entry(main, textvariable=text).grid(column=0, row=0)
    ttk.Entry(main, textvariable=text2).grid(column=1, row=0)
    ttk.Label(main, textvariable=var).grid(column=2, row=0)
    ttk.Button(main, text="Button", command=function).grid(column=0, row=1, columnspan=2)

root=Tk()
ttk.Button(text="Button", command=newwindow).grid(column=0, row=0)
root.mainloop()

rawDescription: Python Tkinter - When I try to use an Entry form on a new window they do not work


code: cmd = ['/Users/me/src/program', 'a.txt', 'b.txt']

rawDescription: Using python to run another program?

description: Using python to run another program


code:
from commands import getoutput

response = getoutput('php myscript.php')

rawDescription: PHP in python through bash

description: PHP in python through bash


code:
from troposphere import Template
import troposphere.elasticloadbalancing as elb

template = Template()
webelb = elb.LoadBalancer(
    'ElasticLoadBalancer',
    Listeners=[
        elb.Listener(
            LoadBalancerPort="80",
            InstancePort="80",
            Protocol="HTTP",
        ),
    ],
)

if True:
    webelb.ConnectionSettings = elb.ConnectionSettings(IdleTimeout=30)
elasticLB = template.add_resource(webelb)
print(template.to_json())

rawDescription: How to pass a Troposphere object attribute conditionally?

description: Pass a Troposphere object attribute conditionally


code:
ind_set = set(ind)
retain = [i for i in range(len(d1)) if i not in ind_set]
d2 = [[d1[k][j] for j in retain] for k in retain]

rawDescription: Speeding up a code to filter a matrix in python


code:
from tkinter import *

mainFrame1 = PanedWindow()
mainFrame1.pack(fill=BOTH, expand=1)

mainFrame2 = PanedWindow(mainFrame1, orient=VERTICAL)
mainFrame1.add(mainFrame2)

top = Label(mainFrame2, text="top pane", bg="green")
mainFrame2.add(top)

bottom = Label(mainFrame2, text="bottom pane", bg="blue")
mainFrame2.add(bottom)

right = Label(mainFrame1, text="right pane", bg="red") # <---
mainFrame1.add(right)                                  # <---

mainloop()

rawDescription: Tkinter reverse 3 pane widget

description: Tkinter reverse 3 pane widget


code: my_field = models.CharField(max_length=100, default='', blank=True)

rawDescription: django model default="" and "This field cannot be blank"

description: Django model default="" and "This field cannot be blank"


code:
def compute(d, t='c'):
    """
    d is the computing variable
    t is the type, can be a list
    """
    l = []
    for x in t:
        if t == 'a':
            l.append(fa(d))
        elif t == 'b':
            l.append(fb(d))
        else:
            l.append(fc(d))

    if len(l) == 1:
        return l[0]
    else:
        return l

compute(d, ['a', 'b', 'a' , 'c', 'b'])

rawDescription: if logic not working in array context for python

description: If logic not working in array context for python


code: [x*(x + 1) for x in range(10)]

rawDescription: What is a clearer way to generate this sequence of numbers?


rawDescription: Auto zero-padding an array

description: Auto zero-padding an array


code:
def T(lamda,x):
    """
    T Operator
    lambda is a "steering" constant between 3 behavior states
    -----------------------------
    0     -> linearity
    +inf  -> max
    -inf  -> min
    -----------------------------
    """
    if lamda == 0:  # linearity
        return x
    elif lamda > 0: #  Half-wave rectification
        maxval = np.zeros_like(x)
        return np.array([x, maxval]).max(axis=0)
    elif lamda < 0: # Inverse half-wave rectification
        minval = np.zeros_like(x)
        return np.array([x, minval]).min(axis=0)

def Diffusion_operator(lamda,f,t):
    """
    2D Spatially Discrete Non-Linear Diffusion
    ------------------------------------------
    Special case where lambda == 0, operator becomes Laplacian

    Parameters
    ----------
    D : int                      diffusion coefficient
    h : int                      step size
    t0 : int                     stimulus injection point
    stimulus : array-like        luminance distribution

    Returns
    ----------
    f : array-like               output of diffusion equation
    -----------------------------
    0     -> linearity (T[0])
    +inf  -> positive K(lamda)
    -inf  -> negative K(lamda)
    -----------------------------
    """
    if lamda == 0:  # linearity
        return flt.laplace(f)
    else:           # non-linearity
        f_new = T(lamda,np.roll(f,1, axis=0) - f) \
                + T(lamda,np.roll(f,-1, axis=0) - f) \
                + T(lamda,np.roll(f, 1, axis=1) - f) \
                + T(lamda,np.roll(f,-1, axis=1) - f)
        return f_new

rawDescription: 4th Order Runga Kutta Method - Diffusion equation - Image analysis


code:
class BaseModel(db.Model):
    __abstract__ = True

rawDescription: How to subclass the default `db.Model` to use as a custom `Base` with SQLAlchemy

description: Subclass the default `db.Model` to use as a custom `Base` with SQLAlchemy


code: foo(*(users_data['user_1'][k] for k in ('Age', 'address', 'height')))

rawDescription: Access nested dictionaries' data

description: Access nested dictionaries' data


code:
on_heroku = False
if 'YOUR_ENV_VAR' in os.environ:
  on_heroku = True

rawDescription: How can I detect Heroku's environment?

description: Detect Heroku's environment


code:
# A Foolish Consistency is the Hobgoblin of Little Minds [1]
# [1]: http://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds

rawDescription: How should I format a long url in a python comment and still be PEP8 compliant


code:
from enum import Enum, IntEnum

class SerialProcessState(Enum):
    search_start = 1
    verify_elements = 2
    data = 3
    search_end = 4

class SerialProcessValue(IntEnum):
    packet_start = 0xF0
    packet_end = 0xF1
    ...

rawDescription: enums from c# to python (2.7)

description: Enums from c# to python (2.7)


code: tuples = re.findall(r"^\s*static[ \t]*const[ \t]*PropertyID[ \t]*(\w+)[ \t]*=[ \t]*(\d+).*",fileContents)

rawDescription: Writing regular expression to skip a line if specific set of characters are present?


code:
current_dict = myDict
mystring = "classes.students.grades"
myPath = mystring.split(".")
for part in myPath:
    current_dict = current_dict[part]

rawDescription: Python dictionary manipulation from dot notation


rawDescription: "Blending out" noise in images?

description: "Blending out" noise in images


rawDescription: use IDs instead of instances to create new objects with foreign keys

description: Use IDs instead of instances to create new objects with foreign keys


code:
if health == 0:
    break

rawDescription: Stop number decrease once 0 reached - Python


code:
import requests

s = requests.Session()
s.post(website_url, data = params)

rawDescription: Python requests lib, is requests.Session equivalent to urllib2's opener?


rawDescription: Accessing list elements

description: Accessing list elements


code:
import glob
import os
import os.path
lst = glob.glob("abcd")
for element in lst:
    if os.path.isdir(element):
        os.rename(element,"abcd")

rawDescription: Rename a folder with source folder name matched by wildcard ("*")


code:
import functools

def decorator(d):
    """Make function d a decorator: d wraps a function fn.
    Authors: Peter Norvig and Darius Bacon"""
    def _d(fn):
        return functools.update_wrapper(d(fn), fn)
    functools.update_wrapper(_d, d)
    return _d

@decorator
def memo(f):
    # by Peter Norvig
    """Decorator that caches the return value for each call to f(args).
    Then when called again with same args, we can just look it up."""
    cache = {}

    def _f(*args):
        try:
            return cache[args]
        except KeyError:
            cache[args] = result = f(*args)
            return result
        except TypeError:
            # some element of args can't be a dict key
            return f(*args)
    _f.cache = cache
    return _f

@memo
def is_tile_inside_border(x, y, z, border):
    '''Checks if a tile is inside border or not
    >>> is_tile_inside_border(85,53,7,'iran')
    3
    >>> is_tile_inside_border(85,15,7,'iran')
    0
    '''
    # binary_data = get_border_binary(border, z)
    # return isInside((x, y), binary_data)
    return True

class Foo(object):
    @memo
    def bar(self, x):
        """
        >>> Foo().bar(1)
        2
        """
        return x

if __name__ == '__main__':
    import doctest
    doctest.testmod()

rawDescription: How to use doctest with a decorated function in python?

description: Use doctest with a decorated function in python


code:
for element_to_check in elements_to_check:
    for unique_element in unique_list:
        if element_to_check[0] == unique_element[0] and element_to_check not in unique_list:
            unique_list.append(element_to_check)
        elif element_to_check[1] == unique_element[1] and element_to_check not in unique_list:
            unique_list.append(element_to_check)
        elif element_to_check[2] == unique_element[2] and element_to_check not in unique_list:
            unique_list.append(element_to_check)

    if element_to_check not in unique_list and element_to_check not in not_match_list:
        not_match_list.append(element_to_check)

rawDescription: More pythonic way to go over list of lists


code:
def rank(toSort):
    #importing from the string library
    from string import lowercase as alph

    #temporary list
    _ranks=[]

    #populate with empty dictonaries
    for i in range(len(toSort)):
        _ranks.append({})

    #the actual sorting algorithm
    for i in range(len(toSort)-1):
        #iterate all k/v pairs in the supplied dictionary
        for k,v in toSort.iteritems():
            #iterate all k/v pairs in v element
            for a,b in v.iteritems():
                #if the alpha index of an element is equal to
                #the max alpha index of elements in its containing dictionary...
                if alph.index(b)==max(map(alph.index,v.values())):
                    _ranks[i][k]=a
                #if it isn't..
                else:
                    try:
                        _ranks[i+1][k]=a
                    except IndexError:
                        _ranks[-1][k]=a
    return _ranks

rawDescription: How can I get a ranked list from a dictionary?

description: Get a ranked list from a dictionary


code:
import pygame
import math

pygame.display.init()
window = pygame.display.set_mode((600, 500))
mapImg = pygame.image.load("mapoftheusa.bmp")

done = False

while not done:

   window.fill((0,0,0))
   evtList = pygame.event.get()
   for evt in evtList:
       if evt.type == pygame.QUIT:
          done = True

   window.blit(mapImg, (0,0)) #<<will not blit
   pygame.display.update() # solution: you forgot this...

pygame.quit()

rawDescription: trying to load bitmap image in python

description: Trying to load bitmap image in python


code:
try:
    from tkinter import *   # Python 3
except ImportError:
    from Tkinter import *   # Python 2

def new_file():
    # ...
    pass

def about_dialog():
    root.tk.call('tk::mac::standardAboutPanel')

root = Tk()
win = Toplevel(root)
menubar = Menu(win)
menu_file = Menu(menubar)
# ...
menubar.add_cascade(menu=menu_file, label='File')
# ...
menu_file.add_command(label='New', command=new_file)
# ...
root.createcommand('tkAboutDialog', about_dialog)
win['menu'] = menubar
root.mainloop()

rawDescription: py2app plist app info not showing up when looking at About app

description: Py2app plist app info not showing up when looking at About app


rawDescription: Downloading file with Python mechanize

description: Downloading file with Python mechanize


code:
import clr
clr.AddReference('MyAssembly.dll')
import MyClass
obj = MyClass("Hello, World!")
obj.Write()

rawDescription: Instantiating custom C# classes from IronPython


rawDescription: Python - Replacing Indice Values in Nested Lists


code:
def nested_depth(d):
    if not isinstance(d, dict):
        return 0
    if not d:
        return 1
    return 1 + max(nested_depth(v) for v in d.values())

rawDescription: How to find the deepest dict-level of a multilevel python dict?

description: Find the deepest dict-level of a multilevel python dict


code:
from itertools import repeat

if __name__ == '__main__':
    p = Pool(nprocs)
    y = p.starmap(calc_stuff, zip(x, repeat(a), repeat(b), repeat(c)))

rawDescription: python for-loop parallelization using multiprocessing.pool

description: Python for-loop parallelization using multiprocessing.pool


code:
# A simple setup script to create an executable using PyQt4. This also
# demonstrates the method for creating a Windows executable that does not have
# an associated console.
#
# PyQt4app.py is a very simple type of PyQt4 application
#
# Run the build process by running the command 'python setup.py build'
#
# If everything works well you should find a subdirectory in the build
# subdirectory that contains the files needed to run the application

import sys

from cx_Freeze import setup, Executable

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(
        name = "simple_PyQt4",
        version = "0.1",
        description = "Sample cx_Freeze PyQt4 script",
        executables = [Executable("PyQt4app.py", base = base)])

rawDescription: How can I hide the console window when freezing wxPython applications with cxFreeze?

description: Hide the console window when freezing wxPython applications with cxFreeze


code:
started = 0
hash_val = 0

with open("video", "rb") as file:
    byte = file.read(1) # read a byte (a single character in text)
    byte_val = ord(byte) # convert the string character into a number

    if started == 0:
        hash_val = byte_val
        started = 1
    hash_val = (hash_val << 5) - hash_val + byte_val # this is a basic hash

print(hash_val)

rawDescription: Python - How to read a video file as binary data?


code:
Dave = 12
Peter = 5
Agnes = 4
Charles = 10
Mary = 8

rawDescription: Python: How do i sort Names in a text file alphabetically?


code:
def index (req):
       s = """\

    <form method="get" action="./show">

Type a word: <input type="text" name="word">
    <input type="submit" value="Submit"

    </form>

    """
       return s

rawDescription: Not able to load an image in the webpage using mod_python


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

x = np.linspace(0, 10, 1000)
y = np.sin(x)

fig = plt.figure(figsize=(16,4))
ax = fig.add_subplot(1,1,1)

ax.plot(x,y)
ax.set_xlabel('x')
ax.set_ylabel('y')

plt.show()

rawDescription: Do all matplotlib figures have to be square?


code:
extra_args = {'hello': 'world'}
url_for('doit', oid=oid, **extra_args)
# /doit/123?hello=world
url_for('doit', oid=oid, hello='davidism')
# /doit/123?hello=davidism

rawDescription: Creating dynamic arguments for url_for() in Flask?


code: self.assertTrue( issubclass(QuizForm, forms.Form) )

rawDescription: Test if a class is inherited from another


rawDescription: Python's Multiplication Function

description: Python's Multiplication Function


code:
import concurrent.futures
import urllib.request

catname = 'amateur'

def getimg(count):
    localpath = '{0}/images/{0}{1}.jpg'.format(catname, count)
    urllib.request.urlretrieve(URLS[count], localpath)
    URLS[count] = localpath

with concurrent.futures.ThreadPoolExecutor(max_workers=50) as e:
    for i in range(5000):
        e.submit(getimg, i)

rawDescription: How can I download images from a list of links?

description: Download images from a list of links


code:
self.testbed.init_blobstore_stub()
self.testbed.init_files_stub()
from google.appengine.api import files
file_name = files.blobstore.create(mime_type='application/octet-stream')
with files.open(file_name, 'a') as f:
    f.write('blobdata')
files.finalize(file_name)
blob_key = files.blobstore.get_blob_key(file_name)

rawDescription: How to simulate file upload to blobstore using GAE dev server testbed for python

description: Simulate file upload to blobstore using GAE dev server testbed for python


code:
def rainbow_text(x,y,ls,lc,**kw):
    """
    Take a list of strings ``ls`` and colors ``lc`` and place them next to each
    other, with text ls[i] being shown in color lc[i].

    This example shows how to do both vertical and horizontal text, and will
    pass all keyword arguments to plt.text, so you can set the font size,
    family, etc.
    """
    t = plt.gca().transData
    fig = plt.gcf()

    #### note: this line moved down ....###
    #plt.show()                           #
    #######################################
    #horizontal version
    for s,c in zip(ls,lc):
        text = plt.text(x,y," "+s+" ",color=c, transform=t, **kw)
        text.draw(fig.canvas.get_renderer())
        ex = text.get_window_extent()
        t = transforms.offset_copy(text._transform, x=ex.width, units='dots')

    #vertical version
    for s,c in zip(ls,lc):
        text = plt.text(x,y," "+s+" ",color=c, transform=t,
                rotation=90,va='bottom',ha='center',**kw)
        text.draw(fig.canvas.get_renderer())
        ex = text.get_window_extent()
        t = transforms.offset_copy(text._transform, y=ex.height, units='dots')

    t = plt.gca().transData
    fig = plt.gcf()
    plt.show() ############### when this is here, you can see that
               ############### all unicorns poo rainbows ;-)

plt.figure()

rainbow_text(0.0,0.0,"all unicorns poop rainbows ! ! !".split(),
        ['red', 'orange', 'brown', 'green', 'blue', 'purple', 'black'],
        size=30)
### worked on matplotlib version 1.1.0 on Debian Wheezy. Which version did you try?

rawDescription: Drawing text at boundary of another text object in Matplotlib


code:
import string

def Coder(shift):
    alpha = string.ascii_lowercase
    ALPHA = string.ascii_uppercase
    if 0 <= shift < 26:
        unshifted_letters = ALPHA + alpha
        shifted_letters = ALPHA[shift:] + ALPHA[:shift] + alpha[shift:] + alpha[:shift]
        return dict(zip(unshifted_letters, shifted_letters))

rawDescription: Python Caesar cypher

description: Python Caesar cypher


code:
from matplotlib import ticker

# (generate plot here)
cb = plt.colorbar()
tick_locator = ticker.MaxNLocator(nbins=5)
cb.locator = tick_locator
cb.update_ticks()
plt.show()

rawDescription: How to set number of ticks in plt.colorbar?

description: Set number of ticks in plt.colorbar


code:
'123abc'.isalnum()
'123'.isalnum()
'abc'.isalnum()
'123#$%abc'.isalnum()

rawDescription: In Python, how do I check if a string has alphabets or numbers?


code:
from django.db.models import Count

self.annotate(likes_count=Count('like')).order_by('likes_count')

rawDescription: Django, ModelManager with a query based on model property


code:
K = ['a','b','c']
import itertools
N = 4
i = itertools.product(K,repeat = N)
l = [a for a in i]
l[:3]

rawDescription: Get a list of N items with K selections for each element?


code:
from os import listdir
from os.path import isfile, join, splitext
import shutil
import re

mypath = "./somewhere/"

# this function taken from an answer to http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort
def natural_sort_key(s, _nsre=re.compile('([0-9]+)')):
    return [int(text) if text.isdigit() else text.lower()
        for text in re.split(_nsre, s)]

# Get a list of all files in a directory
infiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

# Create a set of starting sequences
sequences = {splitext(file)[0].split('_')[0] for file in infiles}

# Now go about changing the files
for seq in sequences:
    files = sorted([f for f in infiles if f.startswith(seq)],
                   key=natural_sort_key) # sort the files, if you like
    for idx, file in enumerate(files):
        new_name = seq + '-' + str(idx + 1) + '.' + splitext(file)[1][1:]
        print(file, " -> ", new_name)
        # copy or move
        #shutil.copy2(join(mypath,file), join(mypath,new_name))
        #shutil.move(join(mypath,file), join(mypath,new_name))

rawDescription: How to rename file with a sequence that restarts if certain matches exist

description: Rename file with a sequence that restarts if certain matches exist


code:
import collections
# define the namedtuple class Point (used below).
Point = collections.namedtuple('Point', 'total pass fail')

# Notice we declare `variables` empty at first; we'll fill in the values later.
variables={}
keys=('spec','nd','addr','pmtu','icmp')
for s in sections:
    for key in keys:
        page = input_page + s
        url_reference = urllib.urlopen(page)
        html_page = url_reference.read()
        m = re.search(r'TOTAL	:	([0-9,]+)', html_page)
        ntotal = int(m.group(1))
        m = re.search(r'PASS	:	([0-9,]+)', html_page)
        npass = int(m.group(1))
        m = re.search(r'FAIL	:	([0-9,]+)', html_page)
        nfail = int(m.group(1))

        # We create an instance of the namedtuple on the right-hand side
        # and store the value in `variables[key]`, thus building the
        # variables dict incrementally.
        variables[key]=Point(ntotal,npass,nfail)

rawDescription: How do I deal with list of lists correctly in python? Specifically with a list of functions

description: Deal with list of lists correctly in python? Specifically with a list of functions


code:
import operator

def apply_a(func):
    def inner(self, other):
        return Foo(func(self.a, other.a))
    return inner

class Foo(object):
    def __init__(self, a=0):
        self.a = a

for name in ['__add__','__mul__','__sub__']:
    setattr(Foo, name, apply_a(getattr(operator, name)))

rawDescription: python - overloading several operators at once

description: Python - overloading several operators at once


code:
import re
uniq = set()
with open('Sample.txt') as fin:
    for line in fin:
        ma = re.search(r'(\w{1,4})$', line)
        if not ma:
            continue
        uniq.add(ma.group(1))

print(uniq)

rawDescription: Using regex with python to find unique number format


code:
import Tkinter as tk

class App:
    def __init__(self):
        self.root = tk.Tk()
        self.count = 0
        b=tk.Button(text="create window", command=self.create_window)
        b.pack()
        self.root.mainloop()

    def create_window(self):
        self.count += 1
        t=FadeToplevel(self.root)
        t.wm_title("Window %s" % self.count)
        t.fade_in()

class FadeToplevel(tk.Toplevel):
    '''A toplevel widget with the ability to fade in'''
    def __init__(self, *args, **kwargs):
        tk.Toplevel.__init__(self, *args, **kwargs)
        self.attributes("-alpha", 0.0)

    def fade_in(self):
        alpha = self.attributes("-alpha")
        alpha = min(alpha + .01, 1.0)
        self.attributes("-alpha", alpha)
        if alpha < 1.0:
            self.after(10, self.fade_in)

if __name__ == "__main__":
    app=App()

rawDescription: Having trouble with Tkinter transparency


code:
def process_url(url):
    # Do what you want
    return what_you_want

pool = multiprocessing.Pool(processes=4) # how much parallelism?
pool.map(process_url, list_of_urls)

rawDescription: Retrieve multiple urls at once/in parallel


code:
import csv

cla_1results = {
    "Tom": [1, 7, 4],
    "Dunc": [3, 9, 4],
    "Jack": [1, 3, 5]
}

with open("test.csv", 'w+') as file:
    writer = csv.writer(file)

    for name in cla_1results:
        writer.writerow([name, ] + [i for i in cla_1results[name]])

rawDescription: How to write a dictionary with multiple keys, each with multiple values to a csv in Python?

description: Write a dictionary with multiple keys, each with multiple values to a csv in Python


code:
def check(sub, full):
    full_list = list(full)
    for char in sub:
        if char in full_list:
            full_list.remove(char)
        else:
            return False
    return True

rawDescription: Finding a string in a jumbled string

description: Finding a string in a jumbled string


code:
while True:
    new = Cell("A1").value
    if static != new:
        CellRange("C2:E4").clear()
        Cell("C2").table = {"mamposteria": data1,
                            "moretero": data2,
                            "estructura": data3}[new]
        static = new

rawDescription: Interactive sheet using Datanitro

description: Interactive sheet using Datanitro


code:
from unittest import TestCase
from playhouse.test_utils import test_database
from peewee import *

from my_app.models import User, Tweet

test_db = SqliteDatabase(':memory:')

class TestUsersTweets(TestCase):
    def create_test_data(self):
        # ... create a bunch of users and tweets
        for i in range(10):
            User.create(username='user-%d' % i)

    def test_timeline(self):
        with test_database(test_db, (User, Tweet)):
            # This data will be created in `test_db`
            self.create_test_data()

            # Perform assertions on test data inside ctx manager.
            self.assertEqual(Tweet.timeline('user-0') [...])

        # once we exit the context manager, we're back to using the normal database

rawDescription: Custom sqlite database for unit tests for code using peewee ORM


code:
def calculate(function):
    func = getattr(np, function)
    func(...)   # do what you want

calculate("mean") # calculate the average number
calculate("std")  # calculate the standard deviation

rawDescription: Changing only the calculation in a function


code:
est = sm.ols("y ~ x", data =data).fit()
est.predict(exog=new_values)

rawDescription: Python: Predict the y value using Statsmodels - Linear Regression


code: return it.takewhile(lambda x: x < n, get_primes())

rawDescription: Setting a limit on an infinite generator in Python


code:
myarray = array([0, 5, 3, 3, 0, 1, 2])
mylist = list(myarray)

rawDescription: python: what does array([...]) mean?

description: Python: what does array([...]) mean


code:
import PyQt4.QtGui as ui
import PyQt4.QtCore as core

app = ui.QApplication([])

mw = ui.QMainWindow()
mw.setCentralWidget(ui.QTextEdit())

dw = ui.QDockWidget("Test",mw)
dw.setWidget(ui.QLabel("Content"))

mw.addDockWidget(core.Qt.RightDockWidgetArea, dw)

def onDestroy(w):
    print("Do stuff here")
    print(w)

dw.destroyed.connect(onDestroy)

mw.show()
app.exec_()

rawDescription: How does PySide/PyQt QMainWindow close a QDockWidget?


code: "python <<path to setup.py>> install"

rawDescription: Boto on visual studio

description: Boto on visual studio


code:
def check_username(self, username):
    counter = 1
    new_username = username
    while not User.objects.filter(username__iexact=new_username).exists():
        counter += 1
        new_username = username + str(counter)
    return new_username

rawDescription: why does this loop always return the original argument?

description: Why does this loop always return the original argument


code:
def testC(y, f, FC1, FC2):
    f2 = abs(f)
    idx = (f2>=FC1) & (f2<=FC2)
    y[~idx] = 0
    return y

rawDescription: Python: Conditional elements in array

description: Python: Conditional elements in array


rawDescription: Printing formatted arbitrary precision decimals in python


code:
import sys
from subprocess import check_call

check_call([sys.executable, "C:\\examples\\xml2html.py",
            "--dir", "c:\\Temp\\abcd", "c:\\tmp\\results.xml"])

rawDescription: Python: Executing the windows command in windows command prompt from python script


code:
import gnupg
dir(gnupg)
gnupg.Crypt.__doc__

rawDescription: How to get complete list of Method Name's and Doc String in Python Module?

description: Get complete list of Method Name's and Doc String in Python Module


code:
import Tkinter as tk
import tkFileDialog

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.floater = FloatingWindow(self)

class FloatingWindow(tk.Toplevel):
    def __init__(self, *args, **kwargs):
        tk.Toplevel.__init__(self, *args, **kwargs)
        self.overrideredirect(True)

        self.label = tk.Label(self, text="Click on the grip to move")
        self.grip = tk.Label(self, bitmap="gray25")
        self.grip.pack(side="left", fill="y")
        self.label.pack(side="right", fill="both", expand=True)

        self.grip.bind("<ButtonPress-1>", self.StartMove)
        self.grip.bind("<ButtonRelease-1>", self.StopMove)
        self.grip.bind("<B1-Motion>", self.OnMotion)

    def StartMove(self, event):
        self.x = event.x
        self.y = event.y

    def StopMove(self, event):
        self.x = None
        self.y = None

    def OnMotion(self, event):
        deltax = event.x - self.x
        deltay = event.y - self.y
        x = self.winfo_x() + deltax
        y = self.winfo_y() + deltay
        self.geometry("+%s+%s" % (x, y))

app=App()
app.mainloop()

rawDescription: Python/Tkinter: Mouse drag a window without borders, eg. overridedirect(1)


code:
my_dict = {}
with open('path', 'r') as file_object:
    for values in file_object:
        values = values.split()
        key = next(file_object, None)
        if key is None:
            # oops, we got to the end of the file early
            raise ValueError('Invalid file format, missing key')
        my_dict[key.strip()] = values

rawDescription: How to read every first line from a file as values, second as key to a dictionary

description: Read every first line from a file as values, second as key to a dictionary


code:
my_list = [1,2,3,4,5]
my_set = {*my_list}
my_set

rawDescription: Python Set: why is my_set = {*my_list} invalid?


code:
import urwid
import urwid.raw_display
import urwid.web_display

def main():
    text_header = (u"hi!  "
        u"UP / DOWN / PAGE UP / PAGE DOWN scroll.  F8 exits.")
    Radio_Text = [u"Select ",('important', u"one"), ]
    Multiselect_Text = [u"Select ",('important', u"many"), ]
    MultiSelect_Options = [u"Wax", u"Wash", u"Buff", u"Clear Coat", u"Dry",
        u"Racing Stripe"]
    Radio_Options = [u"opt1", u"opt2", u"opt3" ]

    def button_press(button):
        frame.footer = urwid.AttrWrap(urwid.Text(
            [u"Pressed: ", button.get_label()]), 'header')

    radio_button_group = []

    AttrWraps_list = [urwid.AttrWrap(urwid.CheckBox(txt),'buttn','buttnf') for txt in MultiSelect_Options]

    blank = urwid.Divider()
    listbox_content = [
        blank,
        urwid.Padding(urwid.Text(Radio_Text), left=2, right=2,
            min_width=20),
        blank,

        urwid.Padding(urwid.GridFlow(
            [urwid.AttrWrap(urwid.RadioButton(radio_button_group,
                txt), 'buttn','buttnf')
                for txt in Radio_Options],
            23, 7, 1, 'left') ,
            left=3, right=3, min_width=20),
        blank,
        urwid.Padding(urwid.Text(Multiselect_Text), left=2, right=2,
            min_width=20),
        blank,
        urwid.Padding(urwid.GridFlow(
            [urwid.AttrWrap(urwid.CheckBox(txt),'buttn','buttnf')
                for txt in MultiSelect_Options
        ],
            10, 3, 1, 'left') ,
            left=4, right=3, min_width=10),
        blank,
        blank,
        ]

    header = urwid.AttrWrap(urwid.Text(text_header), 'header')
    listbox = urwid.ListBox(urwid.SimpleListWalker(listbox_content))
    frame = urwid.Frame(urwid.AttrWrap(listbox, 'body'), header=header)

    palette = [
        ('body','black','light gray', 'standout'),
        ('reverse','light gray','black'),
        ('header','white','dark red', 'bold'),
        ('important','dark blue','light gray',('standout','underline')),
        ('editfc','white', 'dark blue', 'bold'),
        ('editbx','light gray', 'dark blue'),
        ('editcp','black','light gray', 'standout'),
        ('bright','dark gray','light gray', ('bold','standout')),
        ('buttn','black','dark cyan'),
        ('buttnf','white','dark blue','bold'),
        ]

    # use appropriate Screen class
    if urwid.web_display.is_web_request():
        screen = urwid.web_display.Screen()
    else:
        screen = urwid.raw_display.Screen()

    def unhandled(key):
        if key == 'f8':
            raise urwid.ExitMainLoop()
        if key == 'f5':
            txt = urwid.Text(str( {x.get_label(): x.get_state() for x in AttrWraps_list} ))
            fill = urwid.Filler(txt, 'top')
            loop = urwid.MainLoop(fill)
            loop.run()

    urwid.MainLoop(frame, palette, screen,
        unhandled_input=unhandled).run()

def setup():
    urwid.web_display.set_preferences("Urwid Tour")
    # try to handle short web requests quickly
    if urwid.web_display.handle_short_request():
        return

    main()

if '__main__'==__name__ or urwid.web_display.is_web_request():
    setup()

rawDescription: How to get urwid RadioButton and CheckBox values?

description: Get urwid RadioButton and CheckBox values


rawDescription: Python alternating input and output

description: Python alternating input and output


code:
wFc1_0 = weight_variable([32 * 32 * 64, 4096])
wFc1_1 = weight_variable([32 * 32 * 64, 4096])
wFc1_2 = weight_variable([32 * 32 * 64, 4096])
wFc1_3 = weight_variable([32 * 32 * 64, 4096])

# ...

# Readout layer
y = tf.nn.softmax(
    tf.concat(1, [tf.matmul(hPool2Flat, wFc1_0),
                  tf.matmul(hPool2Flat, wFc1_1),
                  tf.matmul(hPool2Flat, wFc1_2),
                  tf.matmul(hPool2Flat, wFc1_3),
                 ]) + bFc1)

rawDescription: TensorFlow - Unable to save checkpoint: Python exit code 139


code:
import urllib2
request = urllib2.Request("http://www.google.com", headers={"Accept" : "text/html"})
contents = urllib2.urlopen(request).read()

rawDescription: How do I send a custom header with urllib2 in a HTTP Request?

description: Send a custom header with urllib2 in a HTTP Request


code:
def find_results(seq): #I'm sure you can name this function better
    return [seq[0]] + [current for previous, current in zip(seq, seq[1:])
                       if current in previous]

rawDescription: How do you find out if the string is a component of the preceding string

description: Find out if the string is a component of the preceding string


code:
class MClass():

    def __init__(self):
        self.x = 2

    @property
    def y(self):
        return 5 * self.x

    #here a plus method for the setter
    @y.setter
    def y(self,value):
        self.x = y/5

    @property
    def z(self):
        return self.x * self.x

rawDescription: When to store things as part of an instance vs returning them?


code:
from Tkinter import *

remain = 11
_timer = None
def cdtimerr():
    global remain, _timer
    remain -= 1
    cdtext = canvas.create_text(510, 6, text=remain, font="Ubuntu 29 bold", anchor=NW)
    if remain == 0:
        canvas.delete(ALL)
    else:
        _timer = canvas.after(1000, lambda: (canvas.delete(cdtext), cdtimerr()))

root = Tk()
root.geometry('1024x768')
canvas = Canvas(root)
canvas.pack(expand=1, fill=BOTH)
_timer = canvas.after(0, cdtimerr)
Button(root, text='Cancel', command=lambda: canvas.after_cancel(_timer)).pack()
root.mainloop()

rawDescription: Python Overwriting text in Tkinter

description: Python Overwriting text in Tkinter


code:
import numpy as np
a = np.array(range(3*5*5)).reshape(3, 5, 5)
a
a[::2, ::2, ::2]
a[[slice(None, None, 2)] * a.ndim]

rawDescription: Subsampling numpy array in arbitrary number of dimensions


code:
import numpy as np
x = np.array([1,2,3,4,5])
b = np.array([True,False,False,True,False]) # this is your boolean data array
markers_on = x[~b]
markers_on

rawDescription: Plotting a "signals" series on a Matplotlib chart


code:
from social.backends.utils import load_backends
import myprojectname.settings as settings

backends = load_backends(settings.AUTHENTICATION_BACKENDS)
login_urls = ['//%s/login/%s/' % (settings.MY_SERVER_HOSTNAME, name) for name in backend.keys()]

rawDescription: How do I get the list of login stems for configured backends in python-social-auth?

description: Get the list of login stems for configured backends in python-social-auth


code:
import itertools
mydict={}
mydict['a']=[1,0,0,0,1,1,1,1,1,0,0]
mydict['b']=[2,4,5,6,8,7,5,4,5,6,7]
mydict['c']=[4,5,6,4,6,8,4,3,5,8,7]
#            ^       ^ ^ ^ ^ ^
mask = mydict['a']
for key, value in mydict.items():
    mydict[key] = list(itertools.compress(value, mask))
mydict

rawDescription: Deleting items witht the same index from multiple lists inside a dictionary


code:
x = np.array([[1], [2], [3]])
y = np.array([4, 5, 6])
x, y = np.broadcast_arrays(x, y)
x
y
x+y

rawDescription: How do you view a numpy broadcast object?

description: View a numpy broadcast object


code:
import json

newDictionary=json.loads(str(soup))

rawDescription: python beautiful soup how to json decode to dict

description: Python beautiful soup how to json decode to dict


code:
from collections import defaultdict

item_dict = defaultdict(list)

for item in value_list:
    item_dict[item.value].append(item)

# do some calculations base on values

new_data # some dictionary created by computation
# new data is stored new_data[value] = new_value

for value, new_value in new_data.items():
    for item in item_dict[value]:
        item.value = new_value

rawDescription: Using decorators vs iteration to set values?


code:
def get_old_value(attribute_state):
    history = attribute_state.history
    return history.deleted[0] if history.deleted else None

def trigger_attribute_change_events(object_):
    for mapper_property in object_mapper(object_).iterate_properties:
        if isinstance(mapper_property, ColumnProperty):
            key = mapper_property.key
            attribute_state = inspect(object_).attrs.get(key)
            history = attribute_state.history

            if history.has_changes():
                value = attribute_state.value
                # old_value is None for new objects and old value for dirty objects
                old_value = get_old_value(attribute_state)
                handler = registry.get(mapper_property)
                if handler:
                    handler(object_, value, old_value)

def on_after_flush(session, flush_context):
    changed_objects = session.new.union(session.dirty)
    for o in changed_objects:
        trigger_attribute_change_events(o)

event.listen(session, "after_flush", on_after_flush)

rawDescription: How can I get a SQLAlchemy ORM object's previous state after a db update?

description: Get a SQLAlchemy ORM object's previous state after a db update


code:
import ctypes
from ctypes import wintypes

user32 = ctypes.WinDLL("user32")

TOGGLE_UNHIDEWINDOW = 0x40
TOGGLE_HIDEWINDOW   = 0x80

user32.FindWindowW.restype = wintypes.HWND
user32.FindWindowW.argtypes = (
    wintypes.LPCWSTR, # lpClassName
    wintypes.LPCWSTR) # lpWindowName

user32.SetWindowPos.restype = wintypes.BOOL
user32.SetWindowPos.argtypes = (
    wintypes.HWND, # hWnd
    wintypes.HWND, # hWndInsertAfter
    ctypes.c_int,  # X
    ctypes.c_int,  # Y
    ctypes.c_int,  # cx
    ctypes.c_int,  # cy
    ctypes.c_uint) # uFlags

def hide_taskbar():
    handleW1 = user32.FindWindowW(u"Shell_traywnd", u"")
    user32.SetWindowPos(handleW1, 0, 0, 0, 0, 0, TOGGLE_HIDEWINDOW)

def unhide_taskbar():
    handleW1 = user32.FindWindowW(u"Shell_traywnd", u"")
    user32.SetWindowPos(handleW1, 0, 0, 0, 0, 0, TOGGLE_UNHIDEWINDOW)

rawDescription: Hide taskbar using Python in Windows XP

description: Hide taskbar using Python in Windows XP


code:
import numpy as np
from mayavi import mlab

def fun(x, y, z):
    return np.cos(x) + np.cos(y) + np.cos(z)

x, y, z = np.mgrid[-1:1:100j, -1:1:100j, -1:1:100j]
contour = mlab.contour3d(x, y, z, fun)
actor = contour.actor.actors[0]
polydata = tvtk.to_vtk(actor.mapper.input)  # solution
mlab.show()

rawDescription: Convert mayavi mlab.contour3d plot to vtkPolyData


rawDescription: How to parse dates to get the year in Python

description: Parse dates to get the year in Python


code:
json.dumps('test')
json.dumps(['test1', 'test2'])
json.dumps([u'test1', u'test2'])
json.dumps({u'key1': u'val1', u'key2': [u'val21', 'val22', 1]})

rawDescription: Representation of python dictionaries with unicode in database queries


code:
x=arange(10)
y1=sin(x)
y2=10*cos(x)

rect=[0.1,0.1,0.8,0.8]
a1=axes(rect)
a1.yaxis.tick_left()
plot(x,y1)
ylabel('axis 1')
xlabel('x')

a2=axes(rect,frameon=False)
a2.yaxis.tick_right()
plot(x,y2)
a2.yaxis.set_label_position('right')
ylabel('axis 2')
a2.set_xticks([])

rawDescription: Multiple overlapping plots with independent scaling in Matplotlib


code:
x
print(x)
x.oRecordData
x.value #allow for access in the oRecordData as attributes?
x._version, x._rid #other values in string representation

rawDescription: TypeError: 'OrientRecord' object does not support indexing


code:
def getXML(self,subreddit):
        url = 'http://www.reddit.com'+subreddit+'.rss'
        source = urllib.request.urlretrieve(url,'rss.xml')
        self.getXmlData()

rawDescription: Downloading XML file with Python 3

description: Downloading XML file with Python 3


code:
import wx
import thread
from time import sleep

class MainFrame(wx.Frame):

    def __init__(self, parent):
        wx.Frame.__init__(self, parent)

        self.label = wx.StaticText(self, label="Ready")
        self.btn = wx.Button(self, label="Start")
        self.gauge = wx.Gauge(self)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.label, proportion=1, flag=wx.EXPAND)
        sizer.Add(self.btn, proportion=0, flag=wx.EXPAND)
        sizer.Add(self.gauge, proportion=0, flag=wx.EXPAND)

        self.SetSizerAndFit(sizer)

        self.Bind(wx.EVT_BUTTON, self.onButton)

    def onButton(self, evt):
        self.btn.Enable(False)
        self.gauge.SetValue(0)
        self.label.SetLabel("Running")
        thread.start_new_thread(self.longRunning, ())

    def onLongRunDone(self):
        self.gauge.SetValue(100)
        self.label.SetLabel("Done")
        self.btn.Enable(True)

    def longRunning(self):
        """This runs in a different thread.  Sleep is used to simulate a long running task."""
        sleep(3)
        wx.CallAfter(self.gauge.SetValue, 20)
        sleep(5)
        wx.CallAfter(self.gauge.SetValue, 50)
        sleep(1)
        wx.CallAfter(self.gauge.SetValue, 70)
        sleep(10)
        wx.CallAfter(self.onLongRunDone)

if __name__ == "__main__":
    app = wx.PySimpleApp()
    app.TopWindow = MainFrame(None)
    app.TopWindow.Show()
    app.MainLoop()

rawDescription: Loading database?

description: Loading database


code:
from numpy import random
import matplotlib.pyplot as plt

data = random.random((5,5))
fig = plt.imshow(data,interpolation='nearest')
fig.set_cmap('hot')
plt.axis('off')
plt.savefig("test.png",bbox_inches='tight')

rawDescription: Matplotlib plots: removing axis, legends and white spaces


code:
def list_to_string(words):
    sentence = ""
    for word in words:
        sentence += word + " "
    return sentence.rstrip()     # before returning the string, this would strip all the trailing spaces.

rawDescription: assigning words from a list to a string with spaces between each word

description: Assigning words from a list to a string with spaces between each word


code: return wireAmpacityTable[pos1][1]

rawDescription: In Python, return specific item in list of Tuples, using bisect


code:
from pyparsing import *

LBRACE,RBRACE,SEMI,QUOTE = map(Suppress,'{};"')
ipAddress = Combine(Word(nums) + ('.' + Word(nums))*3)
hexint = Word(hexnums,exact=2)
macAddress = Combine(hexint + (':'+hexint)*5)
hdwType = Word(alphanums)

yyyymmdd = Combine((Word(nums,exact=4)|Word(nums,exact=2))+
                    ('/'+Word(nums,exact=2))*2)
hhmmss = Combine(Word(nums,exact=2)+(':'+Word(nums,exact=2))*2)
dateRef = oneOf(list("0123456"))("weekday") + yyyymmdd("date") + \
                                                        hhmmss("time")

startsStmt = "starts" + dateRef + SEMI
endsStmt = "ends" + (dateRef | "never") + SEMI
tstpStmt = "tstp" + dateRef + SEMI
tsfpStmt = "tsfp" + dateRef + SEMI
hdwStmt = "hardware" + hdwType("type") + macAddress("mac") + SEMI
uidStmt = "uid" + QuotedString('"')("uid") + SEMI
bindingStmt = "binding" + Word(alphanums) + Word(alphanums) + SEMI

leaseStatement = startsStmt | endsStmt | tstpStmt | tsfpStmt | hdwStmt | \
                                                        uidStmt | bindingStmt
leaseDef = "lease" + ipAddress("ipaddress") + LBRACE + \
                            Dict(ZeroOrMore(Group(leaseStatement))) + RBRACE

input = open(DHCPLEASEFILE).read()
with open(OUTPUTFILE, 'w') as output:
    for lease, start, stop in leaseDef.scanString(input):
        if lease.hardware.mac != mac:
            output.write(input[start:stop])

rawDescription: Removing a lease that has giving mac from dhcpd.leases with python?


code:
sample1 = pd.read_csv('sample_data.csv', dtype=str, error_bad_lines = False)
sample2 = pd.read_csv('sample2.csv', dtype=str, error_bad_lines = False)
sample_concat = pd.concat([sample1, sample2], keys = ['one', 'two'], ignore_index=True)

rawDescription: Pandas Combine Dataframe Options for More than one instance of Key?


rawDescription: dropping trailing '.0' from floats

description: Dropping trailing '.0' from floats


code:
import os

def machine():
    try:
        return os.uname()[-1]
    except AttributeError:
        if "PROCESSOR_ARCHITEW6432" in os.environ:
            return os.environ.get("PROCESSOR_ARCHITEW6432", '')
        else:
            return os.environ.get('PROCESSOR_ARCHITECTURE', '')

rawDescription: How to check if Windows is 32 or 64 bits on Python2.2

description: Check if Windows is 32 or 64 bits on Python2.2


code:
import re
pattern = re.compile(r'\W+')
pattern.split('vi nod-u')

rawDescription: To split on the basis of space and special character in python


code: agent,_,address = c.partition('@')

rawDescription: In line Conditional Expression or Function - Pythonic?


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup(body)
for div in soup.find_all(class_='highlight-nginx'):
    div.pre.string = my_function(div.pre.string)

rawDescription: Manipulate pieces of data in an html fragment in python


rawDescription: encoding URL into a format readable by google

description: Encoding URL into a format readable by google


code:
import sys,os
sys.path.append(os.path.abspath('..'))
from myproj.logger import LOG

rawDescription: Can't import module from bin directory of the same project


code:
class Node:
     def __init__(self, wordList=None, adjacencyList=None):
        if wordList is None:
            self.wordList = []
        else:
             self.wordList = wordList
        if adjacencyList is None:
            self.adjacencyList = []
        else:
             self.adjacencyList = adjacencyList

rawDescription: Python constructor and default value

description: Python constructor and default value


code:
from random import sample

with open("proxy_list.txt") as proxy_file:
    proxies = [proxy.strip() for proxy in proxy_file.readlines()]

    proxies = sample(proxies, min(len(proxies), 99))

    proxy_str = "|".join(proxies)

rawDescription: Python/Anything - Alter lines from text file, Randomize, Then save on specific line


code:
boundaris = [(0, 68), (68, 1190), (1190, 2248), (2248, 3399), (3399, 4795), (4795, 6023)]
names = ('4', 'X', '2R', '2L', '3R', '3L')
A = numpy.random.random((6023, 6023))

neworder = [3, 2, 5, 4, 0, 1]

def rearrange(l):
    return [l[i] for i in neworder]

newnames = rearrange(names)
ranges = numpy.concatenate([numpy.arange(l, u) for l, u in rearrange(boundaris)])
newA = A[numpy.ix_(ranges, ranges)]

rawDescription: Rearrange subarrays in a numpy array?

description: Rearrange subarrays in a numpy array


code:
binarystring = "asddfsdf"
tmp = long(binarystring.encode('hex'),16)
( "%x" % tmp ).decode('hex')

rawDescription: In Python how do you reverse this call: long("1234", 16)?


code:
import re
re.sub('<[^>]*>', '', mystring)

rawDescription: How to remove tags from a string in python using regular expressions? (NOT in HTML)

description: Remove tags from a string in python using regular expressions? (NOT in HTML)


code:
class YourApplication(QMainWindow):
  # ...

  def closeEvent(self, event):
    if condition:
      if QMessageBox.question(self, 'Your Application', 'Are you sure you want to exit?', QMessageBox.Yes, QMessageBox.No) == QMessageBox.Yes:
        # Do anything before the application closes

        event.accept()
      else:
        event.ignore()

rawDescription: Python PyQt4 closing the application

description: Python PyQt4 closing the application


rawDescription: How can we convert Django Post QueryDict


code:
from tkinter import *
r= Tk()
b= Button(text='hello', foreground='white', background='green',
          activeforeground='red', activebackground='blue')
b.pack()

rawDescription: A right background color of a button with tkinter?


code:
sProjectID = "project-id"
sQuery = '''
    SELECT
        column1, column2
    FROM [dataset_name.tablename]
'''

df = create_dataframe(sQuery, sProjectID, bLargeResults=True)

#*******Functions to make above work*********

def create_dataframe(sQuery, sProjectID, bLargeResults=False):
    "takes a BigQuery sql query and returns a Pandas dataframe"

    if bLargeResults:
        oService = create_service()
        dDestinationTable = run_query(sQuery, oService, sProjectID)
        df = pandas_get_table(dDestinationTable)
    else:
        df = pandas_query(sQuery, sProjectID)

    return df

def pandas_query(sQuery, sProjectID):
    "go into bigquery and get the table with sql query and return dataframe"
    from pandas.io import gbq
    df = gbq.read_gbq(sQuery, sProjectID)

    return df

def pandas_get_table(dTable):
    "fetch a table and return dataframe"
    from pandas.io import gbq

    sProjectID = dTable['projectId']
    sDatasetID = dTable['datasetId']
    sTableID = dTable['tableId']
    sQuery = "SELECT * FROM [{}.{}]".format(sDatasetID, sTableID)

    df = gbq.read_gbq(sQuery, sProjectID)

    return df

def create_service():
    "create google service"
    from oauth2client.client import GoogleCredentials
    from apiclient.discovery import build
    credentials = GoogleCredentials.get_application_default()
    oService = build('bigquery', 'v2', credentials=credentials)
    return oService

def run_query(sQuery, oService, sProjectID):
    "runs the bigquery query"

    dQuery = {
        'configuration': {
            'query': {
                'writeDisposition': 'OVERWRITE',
                'useQueryCache': False,
                'allowLargeResults': True,
                'query': sQuery,
                'destinationTable': {
                    'projectId': sProjectID,
                    'datasetId': 'sandbox',
                    'tableId': 'api_large_result_dropoff',
                },
            }
        }
    }

    job = oService.jobs().insert(projectId=sProjectID, body=dQuery).execute()

    return job['configuration']['query']['destinationTable']

rawDescription: Python BigQuery allowLargeResults with pandas.io.gbq


code:
a = A()
id(a)
id(a.method())
a is a.method()

rawDescription: In Python, does 'return self' return a copy of the object or a pointer?


code:
choices = {
    'vehicles': _('Vehicles'),
    'cars': _('Cars'),
    'bicycles': _('Bicycles'),
    'motorcycles': _('Motorcycles')
}
category = db.CategoryProperty(choices=choices.keys(), default='cars',
                               verbose_name="Category")

rawDescription: How to implement a category system

description: Implement a category system


rawDescription: wx slider binding function returns twice

description: Wx slider binding function returns twice


code:
text = u'étourdi, etourdi, étourdi, préchauffer'
words = re.findall(r'\w+', text, re.U)
cap_words = [unidecode.unidecode(word).upper() for word in words]

rawDescription: How to count words (and also those with accents !) in a text file in Python?

description: Count words (and also those with accents !) in a text file in Python


code:
class MySet(set):
    def __and__(self, other):
        return other

    def __rand__(self, other):
        return other

rawDescription: Implementing the All / Universal set

description: Implementing the All / Universal set


code:
#in this example x,y are the data that are collected, and model contains a function that uses x in fitting to obtain a model y-value.

#create model to evaluate and fit to data
def model(params, x):

    dGA = params['dGA'].value
    dGB = params['dGB'].value
    dGS = params['dGS'].value

    return (((dGA*x) + dGb)*dGS)

#create parameter class
params = lmfit.Parameters()
params.add('dGA', value = 2.9)
params.add('dGB', value = 2.89)
params.add('dGS', value = 3.6)

#now setup objective function which uses the model function
def objective(params):

    finalresid = []

    dGA = params['dGA'].value
    dGB = params['dGB'].value
    dGS = params['dGS'].value

    #can setup loop or anything for multiple data sets (y below)
    #if multiple, just have to lump all residuals into a
    #single flattened array. You could do this by setting up a loop over
    #all data sets, and combine the residuals at the end

    resid = (y - model(params, x))

return resid.flatten()

#now call mimimize() over the objective function with respect to the parameters
result = lmfit.minimize(objective, params)

rawDescription: How do minimize() and residual() functions work together in lmfit


code: df2.to_excel("filename", index=0)

rawDescription: how to prevent the index in a pandas dataframe from showing up in excel?

description: Prevent the index in a pandas dataframe from showing up in excel


code:
import scipy.sparse as sps

b = sps.csc_matrix((a.data, a.indices, a.indptr), shape=a.shape, copy=False)

rawDescription: Share SciPy Sparse Array Between Process Objects


code:
re.match('z\\|a', 'xyz|abc')
re.search('z\\|a', 'xyz|abc')
re.search(r'z\|a', 'xyz|abc')

rawDescription: Match a pipe character in the middle of a string with a python regex


code:
def createFile(data_set):
    output0 = open("Output" + data_set + ".txt","w")
    print >> output0, 'h1,h2,h3,h4'
    return output0

def runCalculations(data_set, output):
    file = open("file.csv","r")
    output = createFile(data_set)
    for row in file:
    # equations and stuff

        if data_set == 1:
            print >> output, row[1]+','+row[2]+','+row[3]+','+x
        if data_set == 2:
            print >> output, row[4]+','+row[5]+','+row[6]+','+y

    output.close()
    file.close()

runCalculations(1)

runCalculations(2)

rawDescription: Python: functions for creating and writing two output files


code:
x1.clip(min=0) + x3.clip(min=0)
x1.clip(max=0) + x3.clip(max=0)

rawDescription: Summing positive and negative elements from two NumPy arrays


code:
s = []
people = int(raw_input())
for i in range(people):
    firstn = raw_input()
    lastn = raw_input()
    numbers = int(raw_input())

    print(firstn, lastn, numbers)
    temp = 0
    for b in range(numbers):
        numbers = float(raw_input())
        temp += numbers
    s.append(temp)
print(s)

rawDescription: Python: Calculating a sum for each loop

description: Python: Calculating a sum for each loop