code:
from sympy import *

x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
w = Symbol('w')
u = Symbol('u')
q = Symbol('q')
e = Symbol('e')

f = x**3 + x*y**4 + x*z**2*w + u*q**2*w*e**3

f2 = (f*f)

F = integrate(f, x)
G = integrate(f, y)

rawDescription: python polynomial package of multiple variables

description: Python polynomial package of multiple variables


code:
a.im_self
a.im_self.b = 2
obj.b

rawDescription: Getting object's parent namespace in python?


code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(1974)

from itertools import cycle

# Generate Data
num = 20
x, y = np.random.random((2, num))
labels = np.random.choice(['a', 'b', 'c'], num)
df = pd.DataFrame(dict(x=x, y=y, label=labels))

groups = df.groupby('label')

markers = ['x', 'o', '^']

# Plot
fig, ax = plt.subplots()
ax.margins(0.05) # Optional, just adds 5% padding to the autoscaling
for (name, group), marker in zip(groups, cycle(markers)):
    ax.plot(group.x, group.y, marker=marker, linestyle='', ms=12, label=name)
ax.legend()

plt.show()

rawDescription: Scatter plots in Pandas/Pyplot: How to plot by category with different markers


code:
class SimClass(object):
    def run(self):
        self.results = ...
        self.plot = SimPlot(self)

class SimPlot(object):
    def __init__(self, simclass):
        self.simclass = simclass

    def plot1(self):
        # access simclass' attribute(s)
        self.simclass.results

sim = SimClass()
sim.run()
sim.plot.plot1()

rawDescription: Allow subclass in a class to access base class properties


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

line = [0.2, 0.3, 0.37, 0.4, 0.6, 0.7, 0.72, 0.75, 0.77, 0.78, 0.79, 0.795]
distribution = [0.2, 0.3, 0.3, 0.4, 0.7, 0.7, 0.7, 0.8]

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

ax2 = ax.twinx()
ax3 = ax2.twiny()

ax.plot(line)
ax.set_xlabel('line xaxis')
ax.set_ylabel('line yaxis')

ax3.hist(distribution, orientation='horizontal', alpha=.5)
ax3.invert_xaxis()
ax3.set_xlabel('hist xaxis, note where 0 is')
# note this needs to be ax2 due to subtle overlay issues....
ax2.set_ylabel('hist yaxis')
plt.draw()

rawDescription: line graph with histogram underlaid and on side

description: Line graph with histogram underlaid and on side


code:
class MyFormatter(Formatter):
    def format_field(self, value, format_spec):
        if format_spec == 't':  # Truncate and render as int
            return str(int(value))
        return super(MyFormatter, self).format_field(value, format_spec)

MyFormatter().format("{0} {1:t}", "Hello", 4.567)  # returns "Hello 4"

rawDescription: format() float as int

description: Format() float as int


code:
from oauth2client.client import GoogleCredentials
from oauth2client import GOOGLE_TOKEN_URI

access_token = None
token_expiry = None
token_uri = GOOGLE_TOKEN_URI
user_agent = 'Python client library'
revoke_uri = None

gCreds = GoogleCredentials(
    access_token,
    client_id,
    client_secret,
    refresh_token,
    token_expiry,
    token_uri,
    user_agent,
    revoke_uri=revoke_uri
    )

rawDescription: How to create Google API OAuth Credentials object from alternate source

description: Create Google API OAuth Credentials object from alternate source


code:
class BaseTestCase(TestCase):
    def setUp(self):
        self.patcher = patch('mymodule.foo')
        self.mock_foo = self.patcher.start()

    def tearDown(self):
        self.patcher.stop()

rawDescription: Django tests - patch object in all tests


code: [obj.id for obj in myObjects]

rawDescription: Python equivalent of C#'s .Select?

description: Python equivalent of C#'s .Select


code:
import StringIO
import os
config = StringIO.StringIO()
config.write('[dummysection]\n')
config.write(open('myrealconfig.ini').read())
config.seek(0, os.SEEK_SET)

import ConfigParser
cp = ConfigParser.ConfigParser()
cp.readfp(config)
somevalue = cp.getint('dummysection', 'somevalue')

rawDescription: parsing .properties file in Python

description: Parsing .properties file in Python


code:
from collections import namedtuple
class P(namedtuple('_P', 'val back')):
    def __iter__(self):
        while self:
            yield self.val, self.back
            self = self.back
q = P(val=15, back=P(val=11, back=P(val=9, back=P(val=6, back=P(val=2, back=P(val=0, back=None))))))
[val for val, back in q]

rawDescription: Get list of values from a nested Python data-structure using a list comprehension?


code:
a, b, c, d = range(1, 5)

result = (
    # First is 1
    a *
    # Then goes 2, result is 2 now
    b *
    # And then 3, result is 6
    c *
    # And 4, result should be 24
    d
)

rawDescription: Python: '#' Comments after backslash

description: Python: '#' Comments after backslash


code:
import re
s = 'I like this as much as that'
re.sub('and|as|like', '', s)

rawDescription: Alternative to Python string replace method


code:
dictionary = {'Year': [1985, 1985, 1986, 1986, 1987, 1987, 1987]}
pdf = pd.DataFrame(dictionary)
gb = pdf.groupby('Year')['Year'].count()

rawDescription: counting column values in pandas

description: Counting column values in pandas


code:
import couchdb
import simplejson as json

resource = couchdb.client.Resource(None, 'http://localhost:5984/dbname/_all_docs')
params = {"include_docs":True}
content = json.dumps({"keys":[idstring1, idstring2, ...]})
headers = {"Content-Type":"application/json"}
resource.post(headers=headers, content=content, **params)
resource.post(headers=headers, content=content, **params)[1]['rows']

rawDescription: Multiple CouchDB Document fetch with couchdb-python


code:
class CustomAdmin(admin.ModelAdmin):
    list_display = ('other_field', 'status')
    list_editable = ('status',)

rawDescription: Text Field not showing when using list_editable on django admin


code:
def test_func_wrapper(*args, **kwargs):
    return test_func(*args, **kwargs).ravel()

output = np.apply_along_axis(test_func_wrapper, m=3, n=2, axis=1, arr=input_data)
np.allclose(output.reshape(5,3, -1), output_data)
# output: True

rawDescription: NumPy: A General Vectorized Method to Apply a Function Returning a Matrix to Each Row of a Matrix


code:
class TestRawInput(unittest.TestCase):

    def test_raw_input(self):
        orig_raw_input = raw_input
        try:
            raw_input = lambda _: 'Alice'
            self.assertEquals(raw_input(), 'Alice')
        finally:
            raw_input = orig_raw_input

rawDescription: Python unit testing overriding module level functions


code:
def fs2InvoiceLinesCalc(*args):

    desktop = XSCRIPTCONTEXT.getDesktop()
    model = desktop.getCurrentComponent()
    try:
        sheets = model.getSheets()
    except AttributeError:
        raise Exception("This script is for Calc Spreadsheets only")
#    sheet = sheets.getByName('Sheet1')
    sheet = model.CurrentController.getActiveSheet()
    oSelection = model.getCurrentSelection()
    oArea = oSelection.getRangeAddress()
    first_row = oArea.StartRow
    last_row = oArea.EndRow
    first_col = oArea.StartColumn
    last_col = oArea.EndColumn
