code:
def add_source_for_attribute(self, attr, source):
    """Adds information about a constant source for an attribute.
    """
    for cdef in self.getmro():
        if attr in cdef.attrs:
            # the Attribute() exists already for this class (or a parent)
            attrdef = cdef.attrs[attr]
            s_prev_value = attrdef.s_value
            attrdef.add_constant_source(self, source)
            # we should reflow from all the reader's position,
            # but as an optimization we try to see if the attribute
            # has really been generalized
            if attrdef.s_value != s_prev_value:
                attrdef.mutated(cdef) # reflow from all read positions
            return
    else:
        # remember the source in self.attr_sources
        sources = self.attr_sources.setdefault(attr, [])
        sources.append(source)
        # register the source in any Attribute found in subclasses,
        # to restore invariant (III)
        # NB. add_constant_source() may discover new subdefs but the
        #     right thing will happen to them because self.attr_sources
        #     was already updated
        if not source.instance_level:
            for subdef in self.getallsubdefs():
                if attr in subdef.attrs:
                    attrdef = subdef.attrs[attr]
                    s_prev_value = attrdef.s_value
                    attrdef.add_constant_source(self, source)
                    if attrdef.s_value != s_prev_value:
                        attrdef.mutated(subdef) # reflow from all read positions

rawDescription: Pythonic ways to use 'else' in a for loop


code:
def spiral(m):
    length = len(m[0])
    last = length - 1
    mid = length // 2
    spirals_remaining = mid

    if length % 2 == 1:
        yield m[mid][mid]
        box = [(mid-1, mid-1), (mid-1, mid+1), (mid+1, mid+1), (mid+1, mid-1)]
    else:
        box = [(mid-1, mid-1), (mid-1, mid), (mid, mid), (mid, mid-1)]

    while spirals_remaining > 0:
        # yield spiral values clockwise from top left corner
        top = m[box[0][0]][slice(box[0][1], box[1][1])]
        for x in top:
            yield x
        right = [m[i][box[1][1]] for i in range(box[1][0], box[2][0])]
        for x in right:
            yield x
        bottom = m[box[2][0]][slice(box[2][1], box[3][1], -1)]
        for x in bottom:
            yield x
        left = [m[i][box[3][1]] for i in range(box[3][0], box[0][0], -1)]
        for x in left:
            yield x

        # update bounding box for next spiral
        box[0] = box[0][0] - 1, box[0][1] - 1
        box[1] = box[1][0] - 1, box[1][1] + 1
        box[2] = box[2][0] + 1, box[2][1] + 1
        box[3] = box[3][0] + 1, box[3][1] - 1
        spirals_remaining -= 1

rawDescription: Slicing through a grid in a spiral motion, returning xMin, xMax, yMin, yMax for each slice


code:
header('rr', 'Test table')
line('First', 'Second')
line(12, 27)
line(31, 9)
footer()

rawDescription: making a table in python

description: Making a table in python


code:
def weekdays_between(s, e):
    return [n % 7 for n in range(s, e + (1 if e > s else 8))]

weekdays_between(2, 4)
weekdays_between(5, 1)

rawDescription: How can I get all days between two days?

description: Get all days between two days


code:
import datetime as DT
import pandas as pd
import pandas.io.data as pdata
eventday_idxs = pd.to_datetime(pd.read_table('data', header=None)[0])
aap1_10_years = pdata.get_data_yahoo(
    'AAPL',
    start=DT.datetime(2004, 12, 10),
    end=DT.datetime(2014, 12, 10))

# mark each event day with a 1
aap1_10_years.loc[eventday_idxs, 'event'] = 1
# use cumsum to assign an event number to each event range
aap1_10_years['event'] = aap1_10_years['event'].fillna(0).cumsum()

mask = aap1_10_years['event'] > 0
aap1_10_years.loc[mask].groupby(['event'])['High'].apply(do_calculations)

rawDescription: How can i do calculations on subsets , Panda's way, without looping

description: Do calculations on subsets , Panda's way, without looping


code: return result[0] if result else None

rawDescription: Unpack a tuple with a single element or return None if tuple is None


code: queryset = super(EventArchiveAdmin, self).queryset(request)

rawDescription: Why can't I register multiple Django ModelAdmin with same Model?


rawDescription: extract a str contained between 2 str

description: Extract a str contained between 2 str


rawDescription: Inverting Rows of multiple columns to vertically concatenated columns


code:
import tkinter as tk
from tkinter import *
from tkinter import ttk

class DIS(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.iconbitmap(self, default="")
        tk.Tk.wm_title(self, "program")
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        container.grid_rowconfigure(0, weight = 1)
        container.grid_columnconfigure(0, weight = 1)

        self.frames = {}

        for F in (startPage, contactQues):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row = 0, column = 0, sticky = "nsew")
            self.show_frame(startPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        frame.postupdate()

class startPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        button2 = ttk.Button(self, text = "Here's a Button",
                    command=lambda: controller.show_frame(contactQues))
        button2.pack()

    def postupdate(self):
        pass

class contactQues(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        self.entry = Entry(self)
        self.entry.pack()

    def postupdate(self):
        self.entry.focus()

app = DIS()
app.mainloop()

rawDescription: Tkinter focus_set and focus_force not working as expected


rawDescription: 'b' character added when using numpy loadtxt


code:
# eventInstanceMethods() bear many details about click/key/time/.widget()
#       <event>.char        on-{ <KeyPress> | <KeyRelease> }
#              .keysym      on-{ <KeyPress> | <KeyRelease> }
#              .keysym_num  on-{ <KeyPress> | <KeyRelease> }
#              .num         on-{ <Mouse-1>  | <Mouse-2> | ... } ? 4,5 == <MouseWheel>
#              .height      on-{ <Configure> }
#              .width       on-{ <Configure> }
#              .serial      <-- system-assigned Integer
#              .time        <-- system-assigned Integer ( .inc each msec )
#              .widget      <-- system-assigned <widget>-instance
#              .x           <-- system-assigned <Event>-in-<widget>-mouse-location.x
#              .y           <-- system-assigned <Event>-in-<widget>-mouse-location.y
#              .x_root      <-- system-assigned <Event>-on-<Screen>-mouse-location.x
#              .y_root      <-- system-assigned <Event>-on-<Screen>-mouse-location.y

rawDescription: How can I program two simultaneous key press events in tkinter to move a canvas item diagonally using a dictionary of keypress events?

description: Program two simultaneous key press events in tkinter to move a canvas item diagonally using a dictionary of keypress events


code: alist, blist, clist, dlist, elist = [[]] * 5

rawDescription: Python - Initializing Multiple Lists/Line


rawDescription: Building a string and running it in terminal python


code:
import re

ls=[]

with open('results.txt') as f:
    for line in f:
        if "saleAmount" in line:
            ls.append(line.strip('\n'))

for num in range(len(ls)):
    for amnt in re.findall('\d+',ls[num]):
        if int(amnt) < 1000:
            print(amnt)

rawDescription: parse a file for a line with specific text, then logic to determine next steps

description: Parse a file for a line with specific text, then logic to determine next steps


code:
lister = [int(i) for i in a ]
return sum(lister) % 10 == 0 or sum(lister) == 0

rawDescription: Python efficiency query

description: Python efficiency query


rawDescription: References and copies in python

description: References and copies in python


code:
from defusedxml.ElementTree import parse
et = parse(xmlfile)

rawDescription: How to prevent "billion laughs" DoS attack in Python's xlrd?

description: Prevent "billion laughs" DoS attack in Python's xlrd


code: import json

rawDescription: django serialize foreign key objects

description: Django serialize foreign key objects


rawDescription: Is it possible to add several columns at once to a pandas DataFrame?


code:
a = ['AA', 'BB', 'C', 'D']
outList = a[:] # make a copy of list values
outList[0] += outputList.pop(1)

rawDescription: Joining Subsequent List Elements - Python


rawDescription: Python: Creating list of subarrays

description: Python: Creating list of subarrays


rawDescription: Inserting a string into a list without getting split into characters


code:
def cached_resource(cache_attribute):
  def decorator_factory(method_to_cache):
    def decorator(self, *args, **kwargs):
        method_name = method_to_cache.__name__
        cache = getattr(self, cache_attribute)
        try:
            return cache[method_name]
        except KeyError:
            result = cache[method_name] = method_to_cache(self, *args, **kwargs)
            return result

    return decorator
  return decorator_factory

class Profile(BeautifulSoup):
    def __init__(self, page_source):
        super().__init__(page_source)
        self._cache = {}

    @cached_resource('_cache')
    def username(self):
        return self.title.split(':')[0]

rawDescription: Is it okay for decorators to access private members of a class?


code:
example = (dao.query(students, colleges)
    .join(colleges, students.collegeID == colleges.collegeID)
    ).all()

for student, college in example:
    print(student, college)

rawDescription: Should I specify all key names when I join tables with Sqlalchemy


code:
import sqlite3

new_db = sqlite3.connect(':memory:') # create a memory database

old_db = sqlite3.connect('test.db')

query = "".join(line for line in old_db.iterdump())

# Dump old database in the new one.
new_db.executescript(query)

rawDescription: How to copy a sqlite table from a disk database to a memory database in python?

description: Copy a sqlite table from a disk database to a memory database in python


code:
def remove_cols():
    remove_list = []

    with open('remove_list.csv') as f:
        for line in f:
            remove_list.append(line.strip())

    colIndexesToKeep = []

    with open('orig.csv') as origFile:
        with open('filtered.csv', 'w') as filteredFile:
            for line in origFile:
                if not colIndexesToKeep:
                    for ix, name in enumerate(line.split(',')):
                        if name.strip() not in remove_list:
                            colIndexesToKeep.append(ix)

                filteredLine = [val.strip() for ix, val in
                  enumerate(line.split(',')) if ix in colIndexesToKeep]
                filteredFile.write(','.join(filteredLine))
                filteredFile.write('\n')

rawDescription: How could I delete certain columns then write wanted columns into csv python


code: list((uuid.uuid4() for  _ in range(2)))

rawDescription: Call GUID function more than once in print formatting in python


code:
import re
myre = re.compile(r"\w{4,}")
myre.findall('Lorem, ipsum! dolör sit? amet...')

rawDescription: List of all words matching regular expression


code:
import pandas as pd
d = pd.read_csv("30735293.csv")
d

rawDescription: csv parsing and manipulation using python

description: Csv parsing and manipulation using python


code:
class Random_Integer(object):
    """Welcome to the guessing game! You have unlimited attempts
    to guess the 3 random numbers, thats pretty much it.
    """
    def __init__(self):
        self.code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))

rawDescription: Trouble printing a variable

description: Trouble printing a variable


rawDescription: Collecting like term of an expression in Sympy


rawDescription: Short (and useful) python snippets

description: Short (and useful) python snippets


code:
def HPformat(str):
    if len(str)==5:
        newstr=str[0]+str[1] + ','+ str[2]  + 'K'
        return newstr
    elif len(str)==4:
        newstr=str[0]+','+ str[1] + 'K'
        return newstr

rawDescription: Python comma and divide an integer

description: Python comma and divide an integer


code:
df['Year'] = df['Date'].dt.year
df['Month'] = df['Date'].dt.month
df['Day'] = df['Date'].dt.day

rawDescription: Which is the fastest way to extract day, month and year from a given date?


code: logger.info("Some message \n %s" % codeinfo())

rawDescription: Python - get static information

description: Python - get static information


code:
ttext = 'hello my name is brian'
test(l,ttext)
ttext = 'hello how are you?'
test(l,ttext)

rawDescription: find only one word of multiple lists in a string

description: Find only one word of multiple lists in a string


rawDescription: Selecting Subset of Pandas DataFrame

description: Selecting Subset of Pandas DataFrame


rawDescription: pandas replace zeros with previous non zero value

description: Pandas replace zeros with previous non zero value


code:
def myfunc():
    return dict(caption='Me', source='http://example.com/img.png')

rawDescription: Can I include partial view in Web2Py, passing specific variables into it?

description: Include partial view in Web2Py, passing specific variables into it