#get the string from Footswitch2 via a TCP port
    import os, socket, time
    from configobj import ConfigObj
    configuration_dir = os.environ["HOME"]
    config_filename = configuration_dir + "/fs2.cfg"
    if  os.access(config_filename, os.R_OK):
        pass
    else:
        return None
    cfg = ConfigObj(config_filename)
    #define values to use from the configuration file
    tcp_port = int(cfg["control"]["TCP_PORT"])
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(0.5)
    try:
        sock.connect(("localhost", tcp_port))
    except:
        return None
    sock.settimeout(10)
    try:
        sock.send(bytes('invoice\n', 'UTF-8'))
    except:
        return None
    try:
        time.sleep(1.0)
        s_list = sock.recv(4096).decode('UTF-8')
        s_list = s_list.split("\n")
    except:
        return None
    lines_in_response = len(s_list)
    if lines_in_response is None:
        return None
    column =['A','B','C','D','E','F','G','H','I','J','K','L','M',\
             'N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
    # merged rows are cumulative
    master_row_merge_adj = 0

    for x in range(0,lines_in_response):
        if s_list[x].startswith("END"):
            break
        row_merge_adj = master_row_merge_adj
        insert_table = s_list[x].split("\t")
        if s_list[x] == "":
            continue
        parts = len(insert_table)
    # merged columns are a simple adjustment for each item within x
        column_merge_adj = 0
        row_merge_done = 0
        for y in range(0,parts):
            it = insert_table[y]
            cell_name = column[first_col + y + column_merge_adj]+str(x +1 +first_row + row_merge_adj)
            cell = sheet.getCellRangeByName(cell_name)
            if cell.getIsMerged():
                cellcursor = sheet.createCursorByRange(cell)
                cellcursor.collapseToMergedArea()
                try:
                    # format AbsoluteName $Sheet1.$A$1:$D$2 for a merged cell of A1:D2
                    a,b,cell_range = cellcursor.AbsoluteName.partition(".")
                    start_cell, end_cell = cell_range.split(":")
                    a, start_col, start_row = start_cell.split("$")
                    a, end_col, end_row = end_cell.split("$")
                    column_merge_adj = column_merge_adj + (int(column.index(end_col)) - int(column.index(start_col)))
                    # merged rows are cumulative over each x
                    # merged row increment should only occur once within each x
                    # or data will not be in the top left of the merged cell
                    if row_merge_done == 0:
                        master_row_merge_adj = row_merge_adj + (int(end_row) - int(start_row))
                        row_merge_done = 1
                except:
                    #unable to compute - insert data off to the right so it's available for cut and paste
                    column_merge_adj = 10
            try:
                float(it)
                ins_numeric = True
            except:
                ins_numeric = False
            if ins_numeric:
                cell.Value = it
            else:
                cell.String = it
    if s_list[x].startswith("END"):
        insert_table = s_list[x].split("\t")
        try:
            invno = int(insert_table[1])
            cell_name = insert_table[4]
        except:
            pass
    try:
        cell = sheet.getCellRangeByName(cell_name)
        cell.Value = invno
    except:
        #The cell_name passed for Invoice number is incorrect, attempt to insert it in the next row, first selected column
        passed_cell_name = cell_name
        cell_name = column[first_col]+str(x +2 +first_row + row_merge_adj)
        cell = sheet.getCellRangeByName(cell_name)
        insert_text = "Invoice Number "+str(invno)+" Pos "+passed_cell_name+" Incorrect"
        cell.String = insert_text

    sock.close()
    return None

rawDescription: How do I write a python macro in libreoffice calc to cope with merged cells when inserting external data

description: Write a python macro in libreoffice calc to cope with merged cells when inserting external data


code:
def evaluate_bool(expr):
    if isinstance(expr, list):
        return all(evaluate_bool(e) for e in expr)
    elif isinstance(expr, tuple):
        return any(evaluate_bool(e) for e in expr)
    else:
        return expr

evaluate_bool([(True, False, False), True]) # True
evaluate_bool((False, [True, True, False], False)) # False

rawDescription: recursive boolean evaluation

description: Recursive boolean evaluation


code:
import time
timestamp = time.mktime(time.strptime('2015-10-20 22:24:46', '%Y-%m-%d %H:%M:%S'))

rawDescription: Convert date to timestamp in Python

description: Convert date to timestamp in Python


code:
data = {}

with open("data.csv") as f:
    reader = csv.reader(f, delimiter="\t")
    reader.next() # Skip header
    for row in reader:
        row = list(map(int, row))
        data[row[0]] = row[1:]

rawDescription: Taking items from a CSV file and putting the elements in a list


code:
def log(*args):
    logging.info(' '.join(map(str, args)))

rawDescription: Writing a 'print' function in Python

description: Writing a 'print' function in Python


rawDescription: How to download with wget in Python using variables?

description: Download with wget in Python using variables


rawDescription: pandas DataFrame.to_string() truncating strings from columns

description: Pandas DataFrame.to_string() truncating strings from columns


rawDescription: Using program variables in python logging configuration file


code:
import csv
import os

def process_vins():
    vin_numbers = []
    with open(os.path.join(os.path.dirname(__file__), 'ITRACK6VIN.csv'), 'r') as csvfile:
        vinreader = csv.reader(csvfile)
        vinreader.next() # skip the first row, presumably a header
        for row in vinreader: # iterate through each row in the file
            current_vin = row[0] # access the first element of the row
            current_vin = modify_vin(current_vin) # optional, do something with vin
            vin_numbers.append(current_vin) # store vins in a list

    return vin_numbers # return that list

process_vins()

rawDescription: Delete a row once it is used

description: Delete a row once it is used


code:
from urlparse import urlparse

url = "http://www.mega.pk/washingmachine-dawlance/"

path = urlparse(url).path  # get the path from the URL ("/washingmachine-dawlnace/")
path = path[:path.index("-")]  # remove everything after the '-' including itself
path = path[1:]  # remove the '/' at the starting of the path (just before 'washing')

rawDescription: Strip URL in Python

description: Strip URL in Python


code:
import boto

all_users = 'http://acs.amazonaws.com/groups/global/AllUsers'
conn = boto.connect_s3()
bucket = conn.get_bucket('mybucket')

for key in bucket:
    readable = False
    acl = key.get_acl()
    for grant in acl.acl.grants:
        if grant.permission == 'READ':
            if grant.uri == all_users:
                readable = True
    if not readable:
        key.make_public()

rawDescription: How can I programmatically check Amazon S3 permissions with boto?

description: Programmatically check Amazon S3 permissions with boto


code:
data = '
Paragraph containing
line break
'
soup = BeautifulSoup(data, 'html.parser')
str(soup).replace('
', '')

rawDescription:
Have BeautifulSoup output
 instead of

description:
Have BeautifulSoup output
 instead of


code:
import Tkinter as tk
import random

class Example(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root)
        self.canvas = tk.Canvas(self, width=400, height=400, background="bisque")
        self.xsb = tk.Scrollbar(self, orient="horizontal", command=self.canvas.xview)
        self.ysb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.ysb.set, xscrollcommand=self.xsb.set)
        self.canvas.configure(scrollregion=(0,0,1000,1000))

        self.xsb.grid(row=1, column=0, sticky="ew")
        self.ysb.grid(row=0, column=1, sticky="ns")
        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        for n in range(50):
            x0 = random.randint(0, 900)
            y0 = random.randint(50, 900)
            x1 = x0 + random.randint(50, 100)
            y1 = y0 + random.randint(50,100)
            color = ("red", "orange", "yellow", "green", "blue")[random.randint(0,4)]
            self.canvas.create_rectangle(x0,y0,x1,y1, outline="black", fill=color)
        self.canvas.create_text(50,10, anchor="nw",
                                text="Click and drag to move the canvas")

        # This is what enables scrolling with the mouse:
        self.canvas.bind("<ButtonPress-1>", self.scroll_start)
        self.canvas.bind("<B1-Motion>", self.scroll_move)

    def scroll_start(self, event):
        self.canvas.scan_mark(event.x, event.y)

    def scroll_move(self, event):
        self.canvas.scan_dragto(event.x, event.y, gain=1)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: Move a tkinter canvas with Mouse

description: Move a tkinter canvas with Mouse


code:
class TagStatusForm(forms.ModelForm):
    class Meta:
        model = TagStatus
        widgets = {'tag': forms.HiddenInput()}

rawDescription: Django ModelForm to have a hidden input

description: Django ModelForm to have a hidden input


code: b.bar()   # echoes B.foo

rawDescription: calling an overridden method from base class?

description: Calling an overridden method from base class


code:
# in initialization:
completer.connect("match-selected", self.match_selected)
self.combo = combo

def match_selected(self, completion, model, iter):
    self.combo.set_active_iter (iter)

rawDescription: Get active item of Gtk ComboBox after searching


code:
import base64
base64.b16encode(base64.b32decode("<your hash goes here>"))

rawDescription: How to convert 32digit long info hash to 40 digit long info hash in python?

description: Convert 32digit long info hash to 40 digit long info hash in python


code:
import requests
import socket
r = requests.get('http://google.com/', stream=True)
s = socket.fromfd(r.raw.fileno(), socket.AF_INET, socket.SOCK_STREAM)
s.getpeername()
s.getsockname()

rawDescription: How to get the underlying socket when using Python requests

description: Get the underlying socket when using Python requests


code:
from typing import TypeVar

T = TypeVar('T', bound=S)

def foo(g: T) -> T:
    pass

rawDescription: Python type hinting with constraint on type superclass


code:
class SomeContainer(object):
    def __iter__(self):
        for elem in self._datastructure:
            if elem.visible:
                yield elem.value

rawDescription: Can a method within a class be generator?


code:
import threading

sem = threading.Semaphore(0)

hostThread = threading.Thread(target=uploadToHost, args=(sem,))
backupThread = threading.Thread(target=uploadToBackup, args=(sem,))

sem.acquire() # Wait for one of them to finish
sem.acquire() # Wait for the other to finish

rawDescription: Python threading flow control in concise way


code: hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')

rawDescription: changing default x range in histogram matplotlib

description: Changing default x range in histogram matplotlib


code: movearray[imageasarray.T > 0] += 1

rawDescription: Faster/Better way to modify (tuple defined) parts of a Numpy array in Python?


code:
from PIL import Image
sess = tf.InteractiveSession()

# Pass image tensor object to a PIL image
image = Image.fromarray(image.eval())

# Use PIL or other library of the sort to rotate
rotated = Image.Image.rotate(image, degrees)

# Convert rotated image back to tensor
rotated_tensor = tf.convert_to_tensor(np.array(rotated))

rawDescription: tensorflow: how to rotate an image for data augmentation?

description: Tensorflow: how to rotate an image for data augmentation


code:
import Tkinter
#Set up a basic canvas
top = Tkinter.Tk()
canv = Tkinter.Canvas(top, bg="brown", height=250, width=300)

#Replace with what ever values you want
x = 50
y = 50

#Draw the first dot
line1 = canv.create_line(x, y, x - 2, y - 2, fill="green", width=3)
#This next line is pretty much all it takes to find the Y inverse
y = canv.winfo_reqheight() - y
#Draw the second dot
line2 = canv.create_line(x, y, x - 2, y - 2, fill="green", width = 3)

canv.pack()
top.mainloop()

rawDescription: How to reverse the y-axis of the imported image in Tkinter?

description: Reverse the y-axis of the imported image in Tkinter


code:
import Tkinter as tk
import random

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        size = 40
        menubar = tk.Menu(self)
        menubar.add_cascade(label="Game")
        menubar.add_cascade(label="Options")
        menubar.add_cascade(label="Help")
        chessboard = tk.Canvas(width=8*size, height=8*size, borderwidth = 0,
                               highlightthickness=0)
        statusbar = tk.Label(self, borderwidth=1, relief="sunken")
        right_panel = tk.Frame(self, borderwidth = 1, relief="sunken")
        scrollbar = tk.Scrollbar(orient="vertical", borderwidth=1)
        # N.B. height is irrelevant; it will be as high as it needs to be
        text = tk.Text(background="white",width=40, height=1, borderwidth=0, yscrollcommand=scrollbar.set)
        scrollbar.config(command=text.yview)

        toolbar = tk.Frame(self)
        for i in range(10):
            b = tk.Button(self, text="B%s" % i, borderwidth=1)
            b.pack(in_=toolbar, side="left")

        self.config(menu=menubar)
        statusbar.pack(side="bottom", fill="x")
        chessboard.pack(side="left", fill="both", expand=False)
        toolbar.grid(in_=right_panel, row=0, column=0, sticky="ew")
        right_panel.pack(side="right", fill="both", expand=True)
        text.grid(in_=right_panel, row=1, column=0, sticky="nsew")
        scrollbar.grid(in_=right_panel, row=1, column=1, sticky="ns")
        right_panel.grid_rowconfigure(1, weight=1)
        right_panel.grid_columnconfigure(0, weight=1)

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

rawDescription: How do I achieve the following Tkinter GUI layout with either pack or grid?

description: Achieve the following Tkinter GUI layout with either pack or grid


code:
list_of_dicts = [{} for i in range(32)]
len(list_of_dicts)
list_of_dicts[0]

rawDescription: Python 3 - Initiating a list with multiple dictionaries


code:
def resultsReportedAtCallsite(ancestorLevel = 1):
    class Ctx:
        def __enter__(self):
            test.fixateResultContext(ancestorLevel + 1)
        def __exit__(self, exc_type, exc_value, traceback):
            test.restoreResultContext()
    return Ctx()

def libraryFunction():
    with resultsReportedAtCallsite():
        test.compare("Apples", "Oranges")

rawDescription: How to decide where Python debugger stops and which line is to be blamed?

description: Decide where Python debugger stops and which line is to be blamed


code:
import math
train = [10, float('NaN'), 20, float('NaN'), 30]
train = [3 if math.isnan(x) else x for x in train]
train

rawDescription: finding and replacing 'nan' with a number

description: Finding and replacing 'nan' with a number


code:
import Tkinter as tk
import ImageTk

FILENAME = 'image.png'
root = tk.Tk()
canvas = tk.Canvas(root, width=250, height=250)
canvas.pack()
tk_img = ImageTk.PhotoImage(file = FILENAME)
canvas.create_image(125, 125, image=tk_img)
quit_button = tk.Button(root, text = "Quit", command = root.quit, anchor = 'w',
                    width = 10, activebackground = "#33B5E5")
quit_button_window = canvas.create_window(10, 10, anchor='nw', window=quit_button)
root.mainloop()

rawDescription: Image behind buttons in tkinter (PhotoImage)


code:
def test(vs, target_sum, current_total):
    counter = 0
    vranges = [range(0, target_sum+1, v) for v in vs]
    for ivec in itertools.product(*vranges):
        if sum(ivec) == current_total:
            counter += 1
    return counter

rawDescription: Is it possible to make reference to an unknown number of variables?


code:
if result['Content-Type'] in ('text/html', 'application/xhtml+xml'):
    # assuming you want to do something with the content
    doSomethingWithXHTML(result.content)
else:
    # use content for something else
    doTheOtherThing(result.content)

rawDescription: Sending the variable's content to my mailbox in Python?


code:
class MyView(ListView):
    # ...

    def get_context_data(self, **kwargs):
        context = super(MyView, self).get_context_data(**kwargs)
        context['mydata'] = ...
        return context

rawDescription: Generic view with additional parameters (if possible) or context processors to pass extra info to the template?


code:
def parse(self, response):
    for sel in response.xpath('//*[@id="conteudoInternas"]/ul/li'):
        item = CinemasItem()
        item['title'] = 'title'
        item['room'] = 'room'
        item['mclass'] = 'mclass'
        item['minAge'] = 'minAge'
        item['cover'] = 'cover'
        item['sessions'] = 'sessions'

        secondUrl = sel.xpath('p[1]/a/@href').extract()[0]

        # see: we are passing the item inside the meta
        yield scrapy.Request(url=secondUrl, meta={'item': item}, callback=self.secondPage)

def secondPage(self, response):
    # see: we are getting the item from meta
    item = response.meta['item']

    item['trailer'] = 'trailer'
    item['synopsis'] = 'synopsis'
    yield item

rawDescription: Recursive crawling over a page

description: Recursive crawling over a page


code: value.setParseAction(lambda t : ' '.join(t))

rawDescription: Get a whole unicode sentence

description: Get a whole unicode sentence


code:
from operator import itemgetter
p = [{'fn':'bill'}, {'fn':'Bob'}, {'fn':'bobby'}]
sorted(p, key=itemgetter('fn'))
sorted(p, key=lambda x: x['fn'].lower())

rawDescription: How do I make this sorting case insensitive?

description: Make this sorting case insensitive


code:
s = """2. Name Bla B'd
32. da Bla 'B'
4 Name Bla 'B'
232 data' Name Name
test Name Name"""
result = re.sub(r"^[ \d.]+", "", s, flags=re.MULTILINE)
print(result)

rawDescription: Regex to match 3 completly different styles of text


rawDescription: Python (Perl-type) regex lookahead/lookbehind


code:
import networkx as nx
G = nx.Graph()
G.add_edges_from([('v1','v2'),('v2','v4'),('v1','v3')])

def neighborhood(G, node, n):
    path_lengths = nx.single_source_dijkstra_path_length(G, node)
    return [node for node, length in path_lengths.iteritems()
                    if length == n]

print(neighborhood(G, 'v1', 1))
# ['v2', 'v3']
print(neighborhood(G, 'v1', 2))
# ['v4']

rawDescription: Finding the n-degree neighborhood of a node


code:
myplot = list_plot(
    zip(range(20), range(20)),
    color='red',
    legend_label='legend item 1')

myplot2 = list_plot(
    zip(range(20), [i*2 for i in range(20)]),
    color='blue',
    legend_label='legend item 2')

combined = myplot + myplot2

combined.axes_labels(['testing x axis', 'testing y axis'])
combined.legend(True)

combined.show(title='Testing title', frame=True, legend_loc="lower right")

rawDescription: How to add titles, axis label, and legend in sagemath?

description: Add titles, axis label, and legend in sagemath


code:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

browser = webdriver.Firefox()
browser.get('https://vsco.co/vincentdemers/media/573bb798ee5e1d0c03edbe1f')
WebDriverWait(browser, 10).until(lambda d: d.find_element_by_css_selector('#ember610 > img').is_displayed())
source = browser.page_source
browser.close

rawDescription: Waiting for a Page to Load in Selenium/Firefox w/ Python


code:
# ... all your data collection
df = pd.DataFrame(data, columns=data.keys())

rawDescription: pandas.DataFrame.from_dict not preserving order using OrderedDict

description: Pandas.DataFrame.from_dict not preserving order using OrderedDict


code:
dummylist = [len(r.split('abc')) for r in list123]
for i, n in enumerate(dummylist):
    if n <= 2:
        list123[i] = list123[i].replace('abc', 'q')
    else:
        list123[i] = 'q'.join(list123[i].rsplit('abc', 1))

rawDescription: Replacing the values of a list whilst there is a while loop


code:
import subprocess
subprocess.call(["vi"])
subprocess.call(["ssh","127.0.0.1"])

rawDescription: In Python, how could I shell out and interact with an external program (say vi or nano) and return to python


code:
# since your `values` is already a tuple
cur.execute(query, values)

# otherwise can be written as...
cur.execute(query, (r["column1"], r["column2"], r["column3"]))

rawDescription: python dbf to mysql

description: Python dbf to mysql


code:
import platform
platform.system()

rawDescription: Can I detect if my code is running on cPython or Jython?

description: Detect if my code is running on cPython or Jython


code:
import lxml.html

root = lxml.html.fromstring(driver.page_source)
for row in root.xpath('.//table[@id="thetable"]//tr'):
    cells = row.xpath('.//td/text()')
    dict_value = {'0th': cells[0],
                  '1st': cells[1],
                  '2nd': cells[2],
                  '3rd': cells[3],
                  '6th': cells[6],
                  '7th': cells[7],
                  '10th': cells[10]}

rawDescription: Getting text of a table quickly in Selenium


code:
import json
...
def to_json(self):
    d = {
           "id": str(self.id),
           "sensorid": str(self.sensorid)
        }
    if not self.start is None:
        d['start'] = self.start.isoformat()
    if not self.end is None:
        d['end'] = self.end.isoformat()

    return json.dumps(d)

rawDescription: MongoEngine Document JSON output

description: MongoEngine Document JSON output


code:
import tkinter as tk

class Example(object):
    def __init__(self):
        self.value = None
        self.root = None

    def show(self):
        '''Show the window, and wait for the user to click a button'''

        self.root = tk.Tk()
        true_button = tk.Button(self.root, text = "True",
                                command= lambda: self.finish(True))
        false_button = tk.Button(self.root, text = "False",
                                 command= lambda: self.finish(False))

        true_button.pack()
        false_button.pack()

        # start the loop, and wait for the dialog to be
        # destroyed. Then, return the value:
        self.root.mainloop()
        return self.value

    def finish(self, value):
        '''Set the value and close the window

        This will cause the show() function to return.
        '''
        self.value = value
        self.root.destroy()

print("getting ready to show dialog...")
print("value:", Example().show())

rawDescription: How to get buttons to get a function to return something?

description: Get buttons to get a function to return something


rawDescription: cv2 Python disable GUI bar on Debian Linux (Raspberry Pi)

description: Cv2 Python disable GUI bar on Debian Linux (Raspberry Pi)


code:
from PyQt4 import QtGui
import sys
import numpy as np
import matplotlib as mpl
mpl.use('Qt4Agg')
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

class MyMplCanvas(FigureCanvas):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = mpl.figure.Figure(figsize=(width, height), dpi=dpi)
        fig.set_tight_layout('tight')
        super(MyMplCanvas, self).__init__(fig)

class MyStaticMplCanvas(MyMplCanvas):

    def mystatic(self, parent=None):

        x, y = np.random.rand(50), np.random.rand(50)
        ax1 = self.figure.add_subplot(411)
        ax1.plot(x,y, '.')
        ax2 = self.figure.add_subplot(412)
        ax2.plot(x,y, '.')
        ax3 = self.figure.add_subplot(413)
        ax3.plot(x,y, '.')
        ax4 = self.figure.add_subplot(414)
        ax4.plot(x,y, '.')

if __name__ == '__main__' :

    app = QtGui.QApplication(sys.argv)

    w = MyStaticMplCanvas(width=5, height=6, dpi=100)
    w.mystatic()
    w.show()

    sys.exit(app.exec_())

rawDescription: PYQT and embedding matplotlib: Graph not showing


rawDescription: How to change numbers around in a list in python

description: Change numbers around in a list in python


code:
buttons = []
buttonphotos = []
# here goes your loop
for imgphoto in (imagedict.keys()):
    buttonphotos.append(Image.open(imgphoto).thumbnail((120,120)))
    # [...] some of your actions
    # access buttonphoto by using last elem index
    # buttonphotos[-1]
    buttons.append(tk.Button(root, [...])) # pseudo code line
    buttons[-1].grid([...]) # pseudo code line

rawDescription: Creating multiple variables during each iteration of for loop and executing tk commands on them


code:
from django.db import models
from django.contrib.auth.models import AbstractUser

class Genre(models.Model):
    name = models.Charfield(max_length=255)

class BookGenre(models.Model):
    book = models.ForeignKey('Book')
    genre = models.ForeignKey('Genre')
    score = models.IntegerField()

class Book(models.Model):
    title = models.CharField(max_length=255)
    # etc...
    genres = models.ManyToManyField('Genre', through=BookGenre)

class UserGenre(models.Model):
    user = models.ForeignKey('User')
    genre = models.ForeignKey('Genre')
    score = models.IntegerField()

class User(AbstractUser):
    genres = models.ManyToManyField('Genre', through=UserGenre)

rawDescription: Designing a simple book recommendation system in python?


code: result = numpy.correlate([1], [1])[0]

rawDescription: A Function Returns a List with one Value. How to assign it?


rawDescription: Draw multiple samples using numpy.random.multivariate_normal(mean, cov[, size])


code:
import pycurl
import sys

def bodycb(buf):
    import sys
    sys.stdout.buffer.write(buf)

def headercb(buf):
    import sys
    sys.stdout.buffer.write(buf)

headers = ['X-Storage-User:12345:12345', 'X-Storage-Pass:new1234']

pycurl_connect = pycurl.Curl()
pycurl_connect.setopt(pycurl.URL, 'https://ssproxy.ucloudbiz.olleh.com/auth/v1.0')
pycurl_connect.setopt(pycurl.HTTPHEADER, headers)
pycurl_connect.setopt(pycurl.WRITEFUNCTION, bodycb)
pycurl_connect.setopt(pycurl.HEADERFUNCTION, headercb)
pycurl_connect.perform()

rawDescription: curl example to pycurl

description: Curl example to pycurl


code:
import lxml.html

telnr = "0306636793"
p = lxml.html.HTMLParser(encoding='utf-8')
root = lxml.etree.parse("http://www.11880.com/rueckwaertssuche/%s"%telnr, parser=p).getroot()
h3 = root.cssselect(b'h3')
txt = h3[0].text_content()

rawDescription: everything is utf-8 .. but I only get dirt

description: Everything is utf-8 .. but I only get dirt


code:
from django.db import models, transaction
class Course(models.Model):
    student_group = models.OneToOneField(Group, related_name="course_taken")

    @transaction.commit_on_success
    def save(self, *args, **kwargs):
        if not self.student_group_id:
            self.student_group, _ = Group.objects.get_or_create(name='_course_' + self.id + '_student')

        super(Course, self).save(*args, **kwargs)

rawDescription: Auto-creating related objects on model creation in Django


code:
import os, sys, time
import zipfile

ENC = 'cp437'
outdir = unicode(os.path.abspath('.'))
outzip = 'c:/1temp/timbersales.zip'
zf = zipfile.ZipFile(outzip, 'r')

for info in zf.infolist():
    fn, dtz = info.filename, info.date_time # , info.file_size

    # some zips have dirs listed as files. Catch
    # and bypass those.
    name = os.path.basename(fn)
    if not name:
        continue

    # get our filename converted from bytes to unicode
    fn_uni = fn.decode(ENC, 'replace')
    bn_uni = os.path.basename(fn_uni)

    # this method is about 15% faster than extractall, and
    # preserves modify and access dates
    c = zf.open(fn)
    outfile = os.path.join(outdir, bn_uni)

    # try/except to avoid problems with locked files, etc
    # do in chunks to avoid memory problems
    chunk = 2**16
    try:
        with open(outfile, 'wb') as f:
            s = c.read(chunk)
            f.write(s)
            while not len(s) < chunk:
                s = c.read(chunk)
                f.write(s)
        c.close()
        # set modify and access dates to that inside the zip
        dtout = time.mktime(dtz + (0, 0, -1))
        os.utime(outfile, (dtout, dtout))
    except IOError:
        c.close()

rawDescription: Python: Unzip a file to current working directory but not maintain directory structure in zip


code:
import webbrowser

urls = ['http://www.google.com', 'http://www.reddit.com', 'http://stackoverflow.com']
b = webbrowser.get('firefox')
for url in urls:
    b.open(url)

rawDescription: How to open a list of address in browser

description: Open a list of address in browser


code:
import numpy as np
a = np.array([True, True, False])
b = np.array([False, True, True])
a | b
a & b

rawDescription: Python: operation on a vector of True/False


code:
import os.path
scriptpath = os.path.abspath(os.path.dirname(__file__))

configfile = os.path.join(scriptpath, configfilename)

rawDescription: Python script on linux and autostart at boot path


code:
class ChatMessage(Base):
    __tablename__ = 'chat_messages'
    id = sa.Column(sa.Integer, primary_key=True)
    sender_id = sa.Column(sa.Integer, sa.ForeignKey(User.id))
    receiver_id = sa.Column(sa.Integer, sa.ForeignKey(User.id))
    content = sa.Column(sa.String, nullable=False)

    __table_args__ = (
        sa.CheckConstraint(receiver_id != sender_id),
    )

rawDescription: sqlalchemy constraint in models inheritance

description: Sqlalchemy constraint in models inheritance


code:
import pandas as pd
df = pd.DataFrame({"var1": [1, 1, 2, 2, 3, 3], 'var2': [1, 2, 3, 4, 5, 6]})
df
df['var2'] = df.groupby('var1').transform(max)
df

rawDescription: Speed up dataframe loop

description: Speed up dataframe loop


rawDescription: PyGtk: How to unpack boxes

description: PyGtk: How to unpack boxes


code:
# not thread safe code! - all threads modifying the same element
def get_url(url):
    result = urllib2.urlopen(url).read()

    #in this example, theResultList is a list of integers
    theResultList[0] += 1

rawDescription: Is this usage of Python threading safe/good?


code:
class CalcSomething(object):
    def __init__(self):
        self._cache = {}
    def __call__(self, a):
        if a not in self._cache:
            self._cache[a] = self.reallyCalc(a)
        return self._cache[a]
    def reallyCalc(self, a):
        return # a real answer
calcSomething = CalcSomething()

rawDescription: Simulating a 'local static' variable in python


code:
for _ in range(bits - 1):
    rem = number % 2
    s.push(rem)
    number = number // 2

rawDescription: Sign-Magnitude Binary Equivelent in Python


rawDescription: Env Variables in Python (v3.0) on Windows


code:
class CItem(list):
    def __eq__(self, other):
        return list.__eq__(self, other) and self.__dict__ == other.__dict__

rawDescription: pythonic way to compare compound classes?

description: Pythonic way to compare compound classes


code:
class Vec(list):
    pass

functions = {"__add__": operator.add,
             "__mul__": operator.mul,
             "__truediv__": operator.truediv,
             "__sub__": operator.sub}
for name, op in functions.iteritems():
    setattr(Vec, name, lambda self, other, op=op: Vec(map(op, self, other)))

rawDescription: python catching functions

description: Python catching functions


code:
def get_form(self, request, obj=None, **kwargs):
    if not request.user.is_superuser:
       self.exclude = []
    else:
       self.exclude = ['approved','day_of_the_week','photo']

    return super(RestauranteAdmin, self).get_form(request, obj, **kwargs)

rawDescription: Django Admin - Inline forms missing after overriding get_form


code:
highvalue = 25
lowvalue = 21
def myfunc():
    return lowvalue if highvalue>21 else highvalue
myfunc()

rawDescription: Convert Simple Obj-C into Python

description: Convert Simple Obj-C into Python


code:
import cherrypy
import nltk
from nltk.book import text4
import simplejson

class BiGrams:
    def index(self):
        c = text4.collocations(num=20)
        return simplejson.dumps(c)
    index.exposed = True

cherrypy.quickstart(BiGrams())

rawDescription: CherryPy WebService not returning NLTK collocations to browser window


code:
import weakref

class A(object):
  _get_obj_cache = weakref.WeakValueDictionary()
  @classmethod
  def get_obj(cls, identifier):
    cache = cls._get_obj_cache
    obj = cache.get((cls, identifier))
    if obj is None:
      obj = cache[(cls, identifier)] = cls(identifier)
    return obj

class B(A):
  pass

rawDescription: How to create instances of a class from a static method?

description: Create instances of a class from a static method


code:
fastq_filename = "test_file"
fastq = open(fastq_filename) # fastq is the file object

canPrintLines = False # Boolean state variable to keep track of whether we want to be printing lines or not
for line in fastq:
    if line.startswith("@"):
        canPrintLines = True # We have found an @ so we can start printing lines
        line = line.replace("@", ">")
    elif line.startswith("+"):
        canPrintLines = False # We have found a + so we don't want to print anymore

    if canPrintLines:
        print(line)

rawDescription: Print lines between two patterns in python


code:
surnames = sorted(i.split(",")[0] if "," in i else i.split()[-1]
                  for i in names.split(" and "))

rawDescription: Extract surnames from a string with names in python


code:
ax1.plot(pd.to_datetime(dfr.ix[dfr['sig']=='EXIT'].index),
    dfr.short_sma[dfr['sig']=='EXIT'],
    'v', markersize=10, color='k' ,label='sell')

rawDescription: I want to use matplotlib to plot date chart,but it showi nvalid literal for float(): 2014-12-10


code:
def change_order2(new_order, old_order, old_card, old_list):
    import numpy as np
    new_ord = [~old_order.index(letter) for letter in new_order]
    old_list = np.array(old_list).reshape(old_card[::-1])
    new_list = np.transpose(old_list, new_ord[::-1]).flatten()
    return new_list

rawDescription: Better way to rearrange elements in a list


rawDescription: Python combine two lists of unequal length in alternating fashion


code:
import urllib
content = urllib.urlopen("http://www.google.com").read()
#urllib.request.urlopen(...).read() in python 3

rawDescription: Downloading contents of several html pages using python


rawDescription: How do you replace regex end-of-line with string?

description: Replace regex end-of-line with string


code: pl.plot(freqs, con, label="$\mu_N: %g$"%noise_mu, linewidth=1.5)

rawDescription: Python pylab plot legend scientivic writing


code:
import random

def combine(wt1, wt2):
    return random.random() < .1, (wt1+wt2)//2

class Linetree():
    def __init__(self, wts):
        self.nodes = []
        for i, wt in enumerate(wts):
            self.nodes.append([[i+1, wt]])

        self.nodes.append([])
        self.processed = []
        self.checked = []

    def processnode(self, idx):
        if idx in self.processed:
            return

        ichild = 0
        while ichild < len(self.nodes[idx]):
            chidx, chwt = self.nodes[idx][ichild]
            self.processnode(chidx)

            igrandchild = 0
            while igrandchild < len(self.nodes[chidx]):
                grchidx, grchwt = self.nodes[chidx][igrandchild]
                if (idx, grchidx) in self.checked:
                    igrandchild += 1
                    continue

                tocombine, newwt = combine(chwt, grchwt)
                self.checked.append((idx, grchidx))
                if tocombine:
                    self.nodes[idx].append([grchidx, newwt])

                igrandchild += 1
            ichild += 1
        self.processed.append(idx)

    def build(self):
        self.processnode(0)

    def get_paths(self, n=0):
        if len(self.nodes[n]) == 0:
            yield [n]

        for ch, wt in self.nodes[n]:
            for sub_path in self.get_paths(ch):
                yield [n] + sub_path

    def pathwt(self, path):
        ret = 0
        for i in range(len(path)-1):
            for child, wt in self.nodes[path[i]]:
                if child == path[i+1]:
                    ret += wt
                    break
            else:
                raise ValueError(str(path))

        return ret

    def __str__(self):
        ret = ""
        for i, children in enumerate(self.nodes):
            ret += "\nNode {}: ".format(i)
            for child in children:
                ret += "{}, ".format(child)
        return ret

def main():
    wts = range(10, 80, 10)
    print(list(enumerate(wts)))
    lt = Linetree(wts)
    print(lt.nodes)
    print(lt)
    lt.build()
    print(lt)

    paths = lt.get_paths()
    for path in paths:
        print(path, lt.pathwt(path))

main()

rawDescription: Linear Directed Acyclic Graph

description: Linear Directed Acyclic Graph


code:
import random
word_list = ['apple', 'banana', 'orange']
shuffled_list = [''.join(random.sample(s,len(s))) for s in word_list]
shuffled_list

rawDescription: I'm trying to create a program that creates anagrams from a string of words


code:
translation_table = str.maketrans(a1, a2)
swapped = input1.translate(translation_table)

rawDescription: Beginner Python 3.3.2 - How do I use .replace() from a file?


code:
from django.core.serializers.json import Serializer, DjangoJSONEncoder
from django.utils import simplejson

class NewSerializer(Serializer):
    def end_serialization(self):
        cleaned_objects = []

        for obj in self.objects:
            del obj['pk']
            del obj['model']
            cleaned_objects.append(obj)

        simplejson.dump(cleaned_objects, self.stream, cls=DjangoJSONEncoder, **self.options)

rawDescription: How can I serialize single object's fields in django(without pk and model)

description: Serialize single object's fields in django(without pk and model)


code:
def reverse_toctree(app, doctree, docname):
    """Reverse the order of entries in the root toctree if 'glob' is used."""
    if docname == "index":
        for node in doctree.traverse():
            if node.tagname == "toctree" and node.get("glob"):
                node["entries"].reverse()
                break

def setup(app):
    app.connect("doctree-resolved", reverse_toctree)

rawDescription: Within a Sphinx documentation, how can I revert the order of the toctree that is provided by the "glob" flag option?


rawDescription: How to execute a path in Windows from Python program?

description: Execute a path in Windows from Python program


code:
from java.lang import System
from java.io import PrintStream, OutputStream
oldOut = System.out
class NoOutputStream(OutputStream):
    def write(self, b, off, len): pass

System.setOut(PrintStream(NoOutputStream()))
System.out.println('foo')
System.setOut(oldOut)
System.out.println('foo')

rawDescription: Controlling stdout/stderr from Jython

description: Controlling stdout/stderr from Jython


code:
from my_module import run

run(...)

rawDescription: imported my module: not defined (python 3.4)

description: Imported my module: not defined (python 3.4)


code: d = runner.crawl(spider_cls, start_urls=["url"])

rawDescription: Scraping one page with scrapy

description: Scraping one page with scrapy


code:
def floatstrcmp(left, right):
   try:
      return cmp(float(left), float(right))
   except ValueError:
      return cmp(left, right)

rawDescription: Compare string and floats in python

description: Compare string and floats in python


code:
class Item(models.Model):

    name = name = models.CharField(max_length = 75)
    sub_category = models.ForeignKey(
        'ItemSubcategory',
        limit_choices_to={'ItemCategory': 'Food'}
    )

rawDescription: Django; limit Subcategory to a certain Main Category


code:
def my_not_cb_view(request):
    user = request.user
    games = Game.objects.filter(user=User.user)
    context = {'games': games, 'user': user}
    render_to_response(request, 'user profile.html', context=context)

rawDescription: Django - How to filter a ListView by user without using CBV?


code:
from itertools import chain

writer.writerows([data1, data2, data3] + list(chain.from_iterable(zip(lat, lon))) )

rawDescription: Splice Two Lists and Output to CSV

description: Splice Two Lists and Output to CSV


code:
LOOK_UP_TABLE = {
    'users' : {
        'model': ...,
        'serializer_class': ...,
    },
    'categories' : {
        ...
    },
}

rawDescription: Better way of defining filtered endpoints using Django REST framework


code:
def joint_positions(j):
    pos = [cmds.xform(j,q=True, t=True, ws=True)]
    children = cmds.listRelatives(j, c=True) or []
    for child in children:
        pos.extend(joint_positions(child))
    return pos
joints = joint_positions('joint1')
cmds.curve(d = 1, p=joints)

rawDescription: How can I create a Maya Nurbs curve to match a joint chain?

description: Create a Maya Nurbs curve to match a joint chain


code:
s = "\u5bc6\u7801\u8f93\u5165\u9519\u8bef\uff0c\u8fd8\u53ef\u4ee5\u8f93\u51654\u6b21"
type(s)
r = s.decode("unicode-escape")
type(r)
print(r)

rawDescription: Python 2.7 How to Print unicode-escape format string?


code:
from operator import mul
reduce(mul, [1, 2, 3], 1)

rawDescription: Product of a list python

description: Product of a list python


rawDescription: numpy opencv flip set of rows

description: Numpy opencv flip set of rows


code:
import pandas as pd
import io

all_person_ids = [0, 1, 2]
all_statuses = ['pass', 'fail']
all_years = [1980, 1981, 1982]
df = pd.read_csv(io.BytesIO("""person_id   status    year    count
0           pass    1980    4
0           fail    1982    1
1           pass    1981    2"""), delim_whitespace=True)
names = ["person_id", "status", "year"]

mind = pd.MultiIndex.from_product(
    [all_person_ids, all_statuses, all_years], names=names)
df.set_index(names).reindex(mind, fill_value=0).reset_index()

rawDescription: Adding values for missing data combinations in Pandas


code:
sum((Values[v] + Addons[c]) * Multipliers[v]
         for c, vs in Category.items()
              for v in vs if c in Addons)
# 1225.5

rawDescription: Fetching and evaluating data from several dictionaries using filter,reduce,add,map


code:
def findList(lst, ele):
    if not lst:         # base case: the list is empty
        return False
    elif lst[0] == ele: # check if current element is the one we're looking
        return True
    elif not isinstance(lst[0], list): # if current element is not a list
        return findList(lst[1:], ele)
    else:                              # if current element is a list
        return findList(lst[0], ele) or findList(lst[1:], ele)

rawDescription: Recursively going through a list (python)


code:
def loadpath(path):
    module_name = os.path.basename(path)[:-3]
    if os.path.isdir(path):
        # module/__init__.py style
        d, f = os.path.split(path.rstrip('/'))
        fd, fpath, desc = imp.find_module(f, [d])
        return imp.load_module(module_name, fd, fpath, desc)
    else:
        return imp.load_source(module_name, path)

rawDescription: Import file by file path entered by user


code:
import pygame
from pygame.locals import *

pygame.init()
# not normally all global, but simplified demo
color_bg = Color("gray20")
color_fg = Color("gray80")
clock = pygame.time.Clock()

screen = pygame.display.set_mode((600,400))

class Entity():
    def __init__(self, pos=(300, 300)):
        self.pos = pos
        self.armR = (10, 10)
        self.armL = (-10, 10)
        self.body = (0, -20)
        self.head_offset = self.offset(self.body)

    def offset(self, offset):
        # get offset to draw, relative stickman's hips
        return (self.pos[0]+offset[0], self.pos[1]+offset[1])

    def render(self):
        b = self.pos
        #pygame.draw.line( screen, color_fg, (10,10), (20,30) )

        o = self.offset( self.armL )
        pygame.draw.line( screen, color_fg, b, o )

        o = self.offset( self.armR )
        pygame.draw.line( screen, color_fg, b, o )

        o = self.offset( self.body )
        pygame.draw.line( screen, Color("red"), b, o )

class Game():
    def __init__(self):
        self.e = Entity()

    def draw(self):
            screen.fill( color_bg )

            self.e.render()

            pygame.display.flip()
            clock.tick(80)

    def loop(self):
        done=False

        while not done:
            events = pygame.event.get()

            for event in events:
                if event.type == pygame.QUIT: done = True
                # event: keydown
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE or event.key == K_SPACE: done = True
                elif event.type == MOUSEMOTION:
                    self.mouse_loc = event.pos

            self.draw()

g = Game()
g.loop()

rawDescription: Pygame draw not drawing what it should

description: Pygame draw not drawing what it should


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

def P(X, Y):
    return mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)

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

x = np.linspace(-2, 2, 60)
y = np.linspace(-2, 2, 60)
X, Y = np.meshgrid(x, y)
Z = P(X, Y)
surf = ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, cmap = jet, linewidth = 0)
ax.set_zlim3d(0, Z.max())

plt.show()

rawDescription: Probability surface plot matplotlib

description: Probability surface plot matplotlib


rawDescription: Disable order email in Django-oscar

description: Disable order email in Django-oscar


code:
def flatten(data):
    res = []
    if hasattr(data, '__iter__'):
        for el in data:
            res.extend(flatten(el))
    else:
        res.append(data)
    return res

reduce(getattr, flatten(x), res)

rawDescription: Constructing function from lists within lists in Python


code:
import sys, IPython, colorama # <-- colorama must be "pip install"-ed

colorama.init()

def custom_exc(shell, etype, evalue, tb, tb_offset=None):
    pre = colorama.Fore.CYAN + colorama.Style.BRIGHT + "AutoImport: " + colorama.Style.NORMAL + colorama.Fore.WHITE
    if etype == NameError:
        shell.showtraceback((etype, evalue, tb), tb_offset) # Show the normal traceback
        import re
        try:
            # Get the name of the module you tried to import
            results = re.match("name '(.*)' is not defined", str(evalue))
            name = results.group(1)

            try:
                __import__(name)
            except:
                print(pre + "{} isn't a module".format(name))
                return

            # Import the module
            IPython.get_ipython().run_code("import {}".format(name))
            print(pre + "Imported referenced module \"{}\", will retry".format(name))
        except Exception as e:
            print(pre + "Attempted to import \"{}\" but an exception occured".format(name))

        try:
            # Run the failed line again
            res = IPython.get_ipython().run_cell(list(get_ipython().history_manager.get_range())[-1][-1])
        except Exception as e:
            print(pre + "Another exception occured while retrying")
            shell.showtraceback((type(e), e, None), None)
    else:
        shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset)