code:
class Test(object):

    def a(self):
        p = {"a":1, "b":2}
        self.start(**p)

    def start(self, **params):
        print(params)

t = Test()
t.a()

rawDescription: Reducing the number of parameters a function takes in python


code: text_widget.bind("<1>", lambda event: text_widget.focus_set())

rawDescription: How to disable input to a Text widget but allow programatic input?

description: Disable input to a Text widget but allow programatic input


code: data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))

rawDescription: django serializers to json - custom json output format

description: Django serializers to json - custom json output format


code:
for f in floats:
    print(' '.join('0x{:02x}'.format(c) for c in struct.pack('>d', f)))

rawDescription: Python outputs strange bytearray

description: Python outputs strange bytearray


code:
def start2(parent):
    inputbox = wx.SingleChoiceDialog(parent,'Choose Fruit', 'Selection Title',
                                     ['apple','banana','orange','papaya'])
    if inputbox.ShowModal()==wx.ID_OK:
        answer = inputbox.GetStringSelection()
    inputbox.Destroy()

class TopLevelFrame2(wx.Frame):

    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id,"Test",size=(300,200))
        panel=wx.Panel(self)
        button=wx.Button(panel, label='Show Dialog', pos=(130,20), size=(60,20))

        # Bind EVENTS --> HANDLERS.
        button.Bind(wx.EVT_BUTTON, self.OnClick)

    def OnClick(self, evt):
        start2(self)

rawDescription: wxPython: How to handle event binding and Show() properly

description: WxPython: How to handle event binding and Show() properly


code:
import httplib

connection =  httplib.HTTPConnection('www.somedomain.com:50070')
connection.request('PUT', '/webhdfs/v1/levi/4?op=CREATE')

response = connection.getresponse()

rawDescription: Put this request with Python httplib

description: Put this request with Python httplib


code:
zeroArray = [0] * Np
zeroMatrix = [zeroArray[:] for i in range(Np)]

rawDescription: How to preallocate a list of lists?

description: Preallocate a list of lists


code: ' '.join(word[0] for word in word_list)

rawDescription: How do i turn a list of words into a sentence string?

description: Turn a list of words into a sentence string


rawDescription: Run tornado web app in my own computer as server


code: treatFiles(argv[1], argv[2], newFile, int(argv[3]), int(argv[4]), int(argv[5]))

rawDescription: Improving a python code reading files

description: Improving a python code reading files


rawDescription: Parsing members of a variable length python string


code:
writers = {}
with open(os.path.join(path, "student_rosters.csv"), "rb") as rosters:
    reader = csv.DictReader(rosters)
    for row in reader:
        course = row['COURSES_COLUMN_HEADER']
        if course not in writers:
            outfile = open(os.path.join(path, course + ".csv"), "wb")
            writers[course] = csv.DictWriter(outfile, reader.fieldnames)
        writers[course].writerow(row)

rawDescription: How do I make the filename of the output csv file equal to the the content of a column

description: Make the filename of the output csv file equal to the the content of a column


code:
links = driver.find_elements_by_link_text('View all hits in this text')
for link in links:
    link.click()

rawDescription: Selenium in Python: Select the second element with given link text


code:
class Object(object):
  _speed = 0
  @property
  def speed(self):
     return self.__class__._speed
  @speed.setter
  def speed(self, value):
     self.__class__._speed = value

rawDescription: Changing variables in multiple Python instances


code:
class IndexOrderedSet(OrderedSet):
    def index(self, elem):
        if key in self.map:
            return next(i for i, e in enumerate(self) if e == elem)
        else:
            raise KeyError("That element isn't in the set")

rawDescription: Python OrderedSet with .index() method

description: Python OrderedSet with .index() method


rawDescription: Getting the indices of the top k numbers by value in a numpy array?


code:
if not lists:
    sys.exit('No jpegs found')
# put main program here, unnested

rawDescription: python argparse set behaviour when no arguments provided

description: Python argparse set behaviour when no arguments provided


rawDescription: How to decode a 'url-encoded' string in python

description: Decode a 'url-encoded' string in python


code: label.set_text('This is the new label')

rawDescription: How can I change the display text of a MenuItem in Gtk2?

description: Change the display text of a MenuItem in Gtk2


code:
from xml.etree import ElementTree as ET

# build a tree structure
root = ET.Element("{http://www.company.com}STUFF")
body = ET.SubElement(root, "{http://www.company.com}MORE_STUFF")
body.text = "STUFF EVERYWHERE!"

# wrap it in an ElementTree instance, and save as XML
tree = ET.ElementTree(root)

tree.write("page.xml",
           xml_declaration=True,encoding='utf-8',
           method="xml",default_namespace='http://www.company.com')

rawDescription: Emitting namespace specifications with ElementTree in Python


code:
a = b = None
for name in files:
    if fnmatch.fnmatch(name, 'A.csv'):
        a = name
    elif fnmatch.fnmatch(name, 'B.csv'):
        b = name
        fileList.append(os.path.join(dirpath, name))
if a is not None and b is None:
    fileList.append(os.path.join(dirpath, a))

rawDescription: Searching recursively for files to add to list, but if one type of file is found ignore other type


rawDescription: Python: How can I increment a char?

description: Python: How can I increment a char


code: dfMerged = dfA.merge(dfB, left_on='ID', right_on='ID', how='outer') # defaults to inner join.

rawDescription: Pandas difference between dataframes on column values


rawDescription: Scramble Python List

description: Scramble Python List


code:
crit1 = df['datecol'].map(lambda x : x.year == 2014)
crit2 = df['datecol'].map(lambda x : x.month == 1)

df[crit1 & crit2]

rawDescription: Selecting rows with a particualr year and month


code:
from itertools import count
from collections import defaultdict

counters = defaultdict(lambda: count(1))

result = [(n, next(counters[n])) for n in inputlist]

rawDescription: Find same elements in a list, and then change these elemens to tuple (f.e. 2 to (2,1))


code:
total = 0
for c in T:
    total += c

rawDescription: Python, a sum() issue

description: Python, a sum() issue


code:
rows = zip(dates, flags, tickers, amount, price)
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', rows)

rawDescription: How to put lists together into list holding them as 'tuples'

description: Put lists together into list holding them as 'tuples'


code:
import sqlalchemy.types as types
import jsonpickle
from copy import deepcopy

class JsonType(types.MutableType, types.TypeDecorator):
    impl = types.Unicode

    def process_bind_param(self, value, engine):
        return unicode(jsonpickle.encode(value))

    def process_result_value(self, value, engine):
        if value:
            rv = jsonpickle.decode(value)
            return rv
        else:
            return None

    def copy_value(self, value):
        return deepcopy(value)

    def compare_values(self, x, y):
        return x == y

rawDescription: one field with different data types [SQLAlchemy]

description: One field with different data types [SQLAlchemy]


code: upper = x[np.triu_indices(N, k)]

rawDescription: Generating indices using np.triu_indices


code:
from __future__ import print_function

print(*map("".join,zip(*grid)),sep="\n")

rawDescription: How can I rotate this list of lists with python

description: Rotate this list of lists with python


code:
import wx
import math
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas

class Graph(wx.Panel):
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)
        self.figure = Figure()
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.Bind(wx.EVT_SIZE, self.OnSize)

    def OnSize(self, event):
        size = self.GetSize()
        self.canvas.SetSize(size)

    def Draw(self):
        self.figure.clear()
        self.subplot = self.figure.add_subplot(111)
        x = [a*(math.pi/50) for a in range(100)]
        y = [self.f(a) for a in x]
        self.subplot.plot(x, y)
        self.canvas.draw()

    def DrawCosine(self, e):
        self.f = math.cos
        self.Draw()

    def DrawSine(self, e):
        self.f = math.sin
        self.Draw()

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

        self.panel = wx.Panel(self)
        self.button1 = wx.Button(self.panel, label="Sine")
        self.button2 = wx.Button(self.panel, label="Cosine")
        self.graph = Graph(self.panel)
        self.graph.DrawSine(None)

        self.button1.Bind(wx.EVT_BUTTON, self.graph.DrawSine)
        self.button2.Bind(wx.EVT_BUTTON, self.graph.DrawCosine)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer2 = wx.BoxSizer()

        self.sizer.Add(self.graph, 1, wx.ALL | wx.EXPAND)
        self.sizer2.Add(self.button1, 1, wx.ALL | wx.EXPAND)
        self.sizer2.Add(self.button2, 1, wx.ALL | wx.EXPAND)
        self.sizer.Add(self.sizer2, 0, wx.ALL | wx.EXPAND)

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

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

rawDescription: wxPython, PyQwt or C# for plotting graph and manually drawing lines on plot

description: WxPython, PyQwt or C# for plotting graph and manually drawing lines on plot


code: return set(st)

rawDescription: Removing duplicates from a string in Python without using adittional buffer


rawDescription: Change Marker Style/Color in Python Probplot


code:
class Tester(object):
    def __init__(self):
        self.__foo = "hi"

Tester()._Tester__foo
Tester().__foo

rawDescription: Python "private" name mangling and instance vs class attributes


rawDescription: Explicitly select items from a Python list or tuple


code:
pairs = []
M = N
if M % 2 == 1:
  M -= 1
while len(pairs) < K:
  B = random.sample(X,M)
  A = zip(B[0:(M/2)],B[(M/2):M])
  pairs.extend(A)
pairs = pairs[0:K]

rawDescription: getting the most 'diverse' set of pairs from a list in Python?

description: Getting the most 'diverse' set of pairs from a list in Python


code:
import re

text = '''
<modules>
    <Orba_Sheepla>
        <!-- module version -->
        <version>0.9.25</version>
    </Orba_Sheepla>
</modules>'''

pattern = re.compile( r'^([ \t]+)<version>.*?^(?!\1)[ \t]*</([^\s>]+)', re.I | re.S | re.M)
match = pattern.search(text)

if match:
    print(match.group(2))

rawDescription: Get XML parent tag with regular expressions


code:
# plot signals
import matplotlib.pyplot as plt
plt.figure(1)
plt.plot(data, label="raw")
plt.plot(data_bp8, label="order 8")
plt.plot(data_bp2, label="order 2")
plt.legend()

rawDescription: Most efficient way to filter a long time series Python


code: cb = lambda : self.resp(items, iteration)

rawDescription: Tornado AsyncHTTPClient fetch callback: Extra parameters?


code:
a = [[] for _ in range(3)]
a[0].append(42)
a

rawDescription: Create sub-lists in lists in Python

description: Create sub-lists in lists in Python


code:
from openerp.osv import fields, osv

class crm_lead(osv.osv):
    _name = 'bala.lead'
    _inherit = 'crm.lead'
    _description = "adding fields to crm.lead"
    _columns = {
          'nitesh_lead': fields.char('Nitesh Lead',size=64)
    }
crm_lead()

rawDescription: After inheriting CRM-Lead unable to hide or add fields to my Custom module in Openerp


code:
import numpy as np
import matplotlib.pyplot as plt
import scipy, pylab

plt.axes()
circle=plt.Circle((0, 0), radius=1, fc='w')
plt.gca().add_patch(circle)
plt.xlim([-3, 3])
plt.ylim([-3, 3])
plt.yticks(np.arange(-3, 3, 0.25))
plt.xticks(np.arange(-3, 3, 0.25))
plt.show()

rawDescription: How to change the range of the x-axis and y-axis in matlibplot?

description: Change the range of the x-axis and y-axis in matlibplot


rawDescription: Combine multiple heatmaps in matplotlib

description: Combine multiple heatmaps in matplotlib


code: count_substitutions('AAA', 'AAT')

rawDescription: Python comparing two strings

description: Python comparing two strings


code: return theano.tensor.net.binary_crossentropy(y_pred * v, y_true * v)

rawDescription: Calculate Hits At metric in Theano

description: Calculate Hits At metric in Theano


code:
index = pd.date_range(start=date(1996, 1,1), end=date(2010, 6, 30), freq='D')
daily = pd.DataFrame(index=index, data=np.random.random(size=len(index)), columns=['temperature'])