# Bind the function we created to IPython's exception handler
IPython.get_ipython().set_custom_exc((Exception,), custom_exc)

rawDescription: Make IPython Import What I Mean

description: Make IPython Import What I Mean


code:
## adapted from http://stackoverflow.com/questions/16824718/python-matplotlib-pyside-fast-timetrace-scrolling

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

N_SAMPLES = 1e6

def test_plot():
    time = np.arange(N_SAMPLES)*1e-3
    sample = np.random.randn(N_SAMPLES)

    plt = pg.PlotWidget(title="Use the slider to scroll and the spin-box to set the width")
    plt.addLegend()
    plt.plot(time, sample, name="Gaussian noise")
    q = ScrollingToolQT(plt)
    return q   # WARNING: it's important to return this object otherwise
            # python will delete the reference and the GUI will not respond!

class ScrollingToolQT(object):
    def __init__(self, fig):
        # Setup data range variables for scrolling
        self.fig = fig
        self.xmin, self.xmax = fig.plotItem.vb.childrenBounds()[0]
        self.step = 1 # axis units

        self.scale = 1e3 # conversion betweeen scrolling units and axis units

        # Retrive the QMainWindow used by current figure and add a toolbar
        # to host the new widgets
        self.win = QtGui.QMainWindow()
        self.win.show()
        self.win.resize(800,600)
        self.win.setCentralWidget(fig)
        self.toolbar = QtGui.QToolBar()
        self.win.addToolBar(QtCore.Qt.BottomToolBarArea, self.toolbar)

        # Create the slider and spinbox for x-axis scrolling in toolbar
        self.set_slider(self.toolbar)
        self.set_spinbox(self.toolbar)

        # Set the initial xlimits coherently with values in slider and spinbox
        self.set_xlim = self.fig.setXRange
        self.set_xlim(0, self.step)

    def set_slider(self, parent):
        # Slider only support integer ranges so use ms as base unit
        smin, smax = self.xmin*self.scale, self.xmax*self.scale

        self.slider = QtGui.QSlider(QtCore.Qt.Horizontal, parent=parent)
        self.slider.setTickPosition(QtGui.QSlider.TicksAbove)
        self.slider.setTickInterval((smax-smin)/10.)
        self.slider.setMinimum(smin)
        self.slider.setMaximum(smax-self.step*self.scale)
        self.slider.setSingleStep(self.step*self.scale/5.)
        self.slider.setPageStep(self.step*self.scale)
        self.slider.setValue(0)  # set the initial position
        self.slider.valueChanged.connect(self.xpos_changed)
        parent.addWidget(self.slider)

    def set_spinbox(self, parent):
        self.spinb = QtGui.QDoubleSpinBox(parent=parent)
        self.spinb.setDecimals(3)
        self.spinb.setRange(0.001, 3600.)
        self.spinb.setSuffix(" s")
        self.spinb.setValue(self.step)   # set the initial width
        self.spinb.valueChanged.connect(self.xwidth_changed)
        parent.addWidget(self.spinb)

    def xpos_changed(self, pos):
        #pprint("Position (in scroll units) %f\n" %pos)
        #        self.pos = pos/self.scale
        pos /= self.scale
        self.set_xlim(pos, pos + self.step, padding=0)

    def xwidth_changed(self, xwidth):
        #pprint("Width (axis units) %f\n" % step)
        if xwidth <= 0: return
        self.step = xwidth
        self.slider.setSingleStep(self.step*self.scale/5.)
        self.slider.setPageStep(self.step*self.scale)
        old_xlim = self.fig.plotItem.vb.viewRange()[0]
        self.xpos_changed(old_xlim[0] * self.scale)

if __name__ == "__main__":
    app = pg.mkQApp()
    q = test_plot()
    app.exec_()

rawDescription: pyqtgraph/chaco/guiqwt: Fast scrolling timetrace demo

description: Pyqtgraph/chaco/guiqwt: Fast scrolling timetrace demo


code:
objects = [{'group': 1, 'name': 'Joe'}, {'group': 2, 'name': 'Kirk'}, {'group': 1, 'name': 'Bob'}]
names = [i["name"] for i in objects]

rawDescription: generate list from values of certain field in list of objects

description: Generate list from values of certain field in list of objects


code:
mutated = False           # First, assume no mutation is present
for index in range(0, len(org), 3):
    if n[org[index:index+3]] != n[pat[index:index+3]]:
        mutated = True    # Set mutation flag to True
        break             # Abort the loop - no point in checking any further
if mutated:
    print("The patient's amino acid sequence is mutated.")
else:
    print("The patient's amino acid sequence is not mutated.")

rawDescription: How to split a string (input) and each section used as a dictionary value?

description: Split a string (input) and each section used as a dictionary value


code:
import struct
import collections

class MetaStruct(type):
    def __new__(cls, clsname, bases, dct):
        nt = collections.namedtuple(clsname, dct['fields'])
        def new(cls, record):
            return super(cls, cls).__new__(cls, *struct.unpack(dct['struct'], record))
        dct.update(__new__=new)
        return super(MetaStruct, cls).__new__(cls, clsname, (nt,), dct)

class Student(object):
    __metaclass__ = MetaStruct
    fields = 'name serialnum school gradelevel'
    struct = '<10sHHb'

record = 'raymond   \x32\x12\x08\x01\x08'
s = Student(record)

rawDescription: Creating a metaclass to unpack a struct into a namedtuple


code:
import re
data = "ATCGNNNATCGATNNNNNATCGANTCG"
spans = (g.span() for g in re.finditer('N+', data))
list(spans)

rawDescription: Finding ranges of specific character in a string


rawDescription: Parsing Tabbed Numbers on a Line

description: Parsing Tabbed Numbers on a Line


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0

ff = webdriver.Firefox()
ff.get("http://somedomain/url_that_delays_loading")
ff.find_element_by_xpath("//div[@class='searchbox']/input").send_keys("obama")

try:
    element = WebDriverWait(ff, 10).until(EC.presence_of_element_located((By.ID, "keywordSuggestion")))
finally:
    ff.find_element_by_xpath("//div[@class='searchbox']/input").send_keys(Keys.RETURN)
    ff.quit()

rawDescription: webdriver wait for ajax request in python

description: Webdriver wait for ajax request in python


code:
from lxml.html.clean import Cleaner

def clean_word_text(text):
    # The only thing I need Cleaner for is to clear out the contents of
    # <style>...</style> tags
    cleaner = Cleaner(style=True)
    return cleaner.clean_html(text)

rawDescription: Remove contents of <style>...</style> tags using html5lib or bleach


code:
import requests
import json
from bs4 import BeautifulSoup
import re

for i in range(0, 32):
    start_count = i * 10;
    jsonResponse = requests.get("http://store.steampowered.com/search/tabpaginated/render/"
                                "?query=&start="+str(start_count)+"&count=10&genre=37&tab=MostPlayed&cc=IN&l=english")
    data = json.loads(jsonResponse.text)
    soup = BeautifulSoup(data["results_html"], "html.parser")
    alltitles = soup.find_all(attrs={'class': re.compile('tab_item_name')})
    for title in alltitles:
        print(title.text)