rawDescription: Align years of daily data

description: Align years of daily data


code:
from collections import defaultdict

file_dict = defaultdict(list)
for filename in files:
    file_dict[get_file_hash(filename)].append(filename)

rawDescription: Finding duplicate files via hashlib?

description: Finding duplicate files via hashlib


code:
from copy import deepcopy
lis = [[1,2,3],[4,5,6]]
foo = deepcopy(lis)

rawDescription: List being identified with another, using new items in the loop


code:
import numpy as np

phi = 0.5
theta = 1
n1 = 10
n2 = 20

N1 = np.random.randint(-100, 100, size=100)
N2 = np.random.randint(-100, 100, size=100)

N1 = N1[(N1 >= 0) & (N1 <= n1)]
N2 = N2[(N2 >= 0) & (N2 <= n2)]

a = N2 * theta + phi
res = N1.reshape(N1.shape[0], 1) - a.reshape(1, a.shape[0])

indices = np.argwhere(res >= 0)
pairs = zip(N1[indices[:,0]], N2[indices[:,1]])

rawDescription: Finding combinations that meet a threshold relation


code:
mask = (v == v.max())
mask = mahotas.dilate(mask, np.ones((48,24)))

rawDescription: How do I find Wally with Python?

description: Find Wally with Python


code:
from inspect import getmembers, isfunction
import jinja_filters

app = Flask(__name__)

my_filters = {name: function
                for name, function in getmembers(jinja_filters)
                if isfunction(function)}

app.jinja_env.filters.update(my_filters)

rawDescription: How to import custom jinja2 filters from another file (and using Flask)?

description: Import custom jinja2 filters from another file (and using Flask)


code:
text_file = ['hello','world','testing']
term_dict = {'some':0, 'word':0, 'world':0}

for word in text_file:
    if word in term_dict:
        term_dict[word] = 1

rawDescription: Vectorizing LIst of Unique Words into 0 or 1 using Python


code:
window = QtWidgets.QWidget()    # note that no parent is given
window.show()

rawDescription: Communicate between two MainWindow() in Qt


rawDescription: Fdist and top 10 function words

description: Fdist and top 10 function words


code:
df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))
df
df_greater_10 = df.ix[df.c > 10, ['a','c']]
df_greater_10

rawDescription: How do I create a DataFrame containing a column where rows are greater than a number?

description: Create a DataFrame containing a column where rows are greater than a number


code:
from wand.image import Image
from wand.color import Color

with Image(filename="pic.png") as img:
  # -resize 300%
  scaler = 3
  img.resize(img.width * scaler, img.height * scaler)
  # -background white
  img.background_color = Color("white")
  img.save(filename="pic2.png")

rawDescription: How to convert this command to a python code using Wand & ImageMagick

description: Convert this command to a python code using Wand & ImageMagick


code:
import csv
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
rows = [{'Symbol':'AA', 'Price':39.48, 'Date':'6/11/2007',
         'Time':'9:36am', 'Change':-0.18, 'Volume':181800},
        {'Symbol':'AIG', 'Price': 71.38, 'Date':'6/11/2007',
         'Time':'9:36am', 'Change':-0.15, 'Volume': 195500},
        {'Symbol':'AXP', 'Price': 62.58, 'Date':'6/11/2007',
         'Time':'9:36am', 'Change':-0.46, 'Volume': 935000}]

with open('stocks.csv','w') as f:
    f_csv = csv.DictWriter(f, headers)
    f_csv.writeheader()
    f_csv.writerows(rows)

with open('stocks.csv', 'r') as file:
    csvread = csv.DictReader(file, delimiter=',')

    rows = []
    for row in csvread:
        row['NewColumn'] = '1'
        rows.append(row)

    with open('out.csv', 'w') as out:
        headertowrite = ['Time', 'Symbol', 'NewColumn']
        writer = csv.DictWriter(out, headertowrite, extrasaction='ignore')
        writer.writeheader()
        writer.writerows(rows)

rawDescription: "Doing work" on csv DictReader fails

description: "Doing work" on csv DictReader fails


code: s = ' '.join(' '.join(str(a[i,j,k].real) for j in range(a.shape[1]) for i in range(a.shape[0])) + ' ' + ' '.join(str(a[i,j,k].imag) for j in range(a.shape[1]) for i in range(a.shape[0])) for k in range(a.shape[2]))

rawDescription: Pythonic way to print a multidimensional complex numpy array to a string


rawDescription: How do you replace empty strings in sublists with '0'?

description: Replace empty strings in sublists with '0'


rawDescription: random numbers with tkinter

description: Random numbers with tkinter


code:
newset = {
  #name : (value, type)
  'lfFaceName': ('Courier New', 1),
  'lfWeight': (700, 4),            #400=normal, 700=bold
  'lfUnderline': (0, 4),
  'lfItalic': (1, 4),              #0=disabled, 1=enabled
  'lfStrikeOut': (0, 4),
  'iPointSize': (160, 4),          #160 = 16pt
  'iMarginBottom': (1000, 4),      #1 inch
  'iMarginTop': (1000, 4),
  'iMarginLeft': (750, 4),
  'iMarginRight': (750, 4),
  'szHeader': ('&f', 1),            #header '&f'=filename
  'szTrailer': ('Page &p', 1),      #footer '&p'=page number
}

notepad_print('datafile.txt', newset)

rawDescription: hide header and footer on text files when direct print using win32 and python

description: Hide header and footer on text files when direct print using win32 and python


code:
class UserDataCreateView(CreateView):
  model=models.UserData

  def get_form_kwargs(self):
      kwargs = super(UserDataCreateView, self).get_form_kwargs()
      kwargs.update({'request': self.request})
      return kwargs

class UserDataDetailView(DetailView):
  def get_object(self, queryset=None):
      obj = super(UserDataDetailView, self).get_object(queryset)
      if not user_has_access(obj, self.request):
          raise Http404(u"Access Denied")
      return obj

class UserDataUpdateView(UpdateView):
  model=models.AuthorityData

  def get_form_kwargs(self):
      kwargs = super(UserDataUpdateView, self).get_form_kwargs()
      kwargs.update({'request': self.request})
      return kwargs

  def get_object(self, queryset=None):
      obj = super(UserDataUpdateView, self).get_object(queryset)
      if not user_has_access(obj, self.request):
          raise Http404(u"Access Denied")
      return obj

rawDescription: Object level permissions in Django admin


code: min(range(len(a)), key=lambda i: abs(a[i]-11.5))

rawDescription: finding index of an item closest to the value in a list that's not entirely sorted

description: Finding index of an item closest to the value in a list that's not entirely sorted


code:
from dis import dis

def foo():
    x = 1
    x = x

dis(foo)

rawDescription: What happens if I say x = x? (On a low, compiler level)


code:
class missions(models.Model):
    crewmembers = models.ManyToManyField('astronauts')

rawDescription: Reference multiple foreign keys in Django Model


code:
from subprocess import Popen, PIPE
from datetime import datetime

# yes, this is me being lazy and not wanting to write a format string.
date = datetime.today().isoformat().split('T')[0]

mysql = "mysqldump -u *username* -p*password* *database* > /usr/local/src/djcode/c2duo_mms/backup-{}.sql".format(date)
gzip = "gzip -c /usr/local/src/djcode/c2duo_mms/backup.sql > /usr/local/src/djcode/c2duo_mms/backup-{}.gz".format(date)

Popen(mysql, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell = True)
Popen(gzip, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell = True)

rawDescription: Want to timestamp two files

description: Want to timestamp two files


code: application = endpoints.api_server([api_root, ...])

rawDescription: Cloud Endpoints with Multiple Services Classes


code:
{'bozo': 1,
 'bozo_exception': xml.sax._exceptions.SAXParseException("EntityRef: expecting ';'\n"),
 'encoding': u'utf-8',
 'entries': [{'link': u'https://hr.example.org/psp/hrapp&SeqId=1',
   'links': [{'href': u'https://hr.example.org/psp/hrapp&SeqId=1',
     'rel': u'alternate',
     'type': u'text/html'}],
   'tags': [{'label': None, 'scheme': None, 'term': u'All Open Jobs'}],
   'title': u'SENIOR BUDGET ANALYST (new)',
   'title_detail': {'base': u'',
    'language': None,
    'type': u'text/plain',
    'value': u'SENIOR BUDGET ANALYST (new)'},
   'updated': u'Wed, 18 Jul 2012 04:00:00 GMT',
   'updated_parsed': time.struct_time(tm_year=2012, tm_mon=7, tm_mday=18, tm_hour=4, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=200, tm_isdst=0)},
  {'link': u'https://hr.example.org/psp/hrapp&SeqId=2',
   'links': [{'href': u'https://hr.example.org/psp/hrapp&SeqId=2',
     'rel': u'alternate',
     'type': u'text/html'}],
   'tags': [{'label': None, 'scheme': None, 'term': u'All category'}],
   'title': u'BUDGET ANALYST (healthcare)',
   'title_detail': {'base': u'',
    'language': None,
    'type': u'text/plain',
    'value': u'BUDGET ANALYST (healthcare)'},
   'updated': u'Wed, 18 Jul 2012 04:00:00 GMT',
   'updated_parsed': time.struct_time(tm_year=2012, tm_mon=7, tm_mday=18, tm_hour=4, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=200, tm_isdst=0)}],
 'feed': {},
 'namespaces': {},
 'version': u'rss20'}

rawDescription: How to scrape xml feed with xmlfeedspider

description: Scrape xml feed with xmlfeedspider


code:
def try_calc():
    a = {'1': 100, '2': 200, '3': 0, '4': -1, '5': None, '6': 'a'}
    calculations = {
        '10': lambda: float(a['1'] * a['2']),
        '11': lambda: float(a['1'] * a['5']),
        '12': lambda: float(a['1'] * a['6']),
        '13': lambda: float(a['1'] / a['2']),
        '14': lambda: float(a['1'] / a['3']),
        '15': lambda: float((a['1'] * a['2']) / (a['3'] * a['4']))
    }
    for key, calculation in calculations.iteritems():
        try:
            a[key] = calculation()
        except (ZeroDivisionError, KeyError, TypeError, ValueError) as e:
            a[key] = None

rawDescription: Readable try except handling with calculations


code: (M == 0).T.nonzero()

rawDescription: How to get a value from every column in a Numpy matrix

description: Get a value from every column in a Numpy matrix


code:
from django.conf.urls.defaults import patterns, url

urlpatterns = patterns('key_auth.views',
    url(r'^$', 'login_view', name='key_auth_login'),
)

rawDescription: Security issues with a middleware screener page


code:
gVar = 10

def editVar():
    global gVar
    gVar += 5

rawDescription: Empty output after appending a list

description: Empty output after appending a list


code:
with open(audiofile, 'rb') as fobj:
    requests.post(url, files={'fieldname', fobj})

rawDescription: Is it possible to post audio files with the python requests library


code:
def __sum_of_hand(self):
    return sum(x.value for x in self.hand)

rawDescription: Python - __str__ returning elements of a list


rawDescription: Convert fixed-width, non-delimited float strings to comma separated values


code: {'Group3': ['DDDD'], 'Group4': ['BBBBB'], 'Group1': ['EEEE'], 'Group2': ['CCCCC'], 'Group5': ['AAAA']}

rawDescription: Append to arrays in loop

description: Append to arrays in loop


code:
def recurse_keys(document):
    for key in document.keys():
        print(str(key))
        if isinstance(document[key], dict):
           recurse_keys(document[key])

rawDescription: How to get all the keys of a Json document using pymongo?

description: Get all the keys of a Json document using pymongo


code: new_dict = {}

rawDescription: Creating a new dict in Python

description: Creating a new dict in Python


code: a = np.random.randint(5, 10, size=100) # 100 [5-10) random numbers

rawDescription: List of indices of every value

description: List of indices of every value


code:
# Unique authors
unique_authors = set([ a for year, authors in the_list
                           for a in authors])

rawDescription: Counting number of elements in nested list