rawDescription: Python beautiful soup showing same result for each page


code:
dis.dis(size)
dis.dis(size1)

rawDescription: Should I use elif if I have already returned from the function in a previous block?


rawDescription: rename elements in a column of a data frame using pandas

description: Rename elements in a column of a data frame using pandas


code:
class M1(models.Model):
    ...

    def save(self, *args, **kwargs):
        super(M1, self).save(*args, **kwargs) # Call the "real" save() method.

        m2 = M2(m1=self, m2code=self.m1code, m2title=self.m1title, m2description=self.m1description)
        m2.save()

rawDescription: Django automatically enter data in table 2 when entering data in a table 1


rawDescription: Splitting integers and string from a value


code:
link = 'http://stackoverflow.com'
print('{0}'.format(link))

rawDescription: Turn URL into HTML link

description: Turn URL into HTML link


code:
GEN_CREATED = 'GEN_CREATED'
GEN_RUNNING = 'GEN_RUNNING'
GEN_SUSPENDED = 'GEN_SUSPENDED'
GEN_CLOSED = 'GEN_CLOSED'

rawDescription: How do you model a state with three values?

description: Model a state with three values


code: sql = "INSERT INTO `projections_sample` (`id`,`month`, `revenue`) VALUES (%s,%s, %s) ON DUPLICATE KEY UPDATE month=IF(VALUES(month)IS NULL,month,VALUES(month)),revenue=IF(VALUES(revenue)IS NULL,revenue,VALUES(revenue))"

rawDescription: updating only null mysql fields using python

description: Updating only null mysql fields using python


code: sum(a[0] for a in my_list)

rawDescription: Summing 2D list columns where some elements are strings


code:
def validate_saturday(value):
    if not value.week.weekday == 5:
        raise ValidationError("Date should be a Saturday.")

rawDescription: What is the best practice to validate a Django DateField at the model level as particular day of the week?


code:
class PlayingField(object):
    # Class constants
    PLAYER = 'i'
    EMPTY = ' '
    EDGE = 'x'
    DEFAULT_SIZE = 6

    def __init__(self, size=DEFAULT_SIZE):
        X, EMPTY = self.EDGE, self.EMPTY
        self._size = size
        # build playing field
        self._field = [size*X] + (size-2)*[X + (size-2)*EMPTY + X] + [size*X]
        self._set_block(2, 2, self.PLAYER)  # Initialize player's position.

    def display(self):
        print(30*'\n')
        for row in self._field:
            print(row)

    def get_player_position(self):
        """Gets player's position."""
        for y, row in enumerate(self._field):
            for x, column in enumerate(row):
                if column == self.PLAYER:
                    return x, y
        else:
            raise ValueError("Couldn't determine player's location on field")

    def set_player_position(self, x, y):
        """Sets player's position."""
        block = self._get_block(x, y)
        if block == self.EMPTY:
            px, py = self.get_player_position()
            self._set_block(px, py, self.EMPTY)
            self._set_block(x, y, self.PLAYER)

    # Private methods
    def _get_block(self, x, y):
        """Gets a block at the given coordinates."""
        try:
            return self._field[y][x]
        except IndexError:
            return None

    def _set_block(self, x, y, block):
        """Sets a block at the given coordinates."""
        try:
            self._field[y] = self._field[y][:x] + block + self._field[y][x + 1:]
        except IndexError:
            pass

def main():
    """Entry point for the program."""
    field = PlayingField()
    cmd = ''
    while cmd.lower() not in ('quit', 'q'):
        field.display()
        cmd = input('Command: ').lower()
        px, py = field.get_player_position()
        if cmd == 'w':
            field.set_player_position(px, py - 1)
        elif cmd == 's':
            field.set_player_position(px, py + 1)
        elif cmd == 'a':
            field.set_player_position(px - 1, py)
        elif cmd == 'd':
            field.set_player_position(px + 1, py)
    print('Bye.')

if __name__ == '__main__':
    main()

rawDescription: Transforming a game to an object-oriented version


rawDescription: Is there a __getattribute__ to get a class or object from a python module?


code:
def gen_command_string(path, url):
    cmd = path + 'TortoiseProc.exe /command:ignore /path:\"%s\" /closeonend:0' % url
    return cmd

SVN_PATH = 'C:/Program Files/TortoiseSVN/bin'
HG_PATH = 'C:/Program Files/TortoiseHg/bin/'

cmd = gen_command_string(SVN_PATH, 'http://google.com')
call(cmd)

rawDescription: How can I get a python script to find the right Tortoise.exe if I have multiple Tortoise clients (Git, SVN) installed?

description: Get a python script to find the right Tortoise.exe if I have multiple Tortoise clients (Git, SVN) installed


code:
from django import forms

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super(ContactForm, self).clean()
        cc_myself = cleaned_data.get("cc_myself")
        subject = cleaned_data.get("subject")

        if cc_myself and subject:
            # Only do something if both fields are valid so far.
            if "help" not in subject:
                raise forms.ValidationError(
                    "Did not send for 'help' in the subject despite "
                    "CC'ing yourself."
                )

rawDescription: Django form checking

description: Django form checking


rawDescription: Illustrator Vector in Pygame/Python

description: Illustrator Vector in Pygame/Python


code:
df["cumulative_VAL"] = df.groupby(df.index.year)["VAL"].cumsum()
df

rawDescription: Computing cumulative values for each year of a dataframe separately


code:
def get_teacher_timetable(TeacherCode):

    timetable = []

    with open(TT_BASE_DIR + 'NTRTimeT.txt') as teacher_timetable:
        reader = csv.DictReader(teacher_timetable, fieldnames=("TeacherCode", "RoomCode", "DayNo", "PeriodNo", "RollClassCode", "ClassCode"))

    rows = iter([row for row in reader if row['TeacherCode'] == TeacherCode])
    row = next(rows,None)

    for day in range(1,11):
        day_schedule = []
        for period in range(1,11):
            if row and int(row['DayNo']) == day and int(row['PeriodNo']) == period:
                day_schedule.append(row)
                row = next(rows,None)
            else:
                new_row = {"TeacherCode":TeacherCode, "RoomCode":"", "DayNo":day, "PeriodNo":period, "RollClassCode":"", "ClassCode":""}
                day_schedule.append(new_row)
        timetable.append(day_schedule)

    return(timetable)

rawDescription: Move list element position, based on values


code:
from datetime import datetime, timedelta

delta = datetime.now() - timedelta(hours=3)
Model.objects.filter(date_time__gte=delta)

rawDescription: Get items for the last few hours

description: Get items for the last few hours


code:
import wx
from threading import Thread
from itertools import cycle

# Define notification event for thread completion
EVT_RESULT_ID = wx.NewId()
EVT_PROGRESSUPDATE_ID = wx.NewId()

def EVT_RESULT(win, func):
    """Define Result Event."""
    win.Connect(-1, -1, EVT_RESULT_ID, func)

class ResultEvent(wx.PyEvent):
    """Simple event to carry arbitrary result data."""
    def __init__(self, data):
        wx.PyEvent.__init__(self)
        self.SetEventType(EVT_RESULT_ID)
        self.data = data

def EVT_PROGRESSUPDATE(win, func):
    win.Connect(-1,-1,EVT_PROGRESSUPDATE_ID,func)

class ProgressUpdateEvent(wx.PyEvent):
    def __init__(self,data):
        wx.PyEvent.__init__(self)
        self.SetEventType(EVT_PROGRESSUPDATE_ID)
        self.data = data

# Thread class that shows progress
class ProgressThread(Thread):
    def __init__(self,notify_window):
        Thread.__init__(self)
        self._notify_window = notify_window
        self.chars = cycle(('|','/','-','\\'))

        self.tinyTimer = wx.Timer(notify_window)
        notify_window.Bind(wx.EVT_TIMER, self.updateTextCtrl, self.tinyTimer)
        self.tinyTimer.Start(100)

    def updateTextCtrl(self,event):
        wx.PostEvent(self._notify_window, ProgressUpdateEvent(next(self.chars)))

    def abort(self):
        self.tinyTimer.Stop()
        return

# Thread class that executes processing
class WorkerThread(Thread):
    """Worker Thread Class."""
    def __init__(self, notify_window):
        """Init Worker Thread Class."""
        Thread.__init__(self)
        self._notify_window = notify_window
        self.start()

    def run(self):
        """Run Worker Thread."""
        x = 0
        for i in range(100000000):
            x += i
        wx.PostEvent(self._notify_window, ResultEvent(x))

class MainFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'Thread Test')

        self.start_button = wx.Button(self, -1, 'Start', pos=(0,0))
        self.progress = wx.TextCtrl(self,-1,'',pos=(0,50))
        self.status = wx.StaticText(self, -1, '', pos=(0,100))
        self.Bind(wx.EVT_BUTTON, self.OnStart, self.start_button)

        # Set up event handlers
        EVT_RESULT(self,self.OnResult)
        EVT_PROGRESSUPDATE(self,self.OnProgressUpdate)

        # And indicate we don't have a worker thread yet
        self.worker = None

    def OnStart(self, event):
        """Start Computation."""
        # Trigger the worker thread unless it's already busy
        if not self.worker:
            self.status.SetLabel('Starting computation')
            self.worker = WorkerThread(self)
            self.p = ProgressThread(self)

    def OnResult(self, event):
        """Show Result status."""
        self.p.abort()
        self.status.SetLabel('Computation Result: %s' % event.data)
        self.worker = None

    def OnProgressUpdate(self,event):
        self.progress.ChangeValue(event.data)

class MainApp(wx.App):
    def OnInit(self):
        self.frame = MainFrame(None, -1)
        self.frame.Show(True)
        self.SetTopWindow(self.frame)
        return True

if __name__ == '__main__':
    app = MainApp(0)
    app.MainLoop()

rawDescription: Is there something like a wxpython TextCtrl flush method?


code:
prefix = "004"
prefix_len = len(prefix) + 1 # +1 for space
end_line_prefix = "819"
desired_value = "8041"
with open("input.txt", "r") as rfile:
    for line in rfile:
        if not line.startswith(prefix):
            continue  # if it doesnt start with 004, not interested

        val = line[prefix_len:len(line) - 1]  # at the end we also have new line
        if val != desired_value:
            continue  # if 004 doesnt have the value of our interest, skip

        while True:
            print("-> %s" % line)
            line = rfile.readline()
            if line.startswith(end_line_prefix):  # if we reached the line starting with 819, we print and then break
                print("-> %s" % line)
                break
rfile.close()

rawDescription: How to use Python to read a range of lines in a file

description: Use Python to read a range of lines in a file


code:
def on_key_down(self, e):
    if e.GetKeyCode() == wx.WXK_TAB:
        tab = ' ' * 4
        self.editor.WriteText(tab)
    else:
        e.Skip()

rawDescription: Python wxTextCtrl move text 4 spaces on tab key down?


code: matching = [string for string in words if string in op_text]

rawDescription: Search a list for a string and store it in Python


code: import html_form

rawDescription: How do you read an html template in a python script?

description: Read an html template in a python script


rawDescription: global name 'request' is not defined: overriding form_valid

description: Global name 'request' is not defined: overriding form_valid


code:
path = "/folder_a/folder_b/folder_c/folder_d"
import os
os.path.basename(path)

rawDescription: Python: Extract folder name from path

description: Python: Extract folder name from path


rawDescription: Extract items from array: between given values/conditions


code:
# Module imports
import math
import turtle
import random
from Suter_Andrew_shapesfinal import *

randint = random.randint

# Globals
MAX_S = 50

# List Definitions
shapes = [Rectangle, Triangle, Circle]
colors = ["blue", "green", "red", "purple", "pink", "yellow", "orange", "black", "white"]

# Main body
for i in range(MAX_S):
    s_choice = random.choice(shapes)
    c_choice = random.choice(colors)
    if s_choice == Rectangle:
        r = Rectangle(*([randint(-100, 100) for x in range(2)] + [randint(0, 100) for x in range(2)]))
        r.draw(c_choice, c_choice, random.randint(0, 10))
    elif s_choice == Triangle:
        t = Triangle(*[randint(-100, 100) for x in range(6)])
        t.draw(c_choice, c_choice, random.randint(0, 10))
    elif s_choice == Circle:
        c = Circle(*([randint(-100, 100) for x in range(2)] + [randint(0, 100)]))
        c.draw(c_choice, c_choice, random.randint(0, 10))

turtle.mainloop()

rawDescription: Random Geometry Assignment (Beginner Python)


rawDescription: Python mySQL Update, Working but not updating table


code:
password = ReadOnlyPasswordHashField(label= ("Password"),
        help_text= ("Raw passwords are not stored, so there is no way to see "
                    "this user's password, but you can change the password "
                    "using this form."))

rawDescription: EDit Django admin Form so that only staff users can change users password


code:
offset_x = 10      # Distance from left edge.
offset_y = 10      # Distance from top.
cell_size = 10     # Height and width of checkerboard squares.

for i in range(8):             # Note that i ranges from 0 through 7, inclusive.
    for j in range(8):           # So does j.
        if (i + j) % 2 == 0:       # The top left square is white.
            color = 'white'
        else:
            color = 'black'
        canvas.setFill(color)
        canvas.drawRect(offset_x + i * cell_size, offset_y + j * cell_size,
                        cell_size, cell_size)

rawDescription: Drawing a checkerboard in Python

description: Drawing a checkerboard in Python


code:
m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
m.group(0)       # The entire match
m.group(1)       # The first parenthesized subgroup.
m.group(2)       # The second parenthesized subgroup.
m.group(1, 2)    # Multiple arguments give us a tuple.

rawDescription: what does the 1 in match.group(1) mean?

description: What does the 1 in match.group(1) mean


code:
import pymongo
client = pymongo.MongoClient()
db = client.test
isinstance(db, pymongo.database.Database)

rawDescription: How to get class of pymongo database suitable for isinstance()?

description: Get class of pymongo database suitable for isinstance()


code:
def place(a):
    try:
        b = int(a)
    except ValueError:
        b = 0

    if (b != 0):
        if b > 0:
            print("Turned right.")
        else:
            print("Turned left.")
    elif (type(a) is str) and ((a == 'r') | (a == 'l')):
        if a == 'r':
            print("Turned right.")
        else:
            print("Turned Left")
    else:
        print("Invalid")
        raise TypeError("Nothing to do")

rawDescription: How can i make a variable recive both a string and a int?

description: Make a variable recive both a string and a int


code: #!/usr/bin/env python

rawDescription: I run Python in TextWrangler and it works fine but on Mac Terminal it doesn't


code:
#CLIENT
urlReq = urllib2.Request(url)
urlReq.add_header('Accept-Encoding', 'gzip')
urlConn = urllib2.urlopen(urlReq)
return zlib.decompress(urlConn.read(), 16+zlib.MAX_WBITS)

rawDescription: Gunzipping Contents of a URL - Python

description: Gunzipping Contents of a URL - Python


code:
class sth(models.Model):
    somefield = models.CharField(max_length = 20, null = False, blank = False)

rawDescription: how to establish in models file that a django model should be defined as NOT NULL?

description: Establish in models file that a django model should be defined as NOT NULL


code:
def createTestProduct(product_group="VG", opno=None):
    if opno is None:
        opno = "MyProduct%s" % Product.objects.count()
    ...

rawDescription: Django objects.count() in default method parameter returns 0


code:
CONST = 1.
lst1 = [1.2, 2.4, 3.1] #sorted and same length as lst1
lst2 = [[2.0, 0.9], [3.1, 1.5], [1.0, 3.0], [2.5, 2.0]]

def gen_generator(lst1):
    #Create iterators to form consecutive pairs
    it1_1, it1_2 = iter(lst1), islice(lst1+[float('inf')], 1, None)
    #Create iterator over items to insert and initialize p
    gen_generator.it2 = iter(sorted(lst2, key=itemgetter(1)))
    gen_generator.p=next(gen_generator.it2)
    for t1, t2 in zip(it1_1, it1_2):
        #Calculate the mid point of the pair t1, t2
        sup = (t1+t2)/2 if t2 != float('inf') else float('inf')
        #Create a generator for each item in lst1
        def generator():
            #All the previously inserted items have disappeared
            #So yield any p such that p[1] < sup
            while gen_generator.p is not None and gen_generator.p[1] < sup:
                yield gen_generator.p[0]
                #Move to next or None
                gen_generator.p = next(gen_generator.it2, None)
            #Add the constant
            yield CONST
        yield generator

res = [[sum(gen()), t] for gen, t in zip(gen_generator(lst1), lst1)]
return res

rawDescription: Projecting python list onto existing values (with generator of generators)


code:
df = sqlContext.createDataFrame(
    [("Bob", 5), ("Alice", 6), ("Chuck", 4)], ("name", "age"))

df.where("name in ('Bob', 'Alice')")
df.where((df.name == "Bob") | (df.name == "Alice"))

rawDescription: Does spark dataframe have a "row name" for each row like pandas?