code:
p = Popen(C_SHARP_EXECUTABLE_FILE_PATH, stdout=PIPE, stdin=PIPE, stderr=PIPE)
out, err = p.communicate(blob)

rawDescription: Passing data between Python and C# without writing a file


code:
conn = sqlite3.connect('data.db')
conn.execute('ATTACH DATABASE details.db AS details')

rawDescription: joining across databases with sqlite3 / pysqlite

description: Joining across databases with sqlite3 / pysqlite


code:
for i in xrange(3, int(math.sqrt(n)), 2):  # use 'range' in Python 3
    if n % i == 0:
        return False

rawDescription: What is Python's equivalent of Java's standard for-loop?


code:
from django.db.models import Q
garage = Garage.objects.all()[0]
query = Vehicle.objects.filter(Q(garage=garage))
query = query.filter(Q(wheels=2) | (Q(wheels=4) & Q(gears=1)))

rawDescription: Django advanced query

description: Django advanced query


code:
def segment(text):
    "Return a list of words that is the best segmentation of text."
    if not text: return []
    candidates = ([first]+segment(rem) for first,rem in splits(text))
    return max(candidates, key=Pwords)

rawDescription: A little help needed in code translation (Python to C#)


code:
cat_to_prod_count = dict(Product.objects
                                .values('category_id')
                                .order_by()
                                .annotate(product_count=Count('id'))
                                .values_list('category_id', 'product_count'))

rawDescription: Tastypie Dehydrate reverse relation count


code: a = Action(*command.split(';'))

rawDescription: python - elegantly handle sequence of multiple arguments

description: Python - elegantly handle sequence of multiple arguments


code:
import itertools
def union_size(sets):
    return sum((-1)**(i+1) * len(set.intersection(*subset))
               for i in xrange(1, len(sets) + 1)
               for subset in itertools.combinations(sets, i))

rawDescription: Setting Up A Recursive Function to Calculate Inclusion Exclusion in Python


code:
def pairup(alist):
  seen = set()
  for word in alist:
    if word not in seen:
      # Haven't seen this one yet
      if word[::-1] in seen:
        # But we've seen its reverse, so we found a pair
        yield (word, word[::-1])
      # Now we've seen it
      seen.add(word)

rawDescription: Efficiently printing matching pairs of semordnilaps from a sorted list of words


code: output = [ (kl(line),line.rstrip()) for line in output]

rawDescription: How to merge only the unique lines from file_a to file_b?

description: Merge only the unique lines from file_a to file_b


code:
leg = plt.legend()
leg.get_frame().set_edgecolor('b')

rawDescription: Remove or adapt border of frame of legend using matplotlib


rawDescription: Python 2 lists of positive integers finding prime number


code:
def check(lst):
        for i in range(len(lst)):
            try:
                    if lst[i+1]-lst[i] != 1:
                            return False
            except IndexError:
                    pass
        return True

check([3, 4, 6])
check([3, 4, 5])
check([3, 4, 5, 6])
check([3, 4, 5, 8])

rawDescription: Itertools, combinations

description: Itertools, combinations


code: processmenu.add_cascade(..., command = main)

rawDescription: Tkinter automatically opens my file

description: Tkinter automatically opens my file


code:
def smallest_sum(n, digits, first=1):
    """Find the smallest number with 'digits' digits that sum to 'n'
    Returns the value as a list of digits because that's what we need next anyway"""
    k = max(first,n + 9 - 9*digits)
    assert k <= 9, "Impossible values"
    if digits > 1:
            return [k]+smallest_sum(n-k, digits-1, 0)
    return [k]

def all_sums(digits):
    """Find the next string of digits with the same sum.
    We can do this by finding the last non-zero digit and decrementing it
    then incrementing the previous non-nine, and sorting any digits that
    follow it."""
    yield digits
    while True:
        was = list(digits)
        for i in range(len(digits)-1,-1,-1):
            if digits[i] != 0:
                decrement = i
                break
        else:
            return
        for i in range(decrement-1,-1,-1):
            if digits[i] != 9:
                increment = i
                break
        else:
            return
        digits[decrement] -= 1
        digits[increment] += 1
        if increment < len(digits)-2:
            digits[increment+1:] = digits[increment+1:][::-1]
        assert digits > was
        yield digits

def count(num_digits, total):
    try:
        digits = smallest_sum(total, num_digits)
    except AssertionError:
        return 0
    return sum(1 for _ in all_sums(digits))

if __name__=='__main__':
    print(count(4,18))
    print(count(10,39))

rawDescription: Speeding Up a Python While Loop

description: Speeding Up a Python While Loop


code: return (value,) + (None,) * (tuple_length - 1)

rawDescription: Is there a more lightweight way to get a tuple of variable length?


code: {orders[i]['food'] for i in orders}

rawDescription: Obtaining list (or set) of unique values in nested dictionary


code:
asyncio.get_event_loop().run_until_complete(asyncio.wait([
   alive(),
   async_processing()
]))

rawDescription: Python async websocket client with async timer


code:
class SetAttrMeta(type):
    def __setattr__(cls, name, value):
        print("Hey, you can't set {0} to {1}!".format(name, value))

class C(metaclass=SetAttrMeta):
    pass

C.spam = 'eggs'

rawDescription: Is it possible to override __setattr__ for a class?


code:
x = "hello"
x.sayHello()
x = str("hello")
x.sayHello()

rawDescription: Add custom method to string object

description: Add custom method to string object


code:
from collections import defaultdict

import nltk
from nltk.classify import MaxentClassifier, accuracy
from nltk.corpus import movie_reviews

rawDescription: My Maxent Classifier works fine with gis algorithm but does not work with iis algorithm. It is not throwing any error, just some warnings


code:
def handleRequest(request):
    if SomeSharedMemory is None:
        d = initSharedMemory()
        d.addCallback(lambda ignored: handleRequest(request))
    else:
        d = PickSomething(SomeSharedMemory)
    return d

rawDescription: Waiting on events in other requests in Twisted


code: s = u'carbon҂ ҉ copolymers—⿴٬ٯ٪III❏£\n12-ः׶ Ǣ ܊ܔ ۩۝۞ء܅۵Géotechnique▣ऀ\n'

rawDescription: Remove all symbols while preserving string consistency


code:
w = csv.writer(...)
for r in records:
    l = {}
    for field in fields:
        f_ = rename(field)
        v_ = transform(field, r.get(field, default(field)))
        l[f_] = v_
    w.write(l)

rawDescription: Looking for a DSL to convert JSON to CSV


code: values /= weights[..., numpy.newaxis]

rawDescription: Plotting sort of a heatmap whose colors are a result of a function x,y -> r,g,b


code:
df
keep = [123, 133]
df_yes = df[df['zip'].isin(keep)]
df_no = df[~df['zip'].isin(keep)]
df_yes
df_no

rawDescription: Python Pandas - Removing Rows From A DataFrame Based on a Previously Obtained Subset


code:
iris = load_iris()
t = tree.DecisionTreeClassifier()
fitted_tree = t.fit(iris.data, iris.targets)
outfile = tree.export_graphviz(fitted_tree, out_file='filename.dot', feature_names=iris.feature_names)
outfile.close()

rawDescription: How to use the actual feature names instead of "X" in scikit-learn DecisionTreeRegressor?

description: Use the actual feature names instead of "X" in scikit-learn DecisionTreeRegressor


code:
def main():
    names = list()
    with open("users.txt", "r") as myfile:
        for line in myfile:
            names.append(line.split('|'))
    print(names)

rawDescription: How to create a list of sublists where the sublists are split strings?

description: Create a list of sublists where the sublists are split strings


code:
df = data.iloc[:, data.columns.str.contains('durations.*'|'shape.*') ]
df.fillna(0)

rawDescription: How to select all columns that start with "durations" or "shape"?

description: Select all columns that start with "durations" or "shape"


code:
import json

file = 'data.json';
data = json.loads(open(file).read())

print(data)

rawDescription: Writing a Perl hash to disk to be read by Python


code:
DEFAULT_FRAMEWORK_FALLBACK = [
    os.path.expanduser("~/Library/Frameworks"),
    "/Library/Frameworks",
    "/Network/Library/Frameworks",
    "/System/Library/Frameworks",
]

DEFAULT_LIBRARY_FALLBACK = [
    os.path.expanduser("~/lib"),
    "/usr/local/lib",
    "/lib",
    "/usr/lib",
]

rawDescription: Which paths does python ctypes module search for libraries on Mac OS?


rawDescription: How can I add two functions together in Python 3?

description: Add two functions together in Python 3


code:
def default_xml_tag(value, arg):
    if value:
        return "<{0}>{1}</{0}>".format(arg, value)
    else:
        return ""

rawDescription: Is there an elegant way to apply {% if .. %} to a whole load of tags in Django?


code:
# setup.py
import sys

def load():
    paths = ['/path1/','/path2/','/path3/']
    for p in path:
        sys.path.insert(0, p)

# entrypoint.py
from setup import load
load()
# continue with program

rawDescription: Import paths - the right way?

description: Import paths - the right way


code:
text_widget.index('end')  # returns line.column
int(text_widget.index('end').split('.')[0]) - 1  # returns line count

rawDescription: Getting the total number of lines in a Tkinter Text widget?


code:
import urllib.request
urllib.request.urlretrieve('http://chart.apis.google.com/...', 'outfile.png')

rawDescription: Python: saving image from web to disk

description: Python: saving image from web to disk


code: logger = logging.getLogger(__name__)

rawDescription: Better logging system for entire package


code:
loc = df1.index.get_loc(t)
df.irow(loc - 1)
df1.irow(slice(max(0, loc-3), min(loc, len(df))))

rawDescription: get previous value of pandas datetime index

description: Get previous value of pandas datetime index


code:
sql = "INSERT INTO `arzugulgundogdu2` (`id`) VALUES (%s)"

value = "dgNotListesi_txtGelisimDurumu_%s" % y
cursor.execute(sql, (y, ))

rawDescription: python mysql in order number input to table id

description: Python mysql in order number input to table id


code:
from mock import patch, Mock

class MyClass(object):
    def __init__(self):
        self.prop = 'prop'

    def foo(self):
        return 'foo'

    def bar(self):
        return 'bar'

    def unmocked(self):
        return 'unmocked'

patcher = patch.multiple('__main__.MyClass',
                         foo=Mock(return_value='mocked foo!'),
                         bar=Mock(return_value='mocked bar!'))
patcher.start()

my_instance = MyClass()
assert my_instance.foo() == 'mocked foo!', my_instance.foo()
assert my_instance.bar() == 'mocked bar!', my_instance.bar()
assert my_instance.unmocked() == 'unmocked', my_instance.unmocked()
assert my_instance.prop == 'prop', my_instance.prop

patcher.stop()

rawDescription: Using the Python mock module, how can I patch a class so that it stubs only the methods I want to stub and leaves other properties and methods alone?


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

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

x = np.random.sample(20)
y = np.random.sample(20)
z = np.random.sample(20)
s = ax.scatter(x, y, z, c="r")
s.set_edgecolors = s.set_facecolors = lambda *args:None

ax.legend()
ax.set_xlim3d(0, 1)
ax.set_ylim3d(0, 1)
ax.set_zlim3d(0, 1)

plt.show()

rawDescription: Controlling alpha value on 3D scatter plot using Python and matplotlib


code:
def decorator2(method_to_decorate):
    @wraps(method_to_decorate)
    def wrapper2(self, request, *args, **kwargs):

        result = method_to_decorate(self, request, *args, **kwargs)

        if isinstance(result, tuple) and result and result[0] == 'failure':
            # decorator1 returned a failure
            return result
        else:
            # decorator1 passed through the wrapped method call
            if decorator2_s_test_was_successful:
                return result
            else:
                return ('another failure', 'message')

    return wrapper2

rawDescription: multiple python decorators

description: Multiple python decorators


code: data['letter']

rawDescription: importing an array from a .dat file in python

description: Importing an array from a .dat file in python


code:
writer=csv.writer(outfile, dialect="excel", delimiter="\t",skipinitialspace=True)
# …
writer.writerow(row[0], row[1], row[9], row[4], row[6], row[5], row[19])

rawDescription: manipulating TSV file

description: Manipulating TSV file


code:
import pdfkit
pdfkit.from_file('template.html', 'output.pdf')

rawDescription: Combine existing figures into one pdf of figure PYTHON


code:
class Test:
    def __init__(self):
        ...
        connect_callbacks(self)

    @callback(widget, signal)
    def test():
        ...

rawDescription: How to get a reference to an instance method from a decorator

description: Get a reference to an instance method from a decorator


rawDescription: Reduce Two Pandas Series to a Single One


code:
listA = [1, 2, 3]
listB = [4, 5, 6]
listC = [7, 8, 9]
n = 9
any(n in x for x in (listA, listB, listC))
n = 4
any(n in x for x in (listA, listB, listC))
n = 0
any(n in x for x in (listA, listB, listC))

rawDescription: Possible to simplify finding if an element exist in multiple lists?


code: return Anomaly(p)

rawDescription: Can I let a superclass return reference to the "actual type"?

description: Let a superclass return reference to the "actual type"


code:
__setitem__
__delitem__
insert
append
reverse
extend
pop
remove
__iadd__

rawDescription: Is any Python type whose objects contain elements that are numbered called a sequence type?


rawDescription: Merge two CSV's with unique columns in python


rawDescription: Convert UTF-8 octets to unicode code points


code:
import definitions

for parameter in xrange(0,10):
    defs = definitions.Definitions()
    defs.variable1 = parameter

    # do some stuff and store the result

# compare the various results

rawDescription: Need help properly using variables, python


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

pygame.init()

BLACK =          (  0,   0,   0)
ABINO =          ( 34,  45, 102)
PINDLER =        (255, 123,  90)
MEXON =          (200, 190, 220)
WHITE =          (255, 255, 255)
YELLOW =         (255, 255,   0)
RED =            (255,   0,   0)
BLUE =           (  0,   0, 255)

size = [700, 500]
D = pygame.display.set_mode(size)
L = pygame.draw.aaline
R = pygame.draw.rect
G = random.randrange(1, 10)
GM = 1
GMT = 2
CIP = 1
CO = 2
V = 0
Blue = 1
event_500ms = pygame.USEREVENT + 1
pygame.time.set_timer(event_500ms, 500)

pygame.display.set_caption("Moline")
myfont = pygame.font.SysFont("monospace", 15)
T = myfont.render
M1S = "RULES:"
M2S = "1. To start, press each arrow key in a random sequence"
M2F = " for roughly one second."
M3S = "2. To win, re-merge the four men on the crossmark."
M4S = "3. Complete before the running man completes a lap."
M5S = "4. Mouse movement is illegal and causes a severe time penalty."
L1 = T(M1S, 1, (255, 255, 0))
L2 = T(M2S, 1, (255, 255, 0))
L2C = T(M2F, 1, (255, 255, 0))
L3 = T(M3S, 1, (255, 255, 0))
L4 = T(M4S, 1, (255, 255, 0))
L5 = T(M5S, 1, (255, 255, 0))
B = D.blit
Fx = 10
Fy = 10
L6 = T("cheeeeeeeeese", 1, (255, 255, 0))

def MOLINE1(D, x, y):
    pygame.draw.ellipse(D, BLACK, [1 + x, y, 10, 10], 0)

    pygame.draw.line(D, BLACK, [5 + x, 17 + y], [10 + x, 27 + y], 2)
    pygame.draw.line(D, BLACK, [5 + x, 17 + y], [x, 27 + y], 2)

    pygame.draw.line(D, PINDLER, [5 + x, 17 + y], [5 + x, 7 + y], 2)

    pygame.draw.line(D, PINDLER, [5 + x, 7 + y], [9 + x, 17 + y], 2)
    pygame.draw.line(D, PINDLER, [5 + x, 7 + y], [1 + x, 17 + y], 2)

def MOLINE2(D, x, y):
    pygame.draw.ellipse(D, BLACK, [1 + x, y, 10, 10], 0)

    pygame.draw.line(D, BLACK, [5 + x, 17 + y], [10 + x, 27 + y], 2)
    pygame.draw.line(D, BLACK, [5 + x, 17 + y], [x, 27 + y], 2)

    pygame.draw.line(D, PINDLER, [5 + x, 17 + y], [5 + x, 7 + y], 2)

    pygame.draw.line(D, PINDLER, [5 + x, 7 + y], [9 + x, 17 + y], 2)
    pygame.draw.line(D, PINDLER, [5 + x, 7 + y], [1 + x, 17 + y], 2)

def MOLINE3(D, x, y):
    pygame.draw.ellipse(D, BLACK, [1 + x, y, 10, 10], 0)

    pygame.draw.line(D, BLACK, [5 + x, 17 + y], [10 + x, 27 + y], 2)
    pygame.draw.line(D, BLACK, [5 + x, 17 + y], [x, 27 + y], 2)

    pygame.draw.line(D, PINDLER, [5 + x, 17 + y], [5 + x, 7 + y], 2)

    pygame.draw.line(D, PINDLER, [5 + x, 7 + y], [9 + x, 17 + y], 2)
    pygame.draw.line(D, PINDLER, [5 + x, 7 + y], [1 + x, 17 + y], 2)

def MOLINE4(D, x, y):
    pygame.draw.ellipse(D, BLACK, [1 + x, y, 10, 10], 0)

    pygame.draw.line(D, BLACK, [5 + x, 17 + y], [10 + x, 27 + y], 2)
    pygame.draw.line(D, BLACK, [5 + x, 17 + y], [x, 27 + y], 2)

    pygame.draw.line(D, PINDLER, [5 + x, 17 + y], [5 + x, 7 + y], 2)

    pygame.draw.line(D, PINDLER, [5 + x, 7 + y], [9 + x, 17 + y], 2)
    pygame.draw.line(D, PINDLER, [5 + x, 7 + y], [1 + x, 17 + y], 2)

def MOLINE5(D, x, y):
    pygame.draw.ellipse(D, BLACK, [1 + x, y, 10, 10], 0)

    pygame.draw.line(D, BLACK, [5 + x, 17 + y], [10 + x, 27 + y], 2)
    pygame.draw.line(D, BLACK, [5 + x, 17 + y], [x, 27 + y], 2)

    pygame.draw.line(D, PINDLER, [5 + x, 17 + y], [5 + x, 7 + y], 2)

    pygame.draw.line(D, PINDLER, [5 + x, 7 + y], [9 + x, 17 + y], 2)
    pygame.draw.line(D, PINDLER, [5 + x, 7 + y], [1 + x, 17 + y], 2)

def FINISH(D, x, y):
    R(D, BLACK, ( 4, 42, 6, 6))
    R(D, WHITE, (10, 42, 6, 6))
    R(D, BLACK, (16, 42, 6, 6))
    R(D, WHITE, (22, 42, 6, 6))
    R(D, BLACK, (28, 42, 6, 6))
    R(D, WHITE, (34, 42, 6, 6))

    R(D, WHITE, ( 4, 48, 6, 6))
    R(D, BLACK, (10, 48, 6, 6))
    R(D, WHITE, (16, 48, 6, 6))
    R(D, BLACK, (22, 48, 6, 6))
    R(D, WHITE, (28, 48, 6, 6))
    R(D, BLACK, (34, 48, 6, 6))

    R(D, BLACK, ( 4, 54, 6, 6))
    R(D, WHITE, (10, 54, 6, 6))
    R(D, BLACK, (16, 54, 6, 6))
    R(D, WHITE, (22, 54, 6, 6))
    R(D, BLACK, (28, 54, 6, 6))
    R(D, WHITE, (34, 54, 6, 6))

x_speed = 0
y_speed = 0

x2_speed = 0
y2_speed = 0

x3_speed = 0
y3_speed = 0

x4_speed = 0
y4_speed = 0

x_coord = 300
y_coord = 300

x2_coord = 300
y2_coord = 300

x3_coord = 300
y3_coord = 300

x4_coord = 300
y4_coord = 300

X5_coord = 30
Y5_coord = 10

direction = 'right'

clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_speed =- 3
                x2_speed = 3
                y3_speed =- 3
                y4_speed = 3
            elif event.key == pygame.K_RIGHT:
                x_speed = 3
                x2_speed =- 3
                y3_speed = 3
                y4_speed =- 3
            elif event.key == pygame.K_UP:
                y_speed =- 3
                y2_speed = 3
                x3_speed =- 3
                x4_speed = 3
            elif event.key == pygame.K_DOWN:
                y_speed = 3
                y2_speed =- 3
                x3_speed = 3
                x4_speed =- 3
            elif event.key == pygame.K_TAB:
                GMT += 1
                CIP = 2
                if GMT % 2:
                    GM = 2
                else:
                    GM = 1

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                x_speed=0
                x2_speed=0
                y3_speed=0
                y4_speed=0
            elif event.key == pygame.K_RIGHT:
                x_speed=0
                x2_speed=0
                y3_speed=0
                y4_speed=0
            elif event.key == pygame.K_UP:
                y_speed=0
                y2_speed=0
                x3_speed=0
                x4_speed=0
            elif event.key == pygame.K_DOWN:
                y_speed=0
                y2_speed=0
                x3_speed=0
                x4_speed=0

        elif event.type == MOUSEBUTTONDOWN:
            x_coord = 300
            y_coord = 300
            x2_coord = 300
            y2_coord = 300
            x3_coord = 300
            y3_coord = 300
            x4_coord = 300
            y4_coord = 300
            X5_coord = 30
            Y5_coord = 10
            direction = 'right'
            D.fill(BLACK)
            G = random.randrange(1, 10)
            CO = 2
            V = 2

        elif event.type == MOUSEBUTTONUP:
            X5_coord = 30
            Y5_coord = 10
            direction = 'right'

        if direction == 'right':
            X5_coord += 10
            if X5_coord == 670:
                direction = 'down'
        elif direction == 'down':
            Y5_coord += 10
            if Y5_coord == 460:
                direction = 'left'
        elif direction == 'left':
            X5_coord -= 10
            if X5_coord == 10:
                direction = 'up'
        elif direction == 'up':
            Y5_coord -= 10
            if Y5_coord == 10:
                direction = 'right'
        print(V, event, event.type, event_500ms, V == 2, event.type == event_500ms, Blue)
        if V == 2:
            if event.type == event_500ms:
                if Blue == 1:
                    D.fill(BLUE)
                    Blue = 2
                elif Blue == 2:
                    D.fill(YELLOW)
                    Blue = 1

    if V != 2:
        x_coord = x_coord + x_speed
        y_coord = y_coord + y_speed

        x2_coord = x2_coord + x2_speed
        y2_coord = y2_coord + y2_speed

        x3_coord = x3_coord + x3_speed
        y3_coord = y3_coord + y3_speed

        x4_coord = x4_coord + x4_speed
        y4_coord = y4_coord + y4_speed

        if GM == 2 and CIP == 2:
            D.fill(BLACK)
            CIP = 1

        if GM == 1:
            D.fill(MEXON)

        if G >= 6:
            B(L6, (80, 150))

        if G == 1 and CO == 2:
            x_coord = 366
            y_coord = 201

            x2_coord = 234
            y2_coord = 399

            x3_coord = 201
            y3_coord = 366

            x4_coord = 399
            y4_coord = 234

            CO = 1

        elif G == 2 and CO == 2:
            x_coord = 240
            y_coord = 312

            x2_coord = 360
            y2_coord = 288

            x3_coord = 312
            y3_coord = 240

            x4_coord = 288
            y4_coord = 360

            CO = 1

        elif G == 3 and CO == 2:
            x_coord = 405
            y_coord = 228

            x2_coord = 195
            y2_coord = 372

            x3_coord = 228
            y3_coord = 405

            x4_coord = 372
            y4_coord = 195

            CO = 1

        elif G == 4 and CO == 2:
            x_coord = 179
            y_coord = 309

            x2_coord = 421
            y2_coord = 291

            x3_coord = 309
            y3_coord = 179

            x4_coord = 291
            y4_coord = 421

            CO = 1

        elif G == 5 and CO == 2:
            x_coord = 315
            y_coord = 450

            x2_coord = 285
            y2_coord = 150

            x3_coord = 450
            y3_coord = 315

            x4_coord = 150
            y4_coord = 285

            CO = 1

        elif G == 6 and CO == 2:
            x_coord = 180
            y_coord = 390

            x2_coord = 420
            y2_coord = 210

            x3_coord = 390
            y3_coord = 180

            x4_coord = 210
            y4_coord = 420

            CO = 1

        elif G == 7 and CO == 2:
            x_coord = 267
            y_coord = 204

            x2_coord = 333
            y2_coord = 396

            x3_coord = 204
            y3_coord = 267

            x4_coord = 396
            y4_coord = 333

            CO = 1

        elif G == 8 and CO == 2:
            x_coord = 363
            y_coord = 390

            x2_coord = 237
            y2_coord = 210

            x3_coord = 390
            y3_coord = 363

            x4_coord = 210
            y4_coord = 237

            CO = 1

        elif G == 9 and CO == 2:
            x_coord = 234
            y_coord = 273

            x2_coord = 366
            y2_coord = 327

            x3_coord = 273
            y3_coord = 234

            x4_coord = 327
            y4_coord = 366

            CO = 1

        elif G == 10 and CO == 2:
            x_coord = 102
            y_coord = 267

            x2_coord = 498
            y2_coord = 333

            x3_coord = 267
            y3_coord = 102

            x4_coord = 333
            y4_coord = 498

            CO = 1

        B(L1, (47, 45))
        B(L2, (47, 60))
        B(L2C, (65, 75))
        B(L3, (47, 90))
        B(L4, (47, 105))
        B(L5, (47, 120))

        L(D, PINDLER, (40, 5), (695, 5), 10)
        L(D, PINDLER, (3, 42), (3, 495), 10)
        L(D, PINDLER, (3, 495), (695, 495), 10)
        L(D, PINDLER, (695, 495), (695, 5), 10)

        L(D, PINDLER, (3, 41), (658, 42), 10)
        L(D, PINDLER, (40, 5), (40, 458), 10)
        L(D, PINDLER, (40, 458), (658, 458), 10)
        L(D, PINDLER, (658, 458), (658, 42), 10)

        FINISH(D, Fx, Fy)

        MOLINE1(D, x_coord, y_coord)

        MOLINE2(D, x2_coord, y2_coord)

        MOLINE3(D, x3_coord, y3_coord)

        MOLINE4(D, x4_coord, y4_coord)

        MOLINE5(D, X5_coord, Y5_coord)

        pygame.draw.line(D, PINDLER, (303, 302), (307, 306), 1)
        pygame.draw.line(D, PINDLER, (307, 302), (303, 306), 1)

    pygame.display.flip()

    clock.tick(60)

pygame.quit()

rawDescription: Flash event ceases upon input

description: Flash event ceases upon input


code:
import numpy as np, pandas as pd

def fake_data(nids, nclusters, ntile):
    ids = ["i{}".format(i) for i in range(1,nids+1)]
    clusters = ["A{}".format(i) for i in range(nclusters)]
    df = pd.DataFrame(index=pd.MultiIndex.from_product([ids, clusters], names=["id", "cluster"]))
    df = df.reset_index()
    df = pd.concat([df]*ntile)
    df["count"] = np.random.randint(0, 10, size=len(df))
    return df

def join_group(g):
    m= pd.merge(g, g, on='dummy_key')
    return m[['cluster_x', 'count_x', 'cluster_y', 'count_y']]

def old_method(df):
    df["dummy_key"] = 1
    h1 = df.groupby(['id'], as_index=True).apply(join_group)
    h2 = h1.groupby(['cluster_x', 'cluster_y'], as_index=False)
    h3 = h2[['count_x', 'count_y']].sum()
    return h3

def new_method1(df):
    m1 = df.groupby("cluster", as_index=False)["count"].sum()
    m1["dummy_key"] = 1
    m2 = m1.merge(m1, on="dummy_key")
    m2 = m2.sort_index(axis=1).drop(["dummy_key"], axis=1)
    return m2

rawDescription: cogroup like operation for pandas

description: Cogroup like operation for pandas


code: np.concatenate([np.linspace(0, 2, 60), np.linspace(2, 10, 40)[1:]])

rawDescription: Stretched sections in plotting

description: Stretched sections in plotting


code:
clients_orders = db.Table('clients_orders',
    db.Column('client_id', db.Integer, db.ForeignKey('client.id'),
              primary_key=True),
    db.Column('order_id', db.Integer, db.ForeignKey('order.id'),
              primary_key=True)
)

class Client(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    orders = db.relationship('Order', secondary=clients_orders,
                             backref='clients')
    # Define other columns...

class Order(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    # Define other columns...

class Item(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    order_id = db.Column(db.Integer, db.ForeignKey('order.id'), nullable=False)
    order = db.relationship('Order', backref='items')
    timestamp = db.Column(db.DateTime)
    # Define other columns...

rawDescription: How to do two-level many-to-many relationships?

description: Do two-level many-to-many relationships


code:
def example():
    """
    @param x: This is a description of
        the parameter x to a function.
        Note that the description is
        indented four spaces.
    @type x: This is a description of
        x's type.
    @return: This is a description of
        the function's return value.

        It contains two paragraphs.
    """
    #[...]

rawDescription: What is this structured comment and what is "updated" field for?


code:
def func(group):
    mean, std = group.mean(), group.std()
    inliers = (group - mean).abs() <= 2*std
    tmp = group[inliers]
    return {"mean":tmp.mean(), "std":tmp.std(), "len":tmp.shape[0]}

g.c5.apply(func).unstack()

rawDescription: Remove outliers before aggregate in Python Pandas


code:
self.ci = []
for i in xrange(self.bands):
    self.ci.append(0)

rawDescription: Brackets in the statement. How does it work?


code:
for i in range(X.shape[0]):
    output[i][Y[i]] = X[i]

rawDescription: numpy 2D array assignment with 2D value and indices arrays

description: Numpy 2D array assignment with 2D value and indices arrays


code:
mylist = ['A', 'B', 'C', 'D'] # the full list
indices = [0, 3] # the indices of myList that you want to extract

# Now build and join a new list comprehension using only those indices.
partList = "".join([e for i, e in enumerate(mylist) if i in indices])
print(partList) # >>> AD

rawDescription: Python lists: join list by index

description: Python lists: join list by index


rawDescription: django-reversion how to get user-id

description: Django-reversion how to get user-id


code:
import scrapy
selector = scrapy.Selector(text='''
    <html>
    <element attr1="value1" attr2="value2">some text</element>
    </html>''')
selector.xpath('//element').xpath('name()').extract()

rawDescription: Getting name of attributes with Scrapy XPATH


code:
def setup_1():
    print('1')

def setup_2():
    print('2')

def setup_3():
    print('3')

if __name__ == '__main__':
    for func in (val for key,val in vars().items()
                 if key.startswith('setup_')):
        func()

rawDescription: Automatically call all functions matching a certain pattern in python


code:
unique_id_elmt = tree.find('*/*')  # First (and only) element two levels below the root
unique_id_elmt
unique_id_elmt.text  # Text contained in UniqueID

rawDescription: Using ElementTree to parse an XML string with a namespace


code:
while True:
    oanda = oandapy.API(environment="practice", access_token="xxxxxx")
    response = oanda.get_prices(instruments="EUR_USD")
    prices = response.get("prices")
    asking_price = prices[0].get("ask")
    s = asking_price - .001
    return s

rawDescription: Calling While loop Function in __main__?

description: Calling While loop Function in __main__


code:
s = '0\n'
s
s.strip()
s.split()
int(s.strip())

rawDescription: Convert integer within a list into a string to be written to a text file and later retrieved


rawDescription: Generating a list of tuples and using it


rawDescription: Python - find average for columns with unique matching value in nested list


code:
import glob
import csv
import os

file_list = glob.glob('*.csv')

output_folder = 'temp'  # make sure this folder exists

for file in file_list:
    file_name = os.path.join(output_folder, os.path.basename(file))
    with open(file, 'r') as f_input, open(file_name, 'w', newline='') as f_output:
        csv_input = csv.reader(f_input)
        csv_output = csv.writer(f_output)

        header = next(csv_input)
        first_row = next(csv_input)

        csv_output.writerow(header)
        csv_output.writerow(first_row)

        for row in csv_input:
            if row[0] == first_row[0]:
                if row[1] == first_row[1] or row[7] == '0':
                    csv_output.writerow(row)

rawDescription: How to search for the common records of one csv file to another csv file without using for loop

description: Search for the common records of one csv file to another csv file without using for loop


code:
from lxml.html import parse
page = parse("test.html")
rows = page.xpath("body/table")[0].findall("tr")
data = list()
for row in rows:
    data.append([c.text for c in row.getchildren()])

for row in data[4:]: print(row)

rawDescription: parsing HTML table using python - HTMLparser or lxml

description: Parsing HTML table using python - HTMLparser or lxml


code:
from django.conf.urls import url, patterns
from views import get_no_of_lines, line_form

urlpatterns = patterns('',
     url(r'^$', get_no_of_lines, name='get_no_of_lines'),
     url(r'^line_form/(?P<no_of_lines>\d{1})$', line_form, name='line_form'),
)

rawDescription: Django: how to change label using formset extra?


code:
MY_COLORS = enum(RED=0, BLUE=1)
MY_COLORS.keys()

rawDescription: python built-in function type, how to define a member function for the new type?

description: Python built-in function type, how to define a member function for the new type


code:
stt_value = soup.findAll('ln')[0]['stt'] # u'114'
end_value = soup.findAll('ln')[0]['end'] # u'142'

rawDescription: reading token on python

description: Reading token on python


code:
fn = lambda x: x**2 + 3*x - 4
fn(3)

rawDescription: Python function handle ala Matlab

description: Python function handle ala Matlab


code:
for i, line in enumerate(lines):
    lines[i] = '~$ ' + line

rawDescription: how to modify strings in a list of strings

description: Modify strings in a list of strings


code:
selected_full_paths = []
for selected_i in listbox.curselection():
    selected_text = listbox.get(i)
    full_path = files_to_show[selected_text]
    selected_full_paths.append(full_path)

rawDescription: Attach data element to tkinter Listbox element


rawDescription: How can obtain middle number with grid/step in Python


code:
# dimension of the problem (in this example I use 3D grid,
# but the method works for any dimension n>=2)
n = 3
# my array of grid points (array of n-dimensional coordinates)
points = [[1,2,3], [2,3,4], ...]
# each point has some assigned value that will be interpolated
# (e.g. a float, but it can be a function or anything else)
values = [7, 8, ...]
# a set of points at which I want to interpolate (it must be a NumPy array)
p = np.array([[1.5, 2.5, 3.5], [1.1, 2.2, 3.3], ...])

# create an object with triangulation
tri = Delaunay(points)
# find simplexes that contain interpolated points
s = tri.find_simplex(p)
# get the vertices for each simplex
v = tri.vertices[s]
# get transform matrices for each simplex (see explanation bellow)
m = tri.transform[s]

# for each interpolated point p, mutliply the transform matrix by
# vector p-r, where r=m[:,n,:] is one of the simplex vertices to which
# the matrix m is related to (again, see bellow)
b = np.einsum('ijk,ik->ij', m[:,:n,:n], p-m[:,n,:])

# get the weights for the vertices; `b` contains an n-dimensional vector
# with weights for all but the last vertices of the simplex
# (note that for n-D grid, each simplex consists of n+1 vertices);
# the remaining weight for the last vertex can be copmuted from
# the condition that sum of weights must be equal to 1
w = np.c_[b, 1-b.sum(axis=1)]

rawDescription: Interpolation with Delaunay Triangulation (n-dim)


code:
re.split('abc', 'abcabcabcabc')
re.split('bca', 'abcabcabcabc')
re.split('c', 'abcabcabcabc')
re.split('a', 'abcabcabcabc')

rawDescription: Python-Getting contents between current and next occurrence of pattern in a string


code:
if numbers[tiles[int(tile)]] not in collision_list:
    collision_list[numbers[tiles[int(tile)]]] = [tiles[int(tile)].rect]
else:
    collision_list[numbers[tiles[int(tile)]]].append(tiles[int(tile)].rect)

rawDescription: Add object to existing value in dictionary


code: sorted(L, key=lambda t: t[::-1])

rawDescription: Sorting a list of tuples with 3 elements in python


code:
class MyHandler(tornado.web.RequestHandler):

    def get_argument(self, name, minimum, maximum):
        argument = super(MyHandler, self).get_argument(name)
        if not minimum <= argument <= maximum:
            raise tornado.web.HTTPError(400)  # 400 Bad Request
        return argument

    def post(self):
        small_arg = self.get_argument('small_arg', 1, 3)
        medium_arg = self.get_argument('medium_arg', 7, 47)
        large_arg = self.get_argument('large_arg', 9001, 10000)

rawDescription: Tornado set minmum and maximum values for get_argument


code:
# labels = ["USER1", "USER2", ...]
plt.rcParams["figure.figsize"] = (8, 6 * len(labels) / 10)

rawDescription: How to adjust the distance between y-axis label in python

description: Adjust the distance between y-axis label in python


code:
df['ID'] = df['col1']
df = df.drop('col1',axis=1)
df['col1'] = (df.groupby('ID').cumcount() + 1)

rawDescription: How to use an input column as a major index in hierarchical indexing in pandas?

description: Use an input column as a major index in hierarchical indexing in pandas


code:
from lxml import etree

f = """<root>
  <trigger name="trigger_a">
    <config_a>10</config_a>
    <config_b>4</config_b>
    <config_c>true</config_c>
  </trigger>
  <trigger name="trigger_b">
    <config_a>11</config_a>
    <config_b>5</config_b>
    <config_c>false</config_c>
  </trigger>
</root>"""

tree = etree.XML(f)
# uncomment the next line if you want to parse a file
# tree = etree.parse(file_object)

def getTriggerConfig(myname):
   # here "tree" is hardcoded, assuming it is available in the function scope. You may add it as parameter, if you like.
   elements = tree[0].xpath("//trigger[@name=$name]/*", name = myname)
   # If reading from file uncomment the following line since parse() returns an ElementTree object, not an Element object as the string parser functions.
   #elements = tree.xpath("//trigger[@name=$name]/*", name = myname)
   for child in elements:
       print("Config %s is: %s"%(child.tag[7:], child.text))

rawDescription: Get values from xml file using lxml

description: Get values from xml file using lxml


code:
import nltk
tag = nltk.pos_tag(['Google'])
tag
tag[0][1]
tag[0][1] is 'NNP'
tag[0][1] == 'NNP'

rawDescription: How do I check for a certain tag in Python NLTK?

description: Check for a certain tag in Python NLTK


rawDescription: Append items from Y list to one specific list from X list Python


rawDescription: read data from file, store in a python dict and search for values in python

description: Read data from file, store in a python dict and search for values in python


code:
import sys
import unicodedata as ud
import re
import argparse
import functools

__usage__ = '''\
unicode_lookup.py -u '\d'    # Shows all unicode symbols that regex match '\d'
unicode_lookup.py number     # Shows all unicode symbols whose name regex matches 'number'
'''

def lookup(name_pat=None, from_num=0, to_num=0x10ffff, unicode_pattern=None,
           category_pattern=None, ignore_unnamed=True,
           combining=False):
    fmt = u"{symbol} {num} {cat} {bi} {w} {comb} {mir} '{name}'"
    print(fmt.format(
        symbol='Symbol', num='Num', name='NAME',
        cat='Category', bi='Bidirectional', w='Width',
        comb='Combining', mir='Mirrored'))
    for num in range(from_num, to_num + 1):
        s = unichr(num)
        if unicode_pattern and not unicode_pattern.match(s):
            continue
        category = ud.category(s)
        if category_pattern and not category_pattern.match(category):
            continue
        try:
            name = ud.name(s)
            if name_pat and not name_pat.search(name):
                continue
        except ValueError:
            if ignore_unnamed:
                continue
            else:
                name = '?'
        bidirectional = ud.bidirectional(s)
        combining_class = ud.combining(s)
        if combining and not combining_class:
            continue
        mirrored = ud.mirrored(s)
        width = ud.east_asian_width(s)
        data = dict(num=num, symbol=s, name=name,
                    cat=category, bi=bidirectional, w=width,
                    comb=combining_class, mir=mirrored)
        print(fmt.format(**data).encode('utf-8'))

def parse_options():
    parser = argparse.ArgumentParser(
        epilog=__usage__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('name_pat',
                        type=functools.partial(re.compile, flags=re.IGNORECASE))
    parser.add_argument('-f', '--from_num', default=0, type=int)
    parser.add_argument('-t', '--to_num', default=0x10ffff, type=int)
    parser.add_argument('-u', '--unicode_pattern',
                        type=functools.partial(re.compile, flags=re.UNICODE))
    parser.add_argument('--category_pattern', type=re.compile)
    parser.add_argument('--show_unnamed', action='store_true')
    parser.add_argument('--combining', action='store_true')
    return parser.parse_args()

if __name__ == '__main__':
    opt = parse_options()
    lookup(name_pat=opt.name_pat, from_num=opt.from_num, to_num=opt.to_num,
           unicode_pattern=opt.unicode_pattern,
           category_pattern=opt.category_pattern,
           ignore_unnamed=not opt.show_unnamed,
           combining=opt.combining)

rawDescription: Python Regex and the Copyright Symbol

description: Python Regex and the Copyright Symbol


code:
kwargs = {'name': 'a name', 'mapper': 'mapper name', 'combiner': 'combiner name'}
boto.emr.step.StreamingStep(**kwargs)

rawDescription: how to skip argument in python when call method

description: Skip argument in python when call method


rawDescription: Python 2.7 Convert Letters to Phone Numbers


code:
import cherrypy
class HelloWorld(object):
    def index(self):
        return "Hello World!"
    index.exposed = True

cherrypy.quickstart(HelloWorld())

rawDescription: Can you display python web code in Joomla?

description: Display python web code in Joomla


code:
def each_context(self):
        """
        Overriden dictionary of variables returned for
        *every* page in the admin site.
        """
        return {
            'site_title': self.site_title,
            'site_header': self.site_header,
            'srv_time': "%s" % datetime.datetime.now(),
        }

rawDescription: Django: Admin template shows old values after page refresh


code:
[['2925729', 'Patrick came outside and greeted us promptly.'],
 ['2925729', 'Patrick did not shake our hands nor ask our names'],
 ['2925729', 'He greeted us promptly and politely, but it seemed routine.'],
 ['2925728', 'Patrick sucks'],
 ['2925728', 'He farted politely, but it seemed routine.']]

rawDescription: Convert list into sub-list while maintaining "key"


code:
import xml.sax,csv
def getType(filename):
  with open(filename, 'rb') as fh:
    try:
      xml.sax.parse(fh, xml.sax.ContentHandler())
      return 'xml'
    except: # SAX' exceptions are not public
      pass
    fh.seek(0)

    try:
      for line in csv.reader(fh):
        pass
      return 'csv'
    except csv.Error:
      pass

    return 'txt'

rawDescription: Python to check if a gzipped file is xml or csv


rawDescription: Dot product sparse matrices

description: Dot product sparse matrices


code:
def filterRow(row):
    row = list(row)
    while row[-1] == "":
        row.pop()
    return row

rawDescription: How to remove leftmost/rightmost elements in list that satisfy a certain criterion in python?

description: Remove leftmost/rightmost elements in list that satisfy a certain criterion in python


rawDescription: Slicing a Pandas DataFrame using 2 compound indexes


code:
import xml.etree.ElementTree as xee
data='''\
<node1>
  <node2 a1="x1"> ... </node2>
  <node2 a1="x2"> ... </node2>
  <node2 a1="x1"> ... </node2>
</node1>
'''
doc=xee.fromstring(data)

for tag in doc.findall('node2'):
    if tag.attrib['a1']=='x2':
        doc.remove(tag)
print(xee.tostring(doc))
# <node1>
#   <node2 a1="x1"> ... </node2>
#   <node2 a1="x1"> ... </node2>
# </node1>

rawDescription: xml filtering with python

description: Xml filtering with python


code:
friendship_ids = [{'id1': name_to_id[f['name1']], 'id2': name_to_id[f['name2']]}
                  for f in friendships]

rawDescription: Python/MySQL get data from table based on values in a dictionary


rawDescription: Turn NumPy Array of characters into a string


code:
import calendar
_MONTH_MAP = {m.lower(): i for i, m in enumerate(calendar.month_name[1:])}
def sort_month_names_key(m_name):
    return _MONTH_MAP[m_name.lower()]

rawDescription: Sorting Numericly and by Month name

description: Sorting Numericly and by Month name


code: acceptableChars = set('abcdefghi')

rawDescription: If string can be composed of certain characters?


code:
from django import template
register = template.Library()
@register.filter
def convert_units(value, user_pref):
    #You probably want to use that library you found here to do conversions
    #instead of what i've used.
    if user_pref == "met":
        return str(value) + " Kilometers"
    else:
        return str(float(value)/ 1.60934) + " Miles"

rawDescription: Concept of different systems of measurement in Django project


code:
a = one[1]
a
a + a

rawDescription: How do I take an integer from a list intending to use it?

description: Take an integer from a list intending to use it


code:
x=[1,2,3,4]
y=x
y is x
y=x[:]     # this makes a copy of x and assigns that copy to y,
y is x     # y & x now point to different object, so changing one will not affect the other.

rawDescription: Copying arrays in python and manipulating one


code: df.groupby( [df.index.year, df.index.month, df.index.day] ).count()

rawDescription: counting records on per hour, per day and create multindex DataFrame as output

description: Counting records on per hour, per day and create multindex DataFrame as output


code:
a_game = Game("central_corridor")
a_game.play()

rawDescription: Please help understanding how the 'return' statement is used in this example


code: parser.unescape('        "python - питон, прорицатель",')

rawDescription: How to decode 'xmlcharrefreplace' ascii to UTF-8 in python3?

description: Decode 'xmlcharrefreplace' ascii to UTF-8 in python3


code:
a = {"success":1,"data":{"var1":1,"var2":2,"var3":3}}
a["data"]["var2"]
locals().update(a["data"])
var2

rawDescription: how to make child of a list become a variable in python

description: Make child of a list become a variable in python


code:
# provide a unique name for each image file
def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    return "%s.%s" % (uuid.uuid4(), ext.lower())

# store the original images in the 'photos/original' directory
photoStorage = FileSystemStorage(
    location=os.path.join(settings.MEDIA_ROOT, 'photos/original'),
    base_url='/photos/original')

class Photo(models.Model):
    image = models.ImageField(storage=photoStorage, upload_to=get_file_path)
    thumb = ImageSpecField(
        source='image',
        id='myapp:thumbnail')

rawDescription: Django Imagekit overwrite cachefile_name?


code:
thing1 = list.select('h1/text()').extract()[0]
if thing1.strip():
    ...

rawDescription: Scrapy - how to prevent output lines with blank element?


code:
a_string ="""CPU Temp        | 26.000     | degrees C  | ok
            System Temp      | 23.000     | degrees C  | ok
            Peripheral Temp  | 30.000     | degrees C  | ok
            PCH Temp         | 42.000     | degrees C  | ok"""

a_dict  = {key.strip():float(temp.strip()) for key, temp, *rest in map(lambda v: v.split('|'), a_string.splitlines())}

print(a_dict)

rawDescription: How do I parse a multiline string into a python dict?

description: Parse a multiline string into a python dict


code: import resources

rawDescription: Importing resource file to PyQt code?

description: Importing resource file to PyQt code


code:
from flask import Flask
from flask.ext.cache import Cache
import time
import lxml.html
import urllib2

app = Flask(__name__)

cache = Cache(config={'CACHE_TYPE': 'simple'})
cache.init_app(app)

@cache.cached(timeout=86400, key_prefix='content')
def get_content():
    app.logger.debug("get_content called")
#    return lxml.html.fromstring(urllib2.urlopen('http://daybarr.com/wishlist').read())
    return urllib2.urlopen('http://daybarr.com/wishlist').read()

@app.route("/")
def index():
    app.logger.debug("index called")
    return "get_content returned: {0!r}\n".format(get_content())

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

rawDescription: Using Flask-Cache to cache a lxml.html object


code:
def parse_block(block):
    gen = iter(block)
    block_name = next(gen).strip()[1:-1]
    splitted = [e.split('=') for e in gen]
    values = {t[0].strip(): t[1].strip() for t in splitted if len(t) == 2}
    return block_name, values

result = [parse_block(b) for b in blocks]

rawDescription: Parsing specific contents in a file

description: Parsing specific contents in a file


code: [i for i,j,k in os.walk('/path/to/directory/') if i.split("/")[-1].startswith(X)]

rawDescription: Python: How can i find a directory that matches the first 3 characters from a string?


code:
sys.stdout.write('\r  \r')
sys.stdout.write(str(seconds))

rawDescription: How to replace string from previous line using \r (Python)

description: Replace string from previous line using \r (Python)


code: near_indexes = _near_vectors2( near_vectors( vects ) )

rawDescription: How to pull together vectors with common components in a list?

description: Pull together vectors with common components in a list


code:
matrix = {}
for f in FooVal.objects().all():
    matrix[(f.line,f.col)] = f

for line in someRangeOfLines:
    for col in someRangeOfCols:
        cell= matrix.get((line,col),None)

rawDescription: outer join modelisation in django

description: Outer join modelisation in django


code:
import pandas as pd

df = pd.read_csv('f123.csv')
df['Time'] = df['Time'].apply(lambda x: x.split(':')[0] + ':00')
by_hour = df.groupby('Time')
data = {}
for name in ['F1', 'F2', 'F3']:
    data['SUM ' + name] = by_hour[name].sum()
    data['AVG ' + name] = by_hour[name].mean()
res = pd.DataFrame(data)
print(res)

rawDescription: How group by sum and average column in python?


rawDescription: Rolling standard deviation using parts of data in dataframe with Pandas


code:
import wx
import random
import os, sys
from wx.lib.agw import ultimatelistctrl as ULC

class TestUltimateListCtrl(ULC.UltimateListCtrl):
    def __init__(self, parent, log):
        ULC.UltimateListCtrl.__init__(self, parent, -1, agwStyle=ULC.ULC_VIRTUAL|ULC.ULC_REPORT|ULC.ULC_SINGLE_SEL|ULC.ULC_VRULES|ULC.ULC_HRULES)
        self.SetItemCount(1000)
        self.table_fields=['First','Second','Third']
        field_index=0
        for field in self.table_fields:
            info = ULC.UltimateListItem()
            info._mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT | ULC.ULC_MASK_CHECK
            info._image = []
            info._format = wx.LIST_FORMAT_CENTER
            info._kind = 1
            info._text = field
            info._font= wx.Font(13, wx.ROMAN, wx.NORMAL, wx.BOLD)
            self.InsertColumnInfo(field_index, info)
            self.SetColumnWidth(field_index,175)
            field_index += 1

        self.checked = []
        self.Bind(ULC.EVT_LIST_ITEM_CHECKING, self.OnCheck)

    def OnCheck(self, event):
        item_column = (event.m_itemIndex, event.m_item.GetColumn())
        try:
            idx = self.checked.index(item_column)
        except ValueError:
            idx = None

        if idx == None:
            self.checked.append(item_column)
        else:
            del(self.checked[idx])
        self.Refresh()

    def getColumnText(self, index, col):
        item = self.GetItem(index, col)
        return item.GetText()

    def OnGetItemText(self, item, col):
        return "Item %d, Column %d" % (item,col)

    def OnGetItemColumnImage(self, item, col):
        return []

    def OnGetItemImage(self, item):
        return []

    def OnGetItemAttr(self, item):
        return None

    def OnGetItemTextColour(self, item, col):
        return None

    def OnGetItemToolTip(self, item, col):
        return None

    def OnGetItemKind(self, item):
        return 1

    def OnGetItemColumnKind(self, item, col):
        if col==0:
            return self.OnGetItemKind(item)
        return 0

    def OnGetItemColumnCheck(self, item, column):
        item_column = (item, column)
        if item_column in self.checked:
            return True
        else:
            return False

class TestFrame(wx.Frame):
    def __init__(self, parent, log):
        wx.Frame.__init__(self, parent, -1, "UltimateListCtrl in wx.LC_VIRTUAL mode", size=(700, 600))
        panel = wx.Panel(self, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        listCtrl = TestUltimateListCtrl(panel, log)
        sizer.Add(listCtrl, 1, wx.EXPAND)
        panel.SetSizer(sizer)
        sizer.Layout()
        self.CenterOnScreen()
        self.Show()

if __name__ == '__main__':
    import sys
    app = wx.PySimpleApp()
    frame = TestFrame(None, sys.stdout)
    frame.Show(True)
    app.MainLoop()

rawDescription: Item Checking not possible with UltimateListCtrl in ULC_VIRTUAL mode


rawDescription: Python - extending properties like you'd extend a function


code:
age = np.array([np.nan, 30, 20, 10])
(age > 20.0).astype(float)
np.clip(age-20, 0, 1)

rawDescription: Assigning numpy array based on condition


rawDescription: How can I get python logging.debug() messages to output to standard output?

description: Get python logging.debug() messages to output to standard output


code:
def parse_items(self, response):
  str = ""
  hxs = HtmlXPathSelector(response)

  for titles in titles:
      item = CraigslistSampleItem()
      item ["job_id"] = id.select('text()').extract()[0].strip() #this should work if #there is some string data available. otherwise it will give an index out of range error.
      items.append(item)
  return(items)
end

rawDescription: remove white space using strip()

description: Remove white space using strip()


rawDescription: numpy: column-wise dot product

description: Numpy: column-wise dot product


code:
result = np.dot(M,M)
result = np.dot(result,result)

rawDescription: Matrix power for sparse matrix in python


code:
for button, filename, label in mapping:
    button.clicked.connect(lambda filename=filename, label=label: self.loadfiles(filename,label))

rawDescription: Calling the same function in pyqt when any button is clicked


code:
mylist = ['A', 'B', 'C', 'D']
x = '1'
ix = [False, True, False, True]
[value + x if flag else value for value, flag in zip(mylist, ix)]

rawDescription: Concatenating some string elements in a list with a given string


code:
alphabet
bee
house
part
wine

rawDescription: Find if a String is in Ascending order (Lexicographically)


code:
def __e_default(self): # note preceding underscore
    return ExternalModel()

rawDescription: How can I wrap a non-Traits model for use with Python Traits?

description: Wrap a non-Traits model for use with Python Traits


code:
import subprocess

some_path = ...
subprocess.call(["hadoop", "fs", "-rm", "-f", some_path])

rawDescription: pyspark and HDFS commands

description: Pyspark and HDFS commands


rawDescription: Python: nested lists, extend & delete elements


code:
def view(request) :
  msg = '<img src="http://example.com/pretty.jpg" />This picture is very pretty'

rawDescription: Django Double Escaping Quotes etc

description: Django Double Escaping Quotes etc


code:
[[u'\n  Foo ', u'Bar'],
 [u'\n  Baz'],
 [u'\n  ', u'Foobar', u' Quux\n']]

rawDescription: Scrapy selector for nodes between <br /> tags


code:
import pandas as pd
df = pd.read_csv('sample.csv', converters={'ID': str})

rawDescription: How to write tweet IDs to a CSV file as strings

description: Write tweet IDs to a CSV file as strings


code:
m = __import__('sys')
m.path

rawDescription: import userinputed string as a module in python

description: Import userinputed string as a module in python


rawDescription: how to convert xml into list

description: Convert xml into list


rawDescription: Hex grid in ncurses

description: Hex grid in ncurses


code:
All_my_lists=[]
for key in My_list:
   All_my_lists.append(My_list[key])

rawDescription: Python: Merging dictionary lists

description: Python: Merging dictionary lists


code:
# server2.py

from zmq.eventloop import ioloop
from zmq.eventloop.zmqstream import ZMQStream

def print_msg(msg):
    print("received %r" % ' '.join(msg))
    if msg[0] == 'quit':
        ioloop.IOLoop.instance().stop()

# register the print_msg callback to be fired
# whenever there is a message on our socket
stream = ZMQStream(s)
stream.on_recv(print_msg)

# do other things in the meantime
tic = time.time()
def do_other_things():
    print("%.3f" % (time.time() - tic))

pc = ioloop.PeriodicCallback(do_other_things, 1000)
pc.start()

# start the eventloop
ioloop.IOLoop.instance().start()

rawDescription: PyZMQ one-way communication

description: PyZMQ one-way communication


code:
def read_all(self,count=-1):
    """return a list of all packets in the pcap file
    """
    res=[]
    while count != 0:
        count -= 1
        p = self.read_packet()
        if p is None:
            break
        res.append(p)
    return res

rawDescription: How to read .cap files other than Pyshark that is faster than Scapy's rdpcap ()?

description: Read .cap files other than Pyshark that is faster than Scapy's rdpcap ()


rawDescription: Writing methods that accept either a single item or an iterable in Python


rawDescription: Loading key value pairs from a file to mongodb in Python


code:
def sliced_sum(a, b, c) :
    cum = np.cumsum(a, axis=1)
    cum = np.hstack((np.zeros((a.shape[0], 1), dtype=a.dtype), cum))
    rows = np.arange(a.shape[0])
    return cum[rows, c] - cum[rows, b]

rawDescription: Sum between pairs of indices in 2d array


code:
class EditBaseForm(TemplateView):
    template_name = 'some_edit.html'

    def dispatch(self, request, *args, **kwargs):
        self.object1 = get_object_or_404(SomeModel1, pk=kwargs.get('model1_pk'))
        self.object2 = get_object_or_404(SomeModel2, pk=kwargs.get('model2_pk'))
        # and so on

        return super(EditBaseForm, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(EditBaseForm, self).get_context_data(**kwargs)
        if not (context.get('form1') and context.get('form2')):  # actually you can check only first of them
            context['form1'] = FormClass1(instance=self.object1)
            context['form2'] = FormClass2(instance=self.object2)

        return context

    def post(self, request, *args, **kwargs):
        form1 = FormClass1(request.POST, request.FILES, instance=self.object1)
        form2 = FormClass2(request.POST, request.FILES, instance=self.object2)

        if form1.is_valid() and form2.is_valid():
            return self.form_valid(form1, form2)
        else:
            return self.form_invalid(form1, form2)

    def form_valid(self, form1, form2):
        form1.save()
        form2.save()

        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form1, form2):
        return self.render_to_response(
            self.get_context_data(
                form1=form1,
                form2=form2,
            )
        )

    def get_success_url(self):
        return reverse('some_app:some_url')

rawDescription: Django: Handling several forms in one submit, using class based views?


code:
import threading
import queue
import time
queue = queue.Queue()

class Client():
    def write_message(self,msg):
        print(msg)
clients=[Client()]

jobdone=object()
def Consumer():
    while True:
        json = queue.get()
        if json is jobdone:
            break;
        clients[0].write_message(json)

t = threading.Thread(target=Consumer);
t.start()
queue.put("Hello")
queue.put("Word")
time.sleep(2)
queue.put(jobdone)

t.join()
#You can use also q.join()
print("Job Done")

rawDescription: In Producer/Consumer pattern, how could I kill the consumer thread?


rawDescription: Pandas: How to apply a function to different columns


code:
new_driver = webdriver.PhantomJS()
new_driver.set_window_size(800, 450)
new_driver.get("http://www.pudim.com.br/")

rawDescription: Switch window on Selenium

description: Switch window on Selenium


code:
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run

rawDescription: I have got the "Authorization code" for my app. But how can I use it to post in the blogger using gdata-python-client?