code:
d = {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
start = 1
end = 3
sum(d[i] for i in range(start, end + 1) if i in d)

rawDescription: How to add specific values together in a dictionary?

description: Add specific values together in a dictionary


code:
def _dict_to_xml(dictionary):
    returnlist = []
    for key in dictionary:
        if isinstance(dictionary[key],dict):
            returnlist.append(r'<node name="{name}">'.format(name=key))
            returnlist.append(_dict_to_xml(dictionary[key]))
            returnlist.append(r'</node>')
        else:
            returnlist.append(r'<order>{key}</order>'.format(key=key))
            returnlist.append(r'<string>{value}</string>'.format(value = dictionary[key]))
    return '\n'.join(returnlist)

def dict_to_xml(dictionary):
    return '<?xml version="1.0"?>\n'+_dict_to_xml(dictionary)+'</xml>'

rawDescription: Converting a dictionary to XML

description: Converting a dictionary to XML


code:
class A:
    def __init__(self):
        if hasattr(self, '_initialized'):
            return
        print('A')
        self._initialized = true

rawDescription: Python - How to avoid calling the grandparent constructor (multiple inheritance)


code:
def extract_fns(filename):
    with open(filename) as f:
        lines = f.readlines()
        return [line.split(' ', 1)[1].split('(')[0] for line in lines
            if line.strip().startswith('def')]

rawDescription: Get a list of the names of all functions in a Python module in the order they appear in the file?


code:
class Nested(EmbeddedDocument):
    a = StringField(unique=True)
    b = StringField()

class Outer(Document):
    inner = EmbeddedDocumentField(Nested)
    c = StringField()

o = Outer()
o.c = 'abc'
o.inner = Nested(a='a', b='b')
o.save()
o2 = Outer()
o2.c = 'abc'
o2.inner = Nested(a='a', b='B')
o2.save()

rawDescription: mongoengine - index on a key inside of an embedded document?

description: Mongoengine - index on a key inside of an embedded document


code:
import requests

filePath = '/mnt/Images/test.png'
searchUrl = 'http://www.google.hr/searchbyimage/upload'
multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': ''}
response = requests.post(searchUrl, files=multipart, allow_redirects=False)
fetchUrl = response.headers['Location']
webbrowser.open(fetchUrl)

rawDescription: Google reverse image search using POST request


code:
import json

mydict = {'a':1, 'b':2, 'c':3}

data = json.load(open('existing.json'))
data.update(mydict)
json.dump(data, open('recent.json', "w"))

rawDescription: Copy JSON file then append it and a dictionary to another JSON file


code:
unique_elements = set()

for filename in ['file1', 'file2']:
    with open(filename, 'r') as f:
        for l in f.readlines():
            unique_elements.add(int(l.strip()))

sorted_list = list(unique_elements)
sorted_list.sort()

with open('output_file', 'w') as f:
    for number in sorted_list:
        f.write('{}\n'.format(number))

rawDescription: Ordered file combination with python

description: Ordered file combination with python


code:
[e for e in test if e.startswith('x')]
any(e.startswith('x') for e in test)

rawDescription: Subseting list in python using regular expression


code:
# Create the initial circle
circle = Circle([2,2], 2);

# Get the path and the affine transformation
path = circle.get_path()
transform = circle.get_transform()

# Now apply the transform to the path
newpath = transform.transform_path(path)

# Now you can use this
polygon = matpatches.PathPatch(newpath)
patches.append(polygon)

rawDescription: get_path() return of a Circle from matplotlib.patches

description: Get_path() return of a Circle from matplotlib.patches


code:
def scor_func(score):
    name = input("Please enter your name: ")
    entry = (name, score)

    scorefile = "Triviascores.bat"
    if os.path.exists(scorefile):
        with open(scorefile, 'rb') as sf:
            scores = pickle.load(sf)
    else:
        scores = []

    scores.append(entry)

    with open(scoresfile, "wb") as sf:
        pickle.dump(scores, sf)

    return scores

rawDescription: How to change and re-pickle a value in python

description: Change and re-pickle a value in python


code:
chars = 'TGC-'
nums = {}

for char in chars:
    s = df["MUT"]
    A = s.str.contains("A:" + char)
    num = A.value_counts(sort=True)
    nums[char] = num

ATnum = nums['T']
AGnum = nums['G']
# ...etc

rawDescription: counting T/F values for several conditions

description: Counting T/F values for several conditions


code:
#used to determine number of precise digits in a string
def get_precision(str_value):
    vals =  str_value.split('.')
    if (vals[0] == '0'):
        return len(vals[1])
    else:
        return len(str_value) -1

# maintain same precision of incoming string on output text
class ExpDecorator(CurrencyDecorator):
    def get_text(self):
        text = self.decoratedCurrency.get_text()
        return ('{:.' + str(get_precision(text)-1) + 'e}').format(float(text))

rawDescription: Python Scientific Notation precision normalizing


code:
t1 = Topic.objects.create(title='visible1', visible=True)
t2 = Topic.objects.create(title='visible2', visible=True)
t3 = Topic.objects.create(title='invisible1', visible=False)
t4 = Topic.objects.create(title='invisible2', visible=False)
tl1 = TopicLabel.objects.create(name='1')
tl2 = TopicLabel.objects.create(name='2')
tl3 = TopicLabel.objects.create(name='3')
TopicLabelConnection.objects.create(topicId=t1, labelId=tl1)
TopicLabelConnection.objects.create(topicId=t2, labelId=tl2)
TopicLabelConnection.objects.create(topicId=t3, labelId=tl3)
TopicLabelConnection.objects.create(topicId=t4, labelId=tl3)
TopicLabel.objects.filter(connection_label__topicId__visible=True)

rawDescription: Django: Query with EXISTS or a subquery

description: Django: Query with EXISTS or a subquery


code:
import os
os.system(mycommand)

rawDescription: Shell scripting in Python: calling programs that use curses, etc


code:
def move(move):
    print(move,"inside move")

def undomove(move):
    print (move,"inside undomove")
    this_mod =__import__(__name__)
    this_mod.move(move)

if __name__ == '__main__':
    move(1)
    undomove(2)

rawDescription: Parameter and Function with the same name


code:
import datetime
datetime.date(2014, 2, 22) == datetime.datetime.now().date()

rawDescription: python datetime and date comparison

description: Python datetime and date comparison


code:
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

rawDescription: How can I include the template_dir in django settings

description: Include the template_dir in django settings


code:
from numpy.lib.stride_tricks import as_strided

def subsequences(arr, m):
    n = arr.size - m + 1
    s = arr.itemsize
    return as_strided(arr, shape=(m,n), strides=(s,s))

rawDescription: Get all subsequences of a numpy array

description: Get all subsequences of a numpy array


code:
import kivy
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.label import Label
import logging
import thread
import time

def my_thread(log):

    for i in range(2**20):
        time.sleep(1)
        log.info("WOO %s", i)

class MyLabelHandler(logging.Handler):

    def __init__(self, label, level=logging.NOTSET):
        logging.Handler.__init__(self, level=level)
        self.label = label

    def emit(self, record):
        "using the Clock module for thread safety with kivy's main loop"
        def f(dt=None):
            self.label.text = self.format(record) #"use += to append..."
        Clock.schedule_once(f)

class MyApp(App):
    def build(self):
        label = Label(text="showing the log here")

        log = logging.getLogger("my.logger")
        log.level = logging.DEBUG
        log.addHandler(MyLabelHandler(label, logging.DEBUG))

        thread.start_new(my_thread, (log,))

        return label

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

rawDescription: How to redirect Python's logging output to Kivy label?

description: Redirect Python's logging output to Kivy label


code:
import nltk
st2 = nltk.data.load('tokenizers/punkt/english.pickle')
sent = 'A problem. She said: "I don\'t know about it."'
st2.tokenize(sent, realign_boundaries=True)

rawDescription: Why does NLTK mis-tokenize quote at end of sentence?


code:
def prev_portrait(self):
    if self.get_prev_sibling():
        return self.get_prev_sibling().url
    else:
        return self.get_siblings().last().url

def next_portrait(self):
    if self.get_next_sibling():
        return self.get_next_sibling().url
    else:
        return self.get_siblings().first().url

rawDescription: Wagtail: Get previous or next sibling

description: Wagtail: Get previous or next sibling


code:
markup = 'I linked to example.com'
soup = BeautifulSoup(markup)

tag = soup.a
tag.string = "New link text."
tag
# New link text.

rawDescription: How to set value in with Beautiful Soup in some HTML element if I know id of that element or class?

description: Set value in with Beautiful Soup in some HTML element if I know id of that element or class


code:
from datetime import date
from dateutil.relativedelta import relativedelta

starts_at = date(2010, 1, 1)
today = date(2010, 2, 1)  # as an example
diff = relativedelta(today, starts_at)

if diff.days == 0:  # there must be no days difference between two dates
    if diff.months % 12 == 0:  # this is a year interval
        do_something('annual')
    elif diff.months % 6 == 0:  # this is a six month interval
        do_something('bi_annual')
    elif diff.months % 3 == 0:  # this is a three month interval
        do_something('quarter')
    else:  # this is a month interval
        do_something('month')

rawDescription: Calculate if today's date is a recurring date for a given date


code:
nodes = g.node

def has_top2(n):
    return 'metric' in nodes[n] and nodes[n]['metric'] == 'Top2'

def has_dallas(n):
    return 'city' in nodes[n] and nodes[n]['city'] == 'Dallas'

[(n, u) for n, u in g.edges()
    if (has_top2(n) and has_dallas(u))
    or (has_top2(u) and has_dallas(n))
]

rawDescription: Filter NetworkX graph to list all edges coming from a nodes with specific attributes


code:
import pygame, sys
from pygame.locals import*

pygame.init()
FPS = 30
fpsClock = pygame.time.Clock()

DISPLAYSURF = pygame.display.set_mode((1000, 750))
BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
pygame.display.set_caption('Game')

while True:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEMOTION:
            "do something"

        else:
            posx, posy = pygame.mouse.get_pos()
            if event.type == pygame.MOUSEBUTTONUP:
                if posx == 500 and posy == 500:
                    DISPLAYSURF.fill((40, 40, 40))
                    pygame.draw.rect(DISPLAYSURF, (40, 40, 40), (posx, posy, 50, 20))

    pygame.display.update()

rawDescription: pygame.display.update() doesn't work in a loop

description: Pygame.display.update() doesn't work in a loop


rawDescription: Changing the origin of a plot

description: Changing the origin of a plot


code:
from django.contrib import admin
from django.contrib.admin.util import flatten_fieldsets

class CustomAdmin(admin.ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        if request.user.is_superuser:
            return self.readonly_fields

        if self.declared_fieldsets:
            return flatten_fieldsets(self.declared_fieldsets)
        else:
            return list(set(
                [field.name for field in self.opts.local_fields] +
                [field.name for field in self.opts.local_many_to_many]
            ))

rawDescription: Django admin - make all fields readonly

description: Django admin - make all fields readonly


code:
m = np.random.normal(0, 1, size=(500, 2))
m.shape
m.mean(axis=0)
m.std(axis=0)

rawDescription: creating a 2 column table in python

description: Creating a 2 column table in python


code:
input = '[AAA] Grim'
n = len(input.split(' ')[0]) - 2
s = input[n+2:]
a = [''.join(x)+s for x in itertools.product(string.ascii_lowercase, repeat=n)]

rawDescription: How to generate a range of strings from aa... to zz

description: Generate a range of strings from aa... to zz


code: p.sub(lambda m: threeLetterDict[m.group(0)], "abcdefghi")

rawDescription: fix length re.sub with dictionary

description: Fix length re.sub with dictionary


code:
from itertools import chain
addons = list(chain.from_iterable(col.addons for col in collections))

rawDescription: Python list comprehension for joining lists (flattened)


code:
import matplotlib.pyplot as plt

a= [1,2,3,4,5,6,7,8,9]
b= [5,3,4,5,3,2,1,2,3]
plt.hist(a,9, weights=b)
plt.show()

rawDescription: Histogram from data which is already binned, I have bins and frequency values


code:
import importlib

current_package = importlib.import_module(__package__)

# getting the class I want
cls = getattr(current_package, myclass)

rawDescription: Access a class of current package

description: Access a class of current package


code:
from django.db.models import Count

Tag.objects.annotate(action_count=Count('action'))

rawDescription: Add count value to set

description: Add count value to set


code:
string = '3dc8uo8cc33a v8c08oizl6ga'
" ".join("".join(s[2::3]) for s in string.split())

rawDescription: Python: remove characters from a string?

description: Python: remove characters from a string


code:
import py_compile

py_compile.compile('file.py', cfile='/path/where-you-want-to-save/file.py')

rawDescription: Choose location of compiled file

description: Choose location of compiled file


code:
import requests

pagelink = "http://www.example.com"
page = requests.get(pagelink)

with open('/path/to/file/example.html', "w") as file:
    file.write(page.text)

rawDescription: Python script to save webpage and rename it while saving (save as - command)


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

def main():
    np.random.seed(1977)
    numvars, numdata = 4, 10
    data = 10 * np.random.random((numvars, numdata))
    fig = scatterplot_matrix(data, ['mpg', 'disp', 'drat', 'wt'],
            linestyle='none', marker='o', color='black', mfc='none')
    fig.suptitle('Simple Scatterplot Matrix')
    plt.show()

def scatterplot_matrix(data, names, **kwargs):
    """Plots a scatterplot matrix of subplots.  Each row of "data" is plotted
    against other rows, resulting in a nrows by nrows grid of subplots with the
    diagonal subplots labeled with "names".  Additional keyword arguments are
    passed on to matplotlib's "plot" command. Returns the matplotlib figure
    object containg the subplot grid."""
    numvars, numdata = data.shape
    fig, axes = plt.subplots(nrows=numvars, ncols=numvars, figsize=(8,8))
    fig.subplots_adjust(hspace=0.05, wspace=0.05)

    for ax in axes.flat:
        # Hide all ticks and labels
        ax.xaxis.set_visible(False)
        ax.yaxis.set_visible(False)

        # Set up ticks only on one side for the "edge" subplots...
        if ax.is_first_col():
            ax.yaxis.set_ticks_position('left')
        if ax.is_last_col():
            ax.yaxis.set_ticks_position('right')
        if ax.is_first_row():
            ax.xaxis.set_ticks_position('top')
        if ax.is_last_row():
            ax.xaxis.set_ticks_position('bottom')

    # Plot the data.
    for i, j in zip(*np.triu_indices_from(axes, k=1)):
        for x, y in [(i,j), (j,i)]:
            axes[x,y].plot(data[x], data[y], **kwargs)

    # Label the diagonal subplots...
    for i, label in enumerate(names):
        axes[i,i].annotate(label, (0.5, 0.5), xycoords='axes fraction',
                ha='center', va='center')

    # Turn on the proper x or y axes ticks.
    for i, j in zip(range(numvars), itertools.cycle((-1, 0))):
        axes[j,i].xaxis.set_visible(True)
        axes[i,j].yaxis.set_visible(True)

    return fig

main()

rawDescription: Is there a function to make scatterplot matrices in matplotlib?


rawDescription: Convert unicode to python float but keep the decimal places


code:
s = Series(pd.to_timedelta(np.arange(5),unit='s'))
s
s.dtype == 'timedelta64[ns]'
s.dtype == 'm8[ns]'
s.to_frame().select_dtypes(include=['timedelta'])
from pandas.core.common import is_timedelta64_dtype
is_timedelta64_dtype(s.dtype)

rawDescription: Check if series is timedelta

description: Check if series is timedelta


code:
import string
import random

def id_generator(size=8, chars=string.digits):
    return ''.join(random.choice(chars) for _ in xrange(size))

random_numbers_string = '\n'.join(id_generator() for _ in xrange(100))

with open('file.txt', 'w') as f:
    f.write(random_numbers_string)

rawDescription: Random number generator in Python on Linux


code:
from commands.shVersionCmd import shVersionCmd
from commands.shVRFCmd import shVRFCmd

# An explicit list of allowed commands to prevent malicious activity.
commands = ['shVersionCmd', 'shVRFCmd']

def CommandFactory(commandnode):
    cmd = commandnode.attrib['name']
    if cmd in commands:
        fn = globals()[cmd]
        fn(commandnode)

rawDescription: there must be a better way to do this

description: There must be a better way to do this


code:
from abc import abstractmethod, ABCMeta
class A:
    __metaclass__=ABCMeta
    @abstractmethod
    def a(self):
        pass
class B:
    def a(self):
        return 12
class C(B,A):
    pass
c = C()
c
class D:
    pass
class E(D, A):
    pass
e = E()

rawDescription: Declare required mixin by abstractmethod in Python?


code:
def main():
    shape = input("Enter shape to draw (q to quit): ").lower()
    while shape != 'triangle' and shape != 'square' and shape != 'q':
            print("Unknown shape. Please try again")
            shape = input("Enter shape to draw (q to quit): ").lower()
    if shape == "q":
        print("Goodbye")
        return
    get_valid_size()

def get_valid_size():
    size = int(input("Enter size: "))
    while size < 1:
        print("Value must be at least 1")
        size = int(input("Enter size: "))
main()

rawDescription: How to stop my function?

description: Stop my function


code:
f = open("events.csv", "r")

carets_per_record = 33

final_file = []
temp_file  = []
temp_str   = ''
temp_cnt   = 0

building   = False

for i, line in enumerate(f):

    # If there are no carets on the line, we are building a string
    if line.count('^') == 0:
        building = True

    # If we are not building a string, then set temp_str equal to the line
    if building is False:
        temp_str = line
    else:
        temp_str = temp_str + " " + line

    # Count the number of carets on the line
    temp_cnt = temp_str.count('^')

    # If we do not have the proper number of carets, then we are building
    if temp_cnt < carets_per_record:
        building = True

    # If we do have the proper number of carets, then we are finished
    # and we can push this line to the list
    elif temp_cnt == carets_per_record:
        building = False
        temp_file.append(temp_str)

# Strip embedded newline characters from the temp file
for i, item in enumerate(temp_file):
    final_file.append(temp_file[i].replace('\n', ''))

# Write the final_file list out to a csv final_file
g = open("new_events.csv", "wb")

# Write the lines back to the file
for item in enumerate(final_file):
    # item is a tuple, so we get the content part and append a new line
     g.write(item[1] + '\n')

# Close the files we were working with
f.close()
g.close()

rawDescription: Remove nested newline characters in delimited file?