code:
import wx

class Frame ( wx.Frame ):

    def __init__( self, parent ):
        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u"Test", pos = wx.DefaultPosition, size = wx.Size( -1,-1 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )

        sizer0 = wx.BoxSizer( wx.VERTICAL )

        self.scrolledWindow = wx.ScrolledWindow( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.HSCROLL|wx.VSCROLL )
        self.scrolledWindow.SetScrollRate( 5, 5 )
        grid_sizer = wx.GridSizer( 0, 8, 0, 0 )

        self.head1 = wx.StaticText( self.scrolledWindow, wx.ID_ANY, u"Code", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.head1.Wrap( -1 )
        grid_sizer.Add( self.head1, 0, wx.ALL, 5 )

        self.head2 = wx.StaticText( self.scrolledWindow, wx.ID_ANY, u"Classification", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.head2.Wrap( -1 )
        grid_sizer.Add( self.head2, 0, wx.ALL, 5 )

        self.head3 = wx.StaticText( self.scrolledWindow, wx.ID_ANY, u"A", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.head3.Wrap( -1 )
        grid_sizer.Add( self.head3, 0, wx.ALL, 5 )

        self.head4 = wx.StaticText( self.scrolledWindow, wx.ID_ANY, u"B", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.head4.Wrap( -1 )
        grid_sizer.Add( self.head4, 0, wx.ALL, 5 )

        self.head5 = wx.StaticText( self.scrolledWindow, wx.ID_ANY, u"C", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.head5.Wrap( -1 )
        grid_sizer.Add( self.head5, 0, wx.ALL, 5 )

        self.head6 = wx.StaticText( self.scrolledWindow, wx.ID_ANY, u"D", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.head6.Wrap( -1 )
        grid_sizer.Add( self.head6, 0, wx.ALL, 5 )

        self.head7 = wx.StaticText( self.scrolledWindow, wx.ID_ANY, u"Cond.", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.head7.Wrap( -1 )
        grid_sizer.Add( self.head7, 0, wx.ALL, 5 )

        self.head8 = wx.StaticText( self.scrolledWindow, wx.ID_ANY, u"Update", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.head8.Wrap( -1 )
        grid_sizer.Add( self.head8, 0, wx.ALL, 5 )

        self.column11 = wx.StaticText( self.scrolledWindow, wx.ID_ANY, u"86", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.column11.Wrap( -1 )
        grid_sizer.Add( self.column11, 0, wx.ALL, 5 )

        self.column12 = wx.StaticText( self.scrolledWindow, wx.ID_ANY, u"Urban", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.column12.Wrap( -1 )
        grid_sizer.Add( self.column12, 0, wx.ALL, 5 )

        self.column13 = wx.StaticText( self.scrolledWindow, wx.ID_ANY, u"68", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.column13.Wrap( -1 )
        grid_sizer.Add( self.column13, 0, wx.ALL, 5 )

        self.column14 = wx.StaticText( self.scrolledWindow, wx.ID_ANY, u"80", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.column14.Wrap( -1 )
        grid_sizer.Add( self.column14, 0, wx.ALL, 5 )

        self.column15 = wx.StaticText( self.scrolledWindow, wx.ID_ANY, u"86", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.column15.Wrap( -1 )
        grid_sizer.Add( self.column15, 0, wx.ALL, 5 )

        self.column16 = wx.StaticText( self.scrolledWindow, wx.ID_ANY, u"89", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.column16.Wrap( -1 )
        grid_sizer.Add( self.column16, 0, wx.ALL, 5 )

        self.column17 = wx.StaticText( self.scrolledWindow, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
        self.column17.Wrap( -1 )
        grid_sizer.Add( self.column17, 0, wx.ALL, 5 )

        radio1Choices = [ u"G", u"P", u"F" ]
        self.radio1 = wx.RadioBox( self.scrolledWindow, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, radio1Choices, 3, wx.RA_SPECIFY_COLS )
        self.radio1.SetSelection( 0 )
        grid_sizer.Add( self.radio1, 0, wx.ALL, 5 )

        self.scrolledWindow.SetSizer( grid_sizer )
        self.scrolledWindow.Layout()
        grid_sizer.Fit( self.scrolledWindow )
        sizer0.Add( self.scrolledWindow, 1, wx.EXPAND |wx.ALL, 5 )

        # Bind the radio box select event to a function
        self.radio1.Bind( wx.EVT_RADIOBOX, self.on_selected )

        self.SetSizer( sizer0 )
        self.Layout()
        self.Maximize()
        self.Centre( wx.BOTH )
        self.Show()

    def on_selected(self, event):
        # Depending upon the option selected the values of A,B,C,D are changed
        if  self.radio1.GetStringSelection() == 'P':
            self.column13.SetLabel('25')
            self.column14.SetLabel('27')
            self.column15.SetLabel('34')
            self.column16.SetLabel('12')
        elif self.radio1.GetStringSelection() == 'F':
            self.column13.SetLabel('56')
            self.column14.SetLabel('70')
            self.column15.SetLabel('49')
            self.column16.SetLabel('54')
        else:
            self.column13.SetLabel('78')
            self.column14.SetLabel('83')
            self.column15.SetLabel('69')
            self.column16.SetLabel('100')

if __name__ == "__main__":
        app = wx.App()
        Frame(None)
        app.MainLoop()

rawDescription: Radio button display and selection issue in wxPython


code:
sql = """
    INSERT INTO raw_financials (provider, vendor_id)
    SELECT provider, %s
    FROM main_app_provider
    WHERE provider LIKE %s
    """
args = (vendor_id, '%'+provider+'%')
cursor.execute(sql, args)

rawDescription: For INSERT, using LIKE statement with a variable


code:
import numpy
data = numpy.fromfile('./allpoints.txt', dtype=float, count=-1, sep=' ')
data = numpy.reshape(data, (len(data) / 2, 2))
print(data[0:10])

rawDescription: numpy loadtxt takes so much time

description: Numpy loadtxt takes so much time


code:
class Scrip_Master(models.Model):
    nse_markt_typ = models.ForeignKey(MDfile, blank=True, null=True)

class Scrip_MasterAdmin(admin.ModelAdmin):
   ...
   search_fields = ['nse_markt_typ__mkt_type', ...]

rawDescription: Search field is not not working

description: Search field is not not working


rawDescription: Get values in Python dictionary from list of keys


code: volume(eval('lambda x: %s' % args.equation), args.a, args.b)

rawDescription: How to take a function as an argument? (Python)

description: Take a function as an argument? (Python)


rawDescription: Python list comprehension, unpacking and multiple operations


code:
class Foo(object):
    @property
    def property(self):
        return "ham"

    @property
    def other_property(self):
        return "spam"

rawDescription: Using 'property' as the name of a method in a python class


rawDescription: A better way to get count from foreign keys in Django ORM


code:
class GSpam:

   def _predict(self, text, from_='original'):
       if from_ == 'original':
          return "Something very different"
       else:
          return "Content for %s" % from_

   @cherrypy.expose
   def main(self,contents=""):
       return self._predict(contents, 'main')

   @cherrypy.expose
   def alt(self):
       return """

           <form method="post" action="predict">
            <input type="text" value="Enter post to check" name="text" />
            <button type="submit">Predict!</button>
           </form>

       """

   @cherrypy.expose
   def predict(self, text):
       #do some stuff
       result = self._predict(text)
       return result

rawDescription: Cherrypy handling requests differently

description: Cherrypy handling requests differently


code: [''.join(l) for l in list_of_lists]

rawDescription: 'List of lists' to 'list' without losing empty lists from the original list of lists


code: key=lambda x: abs(x._norm - number)

rawDescription: sorting a list of object based on an instance that is nearest to a number python

description: Sorting a list of object based on an instance that is nearest to a number python


code:
# Untested, although it should give you an idea of what to do

class ChildFrame(wx.Frame):

    def __init__(self, parent, id=-1, title="Default Frame", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE):
        wx.Frame.__init__(self, parent, id, title, pos, size, style)
        self._parent = parent

        self.Bind(wx.EVT_CLOSE, self.OnClose)

    def OnClose(self, event):
        # display your parent frame
        self._parent.Show()

rawDescription: Control three frames from main menu

description: Control three frames from main menu


code:
import re

pattern = re.compile(r'^A1.8301$')
matches = [x for x in yourlist if pattern.match(x)]

rawDescription: Compare strings in python like the sql "like" (with "%" and "_")


code:
df = DataFrame(dict(A = range(5)))
df
df.query('A>3')
df.eval('A>3')

rawDescription: Pandas: Getting the mask associated with query


rawDescription: Extract data from a website's list, without superfluous tags


code:
import collections

def get_code(list_of_urls):
    result = collections.defaultdict(list)
    for n in list_of_urls:
        code = code_number(n)
        result[code].append(n)
    return result

rawDescription: dictionary that return website status code as key and website as value - py

description: Dictionary that return website status code as key and website as value - py


code:
import win32com.client
import re

# This is the regular expression to match the text you are after
regexp = "Label: [0-9A-Z-]+"

def replace_label(word_file):
    app = win32com.client.DispatchEx("Word.Application")
    app.Visible = 0
    app.DisplayAlerts = 0
    app.Documents.Open("C:\\" + word_file)
    try:
        doc = app.ActiveDocument
        # Iterate over all the paragraphs
        for parNo in range(1,doc.Paragraphs.Count):
            paragraph = doc.Paragraphs(parNo)
            # Get the text of the paragraph.
            current_text = paragraph.Range.Text
            # Check if there is a match in the paragraph
            if re.search(regexp,current_text):
                # We found a match... do the replace
                paragraph.Range.Text = re.sub(regexp,"Label _______",current_text)
    finally:
        app.ActiveDocument.Close(SaveChanges=True)
        app.Quit()

rawDescription: Selecting and deleting a Line Present in a Word Document Using Python / Win32


code:
means = numpy.array([x[y == i].mean(axis=0) for i in xrange(1, 5)])
means

rawDescription: Numpy: mean calculation results in nan values


rawDescription: Compare cells of dataframe where another cell is same for multiple columns?


code:
""" Strip comments and docstrings from a file.
"""

import sys, token, tokenize

def do_file(fname):
    """ Run on just one file.

    """
    source = open(fname)
    mod = open(fname + ",strip", "w")

    prev_toktype = token.INDENT
    first_line = None
    last_lineno = -1
    last_col = 0

    tokgen = tokenize.generate_tokens(source.readline)
    for toktype, ttext, (slineno, scol), (elineno, ecol), ltext in tokgen:
        if 0:   # Change to if 1 to see the tokens fly by.
            print("%10s %-14s %-20r %r" % (
                tokenize.tok_name.get(toktype, toktype),
                "%d.%d-%d.%d" % (slineno, scol, elineno, ecol),
                ttext, ltext
                ))
        if slineno > last_lineno:
            last_col = 0
        if scol > last_col:
            mod.write(" " * (scol - last_col))
        if toktype == token.STRING and prev_toktype == token.INDENT:
            # Docstring
            mod.write("#--")
        elif toktype == tokenize.COMMENT:
            # Comment
            mod.write("##\n")
        else:
            mod.write(ttext)
        prev_toktype = toktype
        last_col = ecol
        last_lineno = elineno

if __name__ == '__main__':
    do_file(sys.argv[1])

rawDescription: Script to remove python comments/docstrings


code:
import csv

def import_incidents(filename):
    with open(filename, 'r', newline='') as file:
        reader = csv.DictReader(file)
        for row in reader:
            if not row or not row['Policies']:
                continue
            row['Incident Time'] = re.sub('GMT-0600', '', row['Incident Time'])
            yield row

rawDescription: CSV to List of Dictionaries - Better Way?


rawDescription: How to get a list with elements that are contained in two other lists?

description: Get a list with elements that are contained in two other lists


code:
import atexit
from apscheduler.schedulers.background import BackgroundScheduler

scheduler = BackgroundScheduler()
scheduler.start()
scheduler.add_job(print_greetings,
    id='greetings',
    name='Send out birthday greetings',
    trigger='cron',
    minute=0,
    hour=12,
)

atexit.register(lambda: scheduler.shutdown())

rawDescription: Python Pyramid periodic task

description: Python Pyramid periodic task


rawDescription: How to give the max item of a dictionary given a value somewhere in an array in the value?

description: Give the max item of a dictionary given a value somewhere in an array in the value


code:
class Meta:
    unique_together = ("form", "field")

rawDescription: Django: strategy for preventing duplicate object creation


code:
html = """

                    Zazzafooky but one two three!

                    Zazzafooky2

                    Zazzafooky3

"""
html = "".join(line.strip() for line in html.split("\n"))
html

rawDescription: How to remove whitespace in BeautifulSoup

description: Remove whitespace in BeautifulSoup


code: popt, pcov = curve_fit(func, x, yn, p0=(1./np.std(yn), np.argmax(yn) ,0,0,1))

rawDescription: scipy.optimize.curve_fit unable to fit shifted skewed gaussian curve

description: Scipy.optimize.curve_fit unable to fit shifted skewed gaussian curve


code:
conn = boto.connect_s3(AWS_ACCESS_KEYXXX, AWS_SECRET_KEYXXX)
bucket = conn.get_bucket(AWS_BUCKET_NAMEXXX)
k = Key(bucket)
k.key = s3_file_name
k.set_metadata('Content-Type', 'image/jpeg')
k.set_contents_from_file(file_obj)

rawDescription: How to upload a base64 encoded string to s3 and access the url in html file in python

description: Upload a base64 encoded string to s3 and access the url in html file in python


code:
from open_facebook.api import OpenFacebook
graph = OpenFacebook(access_token)
graph.get('%s/likes' % facebook_id)
graph.fql('SELECT ... FROM like WHERE post_id = A and user_id = B')

rawDescription: How to check user facebook likes/post in django

description: Check user facebook likes/post in django


code:
if __name__ == "__main__":
    objx=HtmlTemplate()
    objx.Header()
    objx.Body()
    objx.Form()
    objx.Footer()
    objx.CloseHtml()

rawDescription: importing class and its function from another file

description: Importing class and its function from another file


rawDescription: Algorithm to match 2 lists with wildcards


code:
def num_after_point(x):
    s = str(x)
    if not '.' in s:
        return 0
    return len(s) - s.index('.') - 1

rawDescription: Find the number of digits after the decimal point


code:
d = {'mean': 2, 'sum': 4, 'max': 6}
var1 = "max"
var2 = d[var1]
var2

rawDescription: Set python variable conditionally

description: Set python variable conditionally


code:
def _test():
    testfiles = [arg for arg in sys.argv[1:] if arg and arg[0] != '-']
    if not testfiles:
        name = os.path.basename(sys.argv[0])
        if '__loader__' in globals():          # python -m
            name, _ = os.path.splitext(name)
        print("usage: {0} [-v] file ...".format(name))
        return 2
    for filename in testfiles:
        if filename.endswith(".py"):
            # It is a module -- insert its dir into sys.path and try to
            # import it. If it is part of a package, that possibly
            # won't work because of package imports.
            dirname, filename = os.path.split(filename)
            sys.path.insert(0, dirname)
            m = __import__(filename[:-3])
            del sys.path[0]
            failures, _ = testmod(m)
        else:
            failures, _ = testfile(filename, module_relative=False)
        if failures:
            return 1
    return 0

if __name__ == "__main__":
    sys.exit(_test())

rawDescription: Run doctest on text file from .py file?

description: Run doctest on text file from .py file


code:
import numpy as np
array_a = np.random.rand(10,2)
array_b = np.random.permutation(range(10))

array_c = np.empty(array_a.shape, array_a.dtype)
for i in range(10):
    array_c[array_b[i], 0] = array_a[i, 0]
    array_c[array_b[i], 1] = array_a[i, 1]

rawDescription: transform code from matlab to python

description: Transform code from matlab to python


code:
m = np.zeros((6,6))
for row, col, val in a:
   m[row - 1, col - 1] = val

rawDescription: Create matrix by indices from text file in Python


code:
def name2dict(name_list):
    name_list_tuple = tuple(name_list)
    conn = pymysql.connect()
    cur = conn.cursor()
    Name2pos = """SELECT Tables.ID, Tables.Position FROM Tables where Tables.Name in %s"""
    cur.execute(Name2pos)
    query_dict = dict(cur.fetchall())
    cur.close()
    conn.close()
    return query_dict

rawDescription: How to get a dictionary of data in column1 as key and column2 as the value?

description: Get a dictionary of data in column1 as key and column2 as the value


rawDescription: Groups for M2M object based permissions

description: Groups for M2M object based permissions


code:
from ctypes import c_ubyte, Structure

class VendorRecord(Structure):
    _fields_ = [("vendorListNumber", c_ubyte * 5),
                ("vendorNumber", c_ubyte * 5)]

rawDescription: Python Structure elements as arrays

description: Python Structure elements as arrays


rawDescription: Applying string functions to elements that can be NaN


code:
def action1():
    pass # put a function here

def action2():
    pass # blah blah

def action3():
    pass # and so on

def no_such_action():
    pass # print a message indicating there's no such action

def main():
    actions = {"foo": action1, "bar": action2, "baz": action3}
    while True:
        print_menu()
        selection = raw_input("Your selection: ")
        if "quit" == selection:
            return
        toDo = actions.get(selection, no_such_action)
        toDo()

if __name__ == "__main__":
    main()

rawDescription: Suggestion to implement a text Menu without switch case


code:
from tkinter import *
import tkinter.ttk

category = {'home': ['utilities','rent','cable'],
    'car': ['gas','oil','repairs'],
    'rv':['parks','maintenance','payment']}

class Application(Frame):

    def __init__(self, master=None, Frame=None):
        Frame.__init__(self, master)
        super(Application,self).__init__()
        self.grid(column = 5,row = 20,padx = 50,pady = 50)
        self.createWidgets()

    def getUpdateData(self,  event):
        self.AccountCombo['values'] = category[self.CategoryCombo.get()]

    def createWidgets(self):
        Label(text = 'Combo Box #1:').grid(row = 2,column = 1,padx = 10)
        Label(text = 'Combo Box #2:').grid(row = 4,column = 1,padx = 10)
        self.AccountCombo = tkinter.ttk.Combobox( width = 15)
        self.AccountCombo.grid(row = 5,column = 1,pady = 25,padx = 10)

        self.CategoryCombo = tkinter.ttk.Combobox(width = 15,  values = list(category.keys()))
        self.CategoryCombo.bind('<<ComboboxSelected>>', self.getUpdateData)
        self.CategoryCombo.grid(row = 3,column = 1,padx = 10,pady = 25)

app = Application()
app.master.title('Yearly Budget Setup')
app.mainloop()

rawDescription: How do you populate a Combobox based on the selection of another Combobox?

description: Populate a Combobox based on the selection of another Combobox


code:
def get_account_data(account):
    fields = serializers.serialize('python', [account, ])[0]['fields']
    return {field: str(fields[field]) for field in fields}

rawDescription: Django model as part of Ajax response

description: Django model as part of Ajax response


code:
import numpy
a = numpy.arange(6).reshape(1,2,3)
a
list(numpy.ndenumerate(a))

rawDescription: Iterate over numpy matrix of unknown dimension


code:
from django.db import connection

user.user_profile.games_liked.all()
Game.objects.filter(likes=user)._as_sql(connection)

print(connection.queries)

rawDescription: Django: Which database call is faster/better?


code:
def __contains__(self, w):
    if self._is_special(w):
        return self._special_rule(w)
    return super().__contains__(w)

rawDescription: Overloading operators for custom types in Python


code: [re.sub(r'[@-]',r'',i) if ' ' in i else i for i in List1]

rawDescription: Removing Certain character of a element from list


code:
import re
valid = re.match('^[\w-]+$', str) is not None

rawDescription: How do I check if a string only contains alphanumeric characters and dashes?

description: Check if a string only contains alphanumeric characters and dashes


code:
import Classes.PositionWindow

p = Classes.PositionWindow.PositionWindow()

p.Center()

rawDescription: Importing a class and calling a method

description: Importing a class and calling a method


code:
library(RCurl)
library(jsonlite)

payloadObject <- list(request = "/v1/balances",
                      nonce = "1417217972400792",
                      options = {})
payload_json <- toJSON(payloadObject)
payload <- base64(payload_json)

rawDescription: Python code to R

description: Python code to R


code:
def clusters(array,
             orig_indices = None,
             start = 0,
             rtol=numpy.allclose.__defaults__[0],
             atol=numpy.allclose.__defaults__[1]):
    """For an array, return a permutation that sorts the numbers and the sizes of the resulting blocks of identical numbers."""
    array = numpy.asarray(array)
    if not len(array):
        return numpy.array([]),[]
    if orig_indices is None:
        orig_indices = numpy.arange(len(array))
    x = array[0]
    close = abs(array-x) <= (atol + rtol*abs(x))
    first = sum(close)
    r_perm, r_sizes = clusters(
        array[~close],
        orig_indices[~close],
        start+first,
        rtol, atol)
    r_sizes.insert(0, first)
    return numpy.concatenate((orig_indices[close], r_perm)), r_sizes

def permutation_matrix(permutation, dtype=dtype):
    n = len(permutation)
    P = numpy.zeros((n,n), dtype)
    for i,j in enumerate(permutation):
        P[j,i]=1
    return P

def simultaneously_diagonalize(tensor, atol=numpy.allclose.__defaults__[1]):
    tensor = numpy.asarray(tensor)
    old_shape = tensor.shape
    size = old_shape[-1]
    tensor = tensor.reshape((-1, size, size))
    diag_mask = 1-numpy.eye(size)

    eigvalues, diagonalizer = numpy.linalg.eig(tensor[0])
    diagonalization = numpy.dot(
        numpy.dot(
            matrix.linalg.inv(diagonalizer),
            tensor).swapaxes(0,-2),
        diagonalizer)
    if numpy.allclose(diag_mask*diagonalization, 0):
        return diagonalization.diagonal(axis1=-2, axis2=-1).reshape(old_shape[:-1])
    else:
        perm, cluster_sizes = clusters(diagonalization[0].diagonal())
        perm_matrix = permutation_matrix(perm)
        diagonalization = numpy.dot(
            numpy.dot(
                perm_matrix.T,
                diagonalization).swapaxes(0,-2),
            perm_matrix)
        mask = 1-scipy.linalg.block_diag(
            *list(
                numpy.ones((blocksize, blocksize))
                for blocksize in cluster_sizes))
        print(diagonalization)
        assert(numpy.allclose(
                diagonalization*mask,
                0)) # Assert that the matrices are co-diagonalizable
        blocks = numpy.cumsum(cluster_sizes)
        start = 0
        other_part = []
        for block in blocks:
            other_part.append(
                simultaneously_diagonalize(
                    diagonalization[1:, start:block, start:block]))
            start = block
        return numpy.vstack(
            (diagonalization[0].diagonal(axis1=-2, axis2=-1),
             numpy.hstack(other_part)))

rawDescription: Simultaneously diagonalize matrices with numpy


code: any(cell.update_type(next_cells[cell.index]) for cell in cells)

rawDescription: python map object methods

description: Python map object methods


rawDescription: Convert planar x/y to lat/long

description: Convert planar x/y to lat/long


code:
def make_unique(self, item, ln):
    ln_count = Letter.objects.filter(item=item, letter__startswith=ln+'_').count() + 1
    unique_ln = "{ln}_{count}".format(ln = ln, count = ln_count)
    return unique_ln

rawDescription: Django > form > is_unique()

description: Django > form > is_unique()


rawDescription: Python tkinter .pack/.pack_forget memory issue


code: lines = list(open(description, 'r'))

rawDescription: Read lines from txt python

description: Read lines from txt python


code:
import alotoffunc

class MixinAbc:
    def abc(self, x):
        return alotoffunc.abc(self, x)

class MixinEfg:
    def efg(self, x):
        return alotoffunc.efg(self, x)

class MixinKlm:
    def klm(self, x, y):
        return alotoffunc.klm(self, x, y)

class ObjectI(MixinAbc, MixinEfg):
    pass

class ObjectII(MixinEfg, MixinKlm):
    pass

class ObjectXI(MixinAbc, MixinKlm):
    pass

rawDescription: Creating classes with a lot of imported functions here and there


code:
import subprocess
import os.path
import argparse #requires Python 2.7 or above

parser = argparse.ArgumentParser(description='Converts (.M4V) videos into (.MP3) audio files using ffmpeg.')
parser.add_argument('-d','--directory', help='Source directory name',required=True)
parser.add_argument('-o','--output',help='Output directory name', required=False)
parser.add_argument('-a','--arate',help='ffmpeg\'s arate option', default="64K", required=False)
parser.add_argument('-s','--source',help='Input type; e.g., file ext (default .m4v)', default=".m4v", required=False)
parser.add_argument('-e','--ext',help='Output type; e.g., file ext (default .mp3)', default=".mp3", required=False)
parser.add_argument('-p','--program',help='application program e.g., /usr/bin/ffmpeg', default="/usr/bin/ffmpeg", required=False)
args = parser.parse_args()

arate = args.arate
source = args.source
new_ext = args.ext
prog = args.program
in_path = args.directory

if(not args.output):
    out_path = in_path
else:
    out_path = args.output

if(not os.path.isfile(prog)):
    print("Command {} does not exist".format(prog))

else:
    try:
        filenames = os.listdir(in_path)
        for file in filenames:
            name, extension = os.path.splitext(file)
            if(extension == source):
                print("Processing: {}".format(file))
                inf = os.path.join(in_path, file)
                outf = os.path.join(out_path, name + new_ext)
                process = subprocess.Popen([prog, "-i", inf, "-b:a", arate, "-vn", outf], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
                stdout,stderr = process.communicate()
                return_code = process.poll()
                print("stdout='{}'\nstderr='{}'\nreturn_code='{}'".format(stdout, stderr, return_code))
            else:
                print("Skipping: {}".format(file))

    except IOError as e:
        print("Error: file not found.")

rawDescription: Passing parameters to Python subprocess.Popen


code:
last4 = str(number)[-4:]
if last4.startswith(('10', '02')):
    print("yes, actually")

rawDescription: Regex how to check last 4 numbers from long number


code:
db = SQLAlchemy(app)
db.create_all()

rawDescription: Flask-SQLAlchemy - When are the tables/databases created and destroyed?


code:
# Here, enumerate gives back the index and element.
for i,file_name in enumerate(sorted(os.listdir(full_subdir_name))):
    full_file_name = os.path.join(full_subdir_name,file_name)

    # Here, 'elem' will be the strings naming the actual
    # files inside of the folders.

    for elem in sorted(os.listdir(full_file_name)):
        # Here I am assuming you don't want to append the full path,
        # but you can easily change what to append by adding the
        # whole current file path: os.path.join(full_file_name, elem)

        namelist[i+1].append(elem)

rawDescription: python-read file names and build a namelist

description: Python-read file names and build a namelist


code:
ids = [1000032, 1000048]
sql = 'SELECT CompNo, CompName, CompType FROM Component WHERE DeptID IN ({0})'
sql = sql.format(','.join('?' * len(ids)))
cursor.execute(sql, (ids,))
...

rawDescription: Python list of ints in prepared sql statement


code:
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "http://example.com/"
password_mgr.add_password(None, top_level_url, 'user', 'password')
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(urllib2.HTTPHandler, handler)
request = urllib2.Request(url)

rawDescription: HTTP Authentication in Python

description: HTTP Authentication in Python


code:
def redirectOut(port=port, host=host):
    """
    connect caller's standard output stream to a socket for GUI to listen
    start caller after listener started, else connect fails before accept
    """
    sock = socket(AF_INET, SOCK_STREAM)
    sock.connect((host, port))                # caller operates in client mode
    file = sock.makefile('w')                 # file interface: text, buffered
    sys.stdout = file                         # make prints go to sock.send
    return sock                               # if caller needs to access it raw

rawDescription: Python. Redirect stdout to a socket

description: Python. Redirect stdout to a socket


code: submenu.add_command(label=p, command = lambda p=p: onButtonPosObject(p), underline=0)

rawDescription: python Tkinter: passing an argument to a function

description: Python Tkinter: passing an argument to a function


code: find_joke = re.search( r'\bjoke\b', sentence, re.M|re.I)

rawDescription: Python: regular expressions word match

description: Python: regular expressions word match


code:
class Book(Base):
    __tablename__ = 'books'

    book_id = Column(Integer, primary_key=True)
    title = Column(String(200), nullable=False)
    summary = Column(String(2000))
    excerpt = deferred(Column(Text))
    photo = deferred(Column(Binary))

rawDescription: Lazy loading of columns in sqlalchemy

description: Lazy loading of columns in sqlalchemy


code:
s = 'Find the most common letter in THIS sentence!'
letters = [letter.lower() for letter in s if letter.isalpha()]
max(set(letters), key=letters.count)

rawDescription: Same Python code returns different results for same input string


code:
import pandas as pd
df = pd.DataFrame({'food': ['eggs','eggs','ham','ham'],'co1':[20,19,20,21]})

for x in df.iterrows():
    #iterrows returns a tuple per record whihc you can unpack
    # X[0] is the index
    # X[1] is a tuple of the rows values so X[1][0] is the value of the first column etc.
    pd.DataFrame([x[1][1]]).to_csv(str(x[1][0])+".txt", header=False, index=False)

rawDescription: Write contents of dataframe to .txt files with one file per row?


code:
for filename in allfiles:
    if not os.isfile(filename): continue
    t = os.path.getmtime(filename)
    v = datetime.datetime.fromtimestamp(t)
    x = v.strftime( ' %d-%m-%Y')
    dirname = prefix + x + " " + str(count)
    target = os.path.join(dirname, filename)
    os.renames(filename, target)
    count +=1

rawDescription: Script to rename and copy files to a new directory.


rawDescription: Splitting 2 possibly negative numbers that are hyphenated


code:
import seaborn as sns
titanic = sns.load_dataset("titanic")
sns.countplot(y="deck", hue="class", data=titanic, palette="Greens_d",
              order=titanic.deck.value_counts().iloc[:3].index)

rawDescription: limit the number of groups shown in seaborn countplot?

description: Limit the number of groups shown in seaborn countplot


code:
status = None
counter = 5
while (status != 'ok' and counter > 0):
    status_response = ec2.describe_instance_status(
        DryRun=False,
        InstanceIds=[cye_production_web_server_2, ],
    )
    status = status_response['InstanceStatuses'][0]['SystemStatus']['Status']
    sleep(5)    # 5 second throttle
    counter=counter-1

print(status_response)
print('status is', status.capitalize())

rawDescription: AWS EC2: How to prevent infinite loop for instance status check?


code:
from tkinter import*

def onKeyDown(event):
    if(event.keysym == "Up"):
        canvas.move(rect, 0, -2)
    if(event.keysym == "Down"):
        canvas.move(rect, 0, 2)
    if(event.keysym == "Left"):
        canvas.move(rect, -2, 0)
    if(event.keysym == "Right"):
        canvas.move(rect, 2, 0)

def onClick1(event):
    canvas.itemconfigure(rect, fill="red");
def onClick2(event):
    canvas.itemconfigure(rect, fill="green");
def onClick3(event):
    canvas.itemconfigure(rect, fill="blue")

master = Tk()
canvas = Canvas(master, width=600, height=600)
canvas.pack()
rect = canvas.create_rectangle(250,250,350,350, fill="red")
canvas.update()

rrect = canvas.create_rectangle(0,0,30,30, fill="red")
grect = canvas.create_rectangle(33,0,60,30, fill="green")
brect = canvas.create_rectangle(63,0,90,30, fill="blue")

master.bind("<Key>", onKeyDown)

canvas.tag_bind(rrect,"<Button-1>", onClick1)
canvas.tag_bind(grect,"<Button-1>", onClick2)
canvas.tag_bind(brect,"<Button-1>", onClick3)

rawDescription: How would I make my movebal square change colors by clicking another square on my canvas?


code:
import csv
import os

processed_lines = set()
if os.path.exists('processed_lines.txt'):
    with open('processed_lines.txt') as lines_fp:
        processed_lines.update(int(line_no) for line_no in lines_fp)

with open('processed_lines.txt', 'a') as lines_fp, \
     open('holiday.txt', 'rb') as fp:
    for line_no, (category, url) in enumerate(csv.reader(fp), 1):
        if line_no not in processed_lines:
            # process the line
            # ...
            lines_fp.write(str(line_no)+'\n')  # add it to processed lines file

rawDescription: Delete Used Text Line Or Start From "X" Line Next Run?


code:
with open('goalkeepers.json','wb') as goalkeeper_file:
  json.dump(
    [player for player in data if player['POS'] == "G"],
    goalkeeper_file)

with open('outfielders.json','wb') as outfield_file:
  json.dump(
    [player for player in data if player['POS'] != "G"],
    outfield_file)

rawDescription: Scraping data and inputting it into two different tables


code:
import msgpack
s = msgpack.packb({"a":10,"b":13})
s
'\r' in s
'\n' in s

rawDescription: Python msgpack module: packb and newlines


code:
class TextWrapperDeux(TextWrapper):
    _wordsep_re = re.compile(
    r'((?<!`)\s+(?!`)|'                       # whitespace not between backticks
    r'(?<=\s)(?::[a-z-]+:)`\S+|'              # interpreted text start
    r'[^\s\w]*\w+[a-zA-Z]-(?=\w+[a-zA-Z])|'   # hyphenated words
    r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))')   # em-dash

    @property
    def wordsep_re(self):
        return self._wordsep_re

def char_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    """Describe a character given by unicode name.

    e.g., :char:`SPACE` -> "char:` `(U+00020 SPACE)"
    """
    try:
        character = nodes.unicodedata.lookup(text)
    except KeyError:
        msg = inliner.reporter.error(
            ':char: argument %s must be valid unicode name at line %d' % (text, lineno))
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]
    app = inliner.document.settings.env.app
    describe_char = "(U+%05X %s)" % (ord(character), text)
    char = nodes.inline("char:", "char:", nodes.literal(character, character))
    char += nodes.inline(describe_char, describe_char)
    return [char], []

def setup(app):
    app.add_role('char', char_role)

rawDescription: how to document a single space character within a string in reST/Sphinx?

description: Document a single space character within a string in reST/Sphinx


code:
class Pwr(object):

    def __init__(self):
        pass

    def poweron(self):
        pass

class Eqp(object):

    def __init__(self, pwr):
        self.pwr = pwr

    def poweron(self):
        self.pwr.poweron()

pwr = Pwr()
eq1 = Eqp(pwr)
eq2 = Eqp(pwr)

rawDescription: Create an object that has methods deferred to a different object for execution [Python]


code:
import tkMessageBox
from Tkinter import *

class App():
    def __init__(self):
        self.root = Tk()
        self.root.overrideredirect(1)
        self.frame = Frame(self.root, width=320, height=200,
                           borderwidth=2, relief=RAISED)
        self.frame.pack_propagate(False)
        self.frame.pack()
        self.bQuit = Button(self.frame, text="Quit",
                            command=self.root.quit)
        self.bQuit.pack(pady=20)
        self.bHello = Button(self.frame, text="Hello",
                             command=self.hello)
        self.bHello.pack(pady=20)

    def hello(self):
        tkMessageBox.showinfo("Popup", "Hello!")

app = App()
app.root.mainloop()

rawDescription: How can I create a borderless application in Python (windows)?

description: Create a borderless application in Python (windows)


code:
qry = meta.Session.query(model.EmpsTable).filter(model.EmpsTable
         .firstname.like(searchQuery))

return {'data': [
         {'file_id':record.file_id, 'filename':
            record.filename, 'links_to' :record.url}
        for record in qry
       ]}

rawDescription: How to return Sqlalchemy result as JSON?

description: Return Sqlalchemy result as JSON


code:
insert = "insert into {} (location, mode, process, status, title) values (%s, %s, %s, %s, %s)".format(self.params['tableName'])
cur.execute(insert, (location, transporterMode, "-", "Queued", self.title))

rawDescription: Python MySQL - MySQLdb - apostrophe in string breaks entry


code:
r = chain(hello.s(), hey.s())()

r.parent.get(timeout=1)
r.parent.parent.get(timeout=1)

first = r
while first.parent:
    first = first.parent

rawDescription: How to return the result of the first task from a celery chain?

description: Return the result of the first task from a celery chain


code: row = [unicode(x.strip()) for x in row if x]

rawDescription: Python: list comprehension, do f(x) if x exists?


rawDescription: Fullscreen Causes AttributeError in Python OpenCV


code:
with open('info.txt', 'r') as f:
      data = [line.split(',') for line in f]
print(sorted(data, key=lambda x: int(x[2])))

rawDescription: Sort Items by list element in python

description: Sort Items by list element in python


code:
from functools import total_ordering

@total_ordering
class PixelInfo(object):
    def __init__(self, r, g, b):
        self.r, self.g, self.b = r, g, b

    def __eq__(self, other):
        if not isinstance(other, type(self)): return NotImplemented
        return all(getattr(self, c) == getattr(other, c) for c in 'rgb')

    def __lt__(self, other):
        if not isinstance(other, type(self)): return NotImplemented
        return self.r + self.g + self.b < other.r + other.g + other.b

rawDescription: min-heap with custom data type Python?

description: Min-heap with custom data type Python


code:
def get_clip_corners(clip):
    hack_mesh = tvtk.api.tvtk.PolyData()
    clip.widget.widget._vtk_obj.GetPolyData(hack_mesh._vtk_obj)
    corners = hack_mesh.points.to_array()[:8, :]
    return corners, hack_mesh

def get_inside_mask(sep, data):
    is_in = numpy.zeros((data.shape[0],), dtype = numpy.bool)
    for (di, d) in enumerate(data):
        di_in = sep.is_inside_object(d[0], d[1], d[2])
        is_in[di] = di_in
    return is_in

def extract_points_inside_clip(clip, data):
    corners, mesh = get_clip_corners(clip)

    sep = tvtk.api.tvtk.SelectEnclosedPoints()
    sep.initialize(mesh)

    is_in = get_inside_mask(sep, data)
    data_in_box = data[is_in, :]
    return data_in_box

rawDescription: mayavi2: pythonic access from data_set_clipper filter

description: Mayavi2: pythonic access from data_set_clipper filter


code:
if start_date:
   p = p.filter(Post.date >= start_date)

if end_date:
   p = p.filter(Post.date <= end_date)

return p

rawDescription: sqlalchemy conditional multiple filters on dynamic lazy relationship

description: Sqlalchemy conditional multiple filters on dynamic lazy relationship


code:
while line:
    number += int(line)
    total += 1
    line = random_numbers.readline().rstrip("\n")

print("The total of the numbers: " + str(total))
print("Total count of numbers read from file: " + str(number))
more = input("Do you want to run again to write and read more numbers. (Y/N): ")

rawDescription: Random number file writer and read

description: Random number file writer and read


code:
from flask import request

with app.test_request_context('/hello', method='POST'):
    # now you can do something with the request until the
    # end of the with block, such as basic assertions:
    assert request.path == '/hello'
    assert request.method == 'POST'

rawDescription: How can I unit test this Flask app?

description: Unit test this Flask app


code:
with open("File1.txt") as fin1: lines = set(fin1.readlines())
with open("File2.txt") as fin2: lines.update(set(fin2.readlines()))
with open("file3.txt", 'w') as fout: fout.write('\n'.join(list(lines)))

rawDescription: How to perform an union of two files containing keywords in python?

description: Perform an union of two files containing keywords in python


code:
import numpy as np
import scipy.stats as stats

Array1 = np.random.random((100, 100, 10))
Array2 = np.random.random((100, 100, 10))
resultArray = np.ones(100*100).reshape(100,100)
for i in range(Array1.shape[0]):
        for j in range(Array1.shape[1]):
            slope, intercept, r_value, p_value, std_err = stats.linregress(
                Array1[i, j, :],
                Array1[i, j, :])
            R2 = r_value**2
            resultArray[ i , j ] = R2

print(resultArray)

rawDescription: Python 3D array. Calculate R squared

description: Python 3D array. Calculate R squared


code: list(list(itertools.combinations(list(range(5)), i)) for i in range(2, 5))

rawDescription: Python combination and permuation code

description: Python combination and permuation code


code:
from django.core import urlresolvers
from django.contrib.contenttypes.models import ContentType
from django.db import models

class MyModel(models.Model):

    def get_admin_url(self):
        content_type = ContentType.objects.get_for_model(self.__class__)
        return urlresolvers.reverse("admin:%s_%s_change" % (content_type.app_label, content_type.model), args=(self.id,))

rawDescription: Django - How to get admin url from model instance


code:
occurrences = {}
while True:
    words = input('Enter line: ')
    words = words.lower() #this is also where I have tried a split()
    if words =='':
        break
    for word in words.split():
        occurrences[word]=occurrences.get(word,0)+1
    for word in (occurrences):
        print(word, occurrences[word])

rawDescription: Word Frequency Counter Python

description: Word Frequency Counter Python


code: pylab.title('Minimal Energy Configuration of %s Charges on Disc W = %s'%(N, W))

rawDescription: Python: Using variables in Pylab Titles

description: Python: Using variables in Pylab Titles


code:
def splitResults(d1, d2):
    def splitter(val):
        # Pass val to d2 chain
        d2.callback(val)
        # Return val into d1's chain
        return val

    def splitterError(err):
        d2.errback(err)
    d1.addCallbacks(splitter, splitterError)

rawDescription: How do I attach two separate callbacks to a Twisted deferred, so both fire after the result is ready?

description: Attach two separate callbacks to a Twisted deferred, so both fire after the result is ready


code:
from pywinauto import application
app = application.Application.start("C:\\EnergyPlusV7-2-0\\EP-Launch.exe")
# open dialog here with pywinauto (see docs), it's bound to interface can't help here
# press next button

rawDescription: python, write a code to automatically execute an external program and use the method to execute the program's task

description: Python, write a code to automatically execute an external program and use the method to execute the program's task


code:
import os
dir, file = os.path.split(test_infile)
out_file_name = os.path.join(dir, 'test_outfile.csv')

rawDescription: Write to new non-existent file in same directory, Python 2.7


code:
import xlrd
import csv

def xls_to_csv():

    x =  xlrd.open_workbook('data.xls')
    x1 = x.sheet_by_name('Sheet1')
    csvfile = open('data.csv', 'wb')
    writecsv = csv.writer(csvfile, quoting=csv.QUOTE_ALL)

    for rownum in xrange(sh.nrows):
        writecsv.writerow(x1.row_values(rownum))

    csvfile.close()

rawDescription: Converting xls file into csv/txt file in Python


code:
# _*_ coding: utf-8

import xlsxwriter

workbook = xlsxwriter.Workbook('example.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write('B3', u'Französisch')

workbook.close()

rawDescription: How to write German language to a spreadsheet with xlsxwriter in Python

description: Write German language to a spreadsheet with xlsxwriter in Python


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import _png
from itertools import izip

def main():
    # We'll be saving the figure's background, so let's make it transparent.
    fig, ax = plt.subplots(facecolor='none')

    # You'll have to know the extent of the input beforehand with this method.
    ax.axis([0, 10, 0, 10])

    # We need to draw the canvas before we start adding points.
    fig.canvas.draw()

    # This won't actually ever be drawn. We just need an artist to update.
    col = ax.scatter([5], [5], color=[0.1, 0.1, 0.1], alpha=0.3)

    for xy, color in datastream(int(1e6), chunksize=int(1e4)):
        col.set_offsets(xy)
        col.set_color(color)
        ax.draw_artist(col)

    save(fig, 'test.png')

def datastream(n, chunksize=1):
    """Returns a generator over "n" random xy positions and rgb colors."""
    for _ in xrange(n//chunksize):
        xy = 10 * np.random.random((chunksize, 2))
        color = np.random.random((chunksize, 3))
        yield xy, color

def save(fig, filename):
    """We have to work around `fig.canvas.print_png`, etc calling `draw`."""
    renderer = fig.canvas.renderer
    with open(filename, 'w') as outfile:
        _png.write_png(renderer._renderer.buffer_rgba(),
                       renderer.width, renderer.height,
                       outfile, fig.dpi)

main()

rawDescription: Plotting a large number of points using matplotlib and running out of memory


code:
with open("SomeFileName.%s" % strDateForm, 'w+') as search_file:

    search_file.write("header: ")
    search_file.flush()

    proc = subprocess.Popen(['awk', '{sum+=$1} END {print sum}',"AnotherFileName" ], shell=False, stdout=search_file,stderr = subprocess.PIPE,close_fds = True)
    proc.wait()

    search_file.write("Header 2: ")
    search_file.flush()

    proc2 = subprocess.Popen(['awk', '{s+=$1} END {print s}',"AThirdFileName"], shell=False, stdout=search_file,stderr = subprocess.PIPE,close_fds = True)
    proc2.wait()

rawDescription: Multiple Subprocesses Printing to File

description: Multiple Subprocesses Printing to File


code:
import sys
import os
import random

class GrammarNaziError(SyntaxError):
    pass

class GrammarNaziImporter(object):
    def find_module(self, module_name, package_path):
        if package_path:
            search_paths = package_path
            module_name = module_name.split('.')[-1]

        else:
            search_paths = sys.path + [ '.' ]

        for i in search_paths:
            path = os.path.join(i, module_name)
            if os.path.isdir(path):
                path = os.path.join(path, '__init__.py')
            else:
                path += '.py'

            if os.path.exists(path):
                if not self.valid_syntax(path):
                    raise GrammarNaziError(
                        "The module %s failed Grammar Nazi Inspection" % path)

                break

    def valid_syntax(self, path):
        return random.randint(0, 10) # substitute with logic of your choice

rest = GrammarNaziImporter()
sys.meta_path.insert(0, rest)

rawDescription: Linting .py files run-time as they are loaded in Python


code:
times = race1.index.to_series()
today = pandas.Timestamp('00:00:00')
timedelta = times - today
times_ordinal = timedelta.dt.seconds/(24*60*60) + today.toordinal()
ax = times_ordinal.hist()
ax.xaxis_date()
plt.gcf().autofmt_xdate()
plt.ylabel('Number of finishers')

rawDescription: Histogram of times from a CSV via Pandas


code:
# Get 2D histogram.
H, xedges, yedges = np.histogram2d(x, y, range=rang, bins=binsxy)
# Get Gaussian filtered 2D histogram.
H1 = gaussian_filter(H, 2, mode='nearest')
# Get center of maximum in bin coordinates.
x_cent_bin, y_cent_bin = np.unravel_index(H1.argmax(), H1.shape)
# Get center in x,y coordinates.
x_cent_coor , y_cent_coord = np.average(xedges[x_cent_bin:x_cent_bin + 2]), np.average(yedges[y_cent_g:y_cent_g + 2])

rawDescription: Peak detection in a noisy 2d array

description: Peak detection in a noisy 2d array


rawDescription: Shift particular range of elements in list


code:
domain[i0] = nice.floor(x0);
domain[i1] = nice.ceil(x1);

rawDescription: What is the logic behind d3.js nice() ticks


code:
p1, = plt.plot(rv,'k-.',label='pdf')
plt.hist(series1,125,color='k',normed=1,histtype='step',label='hist 1',linestyle='dashed')
plt.hist(series2,125,color='k',normed=1,histtype='step',label='hist 2')

# plot lines that have the same formating as the histograms
p2, = plt.plot([0,0], label='hist 1',linestyle='dashed')
p3, = plt.plot([0,0],label='hist 2')

# create the legend
plt.legend([p1, p2, p3], ['pdf', 'hist 1', 'hist2'], loc='best')

# make the lines used in the legend invisible.
p2.set_visible(False)
p3.set_visible(False)

rawDescription: How to use alternative legend_handler for histogram

description: Use alternative legend_handler for histogram


code:
# convert yourmulti-dim indices to flat indices
flat_idx = np.ravel_multi_index((Px, Py), dims=a.shape)
# extract the unique indices and their position
unique_idx, idx_idx = np.unique(flat_idx, return_inverse=True)
# Aggregate the repeated indices
deltas = np.bincount(idx_idx, weights=x)
# Sum them to your array
a.flat[unique_idx] += deltas

rawDescription: Assigning identical array indices at once in Python/Numpy


code:
import xml.etree.ElementTree as ET

doc    = ET.parse("users.xml")
root = doc.getroot() #Returns the root element for this tree.
root_new  = ET.Element("person")
for child in root:
    name                = child.attrib['name']
    password             = child.attrib['password']

    user  = ET.SubElement(root_new, "user") # create subelement in cycle!
    user.set("username",name)               # username variable is not declared
    user.set("password",password)

tree = ET.ElementTree(root_new)
tree.write("new.xml")

import sys
tree.write(sys.stdout)

rawDescription: How to create a nodes every time i go through the loop in python

description: Create a nodes every time i go through the loop in python


rawDescription: matplotlib connecting wrong points in line graph

description: Matplotlib connecting wrong points in line graph


code:
self.resultsTable = Treeview(self.parent)
...
self.resultsTable.column("title", stretch=True, width=10)
self.resultsTable.column("artist", stretch=True, width=10)
self.resultsTable.column("length", stretch=True, width=10)
self.resultsTable.column("bitrate", stretch=True, width=10)
self.resultsTable.column("status", stretch=True, width=10)

rawDescription: tkinter: treeview bigger than grid cell

description: Tkinter: treeview bigger than grid cell


rawDescription: How do I add spaces in my program accordingly?

description: Add spaces in my program accordingly


code:
b = B()
b.__class__
b.__class__.__base__
b.__class__.__bases__
b.__class__.__base__.__subclasses__()

rawDescription: How can I work out the class hierarchy given an object instance in Python?

description: Work out the class hierarchy given an object instance in Python


code:
class MyTestCase(unittest.TestCase):
    def setUp(self):
        self.b = 8 #contrived example

    def testOne(self):
        with patch('totest.fn', return_value=self.b) as m:
            self.assertEqual(self.b, m())
            self.assertTrue(m.called)

    @patch("totest.fn")
    def testTwo(self,m):
        m.return_value = self.b
        self.assertEqual(self.b, m())
        self.assertTrue(m.called)

rawDescription: using self in python @patch decorator

description: Using self in python @patch decorator


code:
# your data:
my_dicts = [{'IS_DUMMY': False, 'FACT_CURRENCY': '$', 'RETAILER_NAME': 'kohls', 'RETAILER_KEY': 5, 'ACTIVE': 'Y'},{'IS_DUMMY': False, 'FACT_CURRENCY': '$', 'RETAILER_NAME': 'target', 'RETAILER_KEY': 100, 'ACTIVE': 'Y'}]
column_list = [{'SOURCE_COLUMN':'FACT_CURRENCY', 'TARGET_COLUMN':'CURRENCY'},{'SOURCE_COLUMN':'RETAILER_NAME', 'TARGET_COLUMN':'RETAILER'}, {'SOURCE_COLUMN':'RETAILER_KEY', 'TARGET_COLUMN':'KEY'},{'SOURCE_COLUMN':'ACTIVE', 'TARGET_COLUMN':'ACTIVE'}]

# seems like we only need the SOURCE_COLUMN entries from the column_list
source_cols = [col['SOURCE_COLUMN'] for col in column_list]

# iterate over my_dicts and create a new dictionary for each my_dict using
new_dicts = []
for my_dict in my_dicts:
    new_dicts.append({col:my_dict[col] for col in source_cols if col in my_dict})

rawDescription: How to get the key and value pair from a list of dictionary in python 3

description: Get the key and value pair from a list of dictionary in python 3


code:
from sqlalchemy import Column, Boolean, Integer

def c_id():
    return Column(Integer, primary_key=True)

def c_bool():
    return Column(Boolean, nullable=False, default=False)

def c_string(len):
    return Column(String(len), nullable=False, default='')

class Thing(Base):
    id = c_id()
    thing = c_bool()
    tag = c_string(255)

rawDescription: dynamic sqlalchemy columns on class

description: Dynamic sqlalchemy columns on class


code: '''This is a test {{ <-- escape these ---> }} and the value is {0}'''.format(42)

rawDescription: How to escape char in Python 3 ''' string?

description: Escape char in Python 3 ''' string


code:
from celery import task, subtask, group

@task
def get_list(amount):
    return [i for i in range(amount)]

@task
def process_item(item):
    # do stuff
    pass

@task
def dmap(it, callback):
    # Map a callback over an iterator and return as a group
    callback = subtask(callback)
    return group(callback.clone([arg,]) for arg in it)()

# runs process_item for each item in the return of get_list
process_list = (get_list.s(10) | dmap.s(process_item.s()))

rawDescription: How to chain a Celery task that returns a list into a group?

description: Chain a Celery task that returns a list into a group


code:
find = r'\]\n'
replace = r']'
text = re.sub(find, replace, text)

rawDescription: Using "r" with variables in re.sub

description: Using "r" with variables in re.sub


code:
from multiprocessing import Pool

def fetch_url(url):
    # Fetch the URL contents and save it anywhere you need and
    # return something meaningful (like filename or error code),
    # if you wish.
    ...

pool = Pool(processes=4)
result = pool.map(f, image_url_list)

rawDescription: How to do a non-blocking URL fetch in Python

description: Do a non-blocking URL fetch in Python


rawDescription: How do I use string formatting to show BOTH leading zeros and precision of 3?

description: Use string formatting to show BOTH leading zeros and precision of 3


code:
def lang(text):
    alist=text.split()
    kons="aeiouAEIOU"
    retText=""
    for word in alist:
        nytext=""
        for tkn in word:
            if not tkn in kons:
                nytext+=tkn
            else:
                nytext+=tkn
                retText += nytext*3 + " "
                break
        else:
            retText += word*3 + " "
    return retText

print(lang("This is good"))

rawDescription: How to repeat the first characters of every word in a sentence timed by three in python?

description: Repeat the first characters of every word in a sentence timed by three in python


code:
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
import Image

def plot(data, title):
    plot.i += 1
    plt.subplot(2,2,plot.i)
    plt.imshow(data)
    plt.gray()
    plt.title(title)
plot.i = 0

# Load the data...
im = Image.open('lena.png')
data = np.array(im, dtype=float)
plot(data, 'Original')

# A very simple and very narrow highpass filter
kernel = np.array([[-1, -1, -1],
                   [-1,  8, -1],
                   [-1, -1, -1]])
highpass_3x3 = ndimage.convolve(data, kernel)
plot(highpass_3x3, 'Simple 3x3 Highpass')

# A slightly "wider", but sill very simple highpass filter
kernel = np.array([[-1, -1, -1, -1, -1],
                   [-1,  1,  2,  1, -1],
                   [-1,  2,  4,  2, -1],
                   [-1,  1,  2,  1, -1],
                   [-1, -1, -1, -1, -1]])
highpass_5x5 = ndimage.convolve(data, kernel)
plot(highpass_5x5, 'Simple 5x5 Highpass')

# Another way of making a highpass filter is to simply subtract a lowpass
# filtered image from the original. Here, we'll use a simple gaussian filter
# to "blur" (i.e. a lowpass filter) the original.
lowpass = ndimage.gaussian_filter(data, 3)
gauss_highpass = data - lowpass
plot(gauss_highpass, r'Gaussian Highpass, $\sigma = 3 pixels$')

plt.show()

rawDescription: High Pass Filter for image processing in python by using scipy/numpy


code:
import numpy as np
A = np.arange(15).reshape(5,3)
A
u, s, v = np.linalg.svd(A)
S = np.diag(s)
S = np.vstack([S, np.zeros((2,3)) ])
#fill in zeros to get the right shape
np.allclose(A, np.dot(u, np.dot(S,v)))

rawDescription: Using numpy.linalg.svd on a 12 x 12 matrix using python


code:
def iequal(a, b):
   try:
      return a.upper() == b.upper()
   except AttributeError:
      return a == b

iequal(2, 2)
iequal(4, 2)
iequal("joe", "Joe")
iequal("joe", "Joel")

rawDescription: Ignore case in string comparison

description: Ignore case in string comparison


rawDescription: Realtime collaboration in Python

description: Realtime collaboration in Python


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

x = np.linspace(0,10,31)

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

#Plot analytic solution
ax.plot(x,1*x**2, color='r', label="t = 25")
ax.plot(x,2*x**2, color='b', label="t = 50")
ax.plot(x,3*x**2, color='g', label="t = 500")

#Plot simulation
ax.plot(x,1*x**2, color='r', linestyle='', marker='o')
ax.plot(x,2*x**2, color='b', linestyle='', marker='o')
ax.plot(x,3*x**2, color='g', linestyle='', marker='o')

#Get artists and labels for legend and chose which ones to display
handles, labels = ax.get_legend_handles_labels()
display = (0,1,2)

#Create custom artists
simArtist = plt.Line2D((0,1),(0,0), color='k', marker='o', linestyle='')
anyArtist = plt.Line2D((0,1),(0,0), color='k')

#Create legend from custom artist/label lists
ax.legend([handle for i,handle in enumerate(handles) if i in display]+[simArtist,anyArtist],
          [label for i,label in enumerate(labels) if i in display]+['Simulation', 'Analytic'])

plt.show()

rawDescription: How to make custom legend in matplotlib

description: Make custom legend in matplotlib


code:
#!/usr/bin/python
from matplotlib import cm
import matplotlib.pyplot as plt

#data
x=[1,2,4]
y=[11,12,8]

for i in range(0,len(x)):
  plt.bar(x[i],y[i],color=cm.jet(1.*i/len(x)))

plt.show()

rawDescription: How do I make bar plots automatically cycle across different colors?

description: Make bar plots automatically cycle across different colors


code:
from django.db.models import Count
theanswer = Item.objects.values('category').annotate(Count('category'))

rawDescription: Django equivalent for count and group by


code:
for tag in text.tag_names():
    text.tag_delete(tag)

rawDescription: How to remove all tags from Tk Text() object

description: Remove all tags from Tk Text() object


code:
demean = lambda df: df - df.mean()
df.groupby(['Groupvar1', 'Groupvar2']).transform(demean)

rawDescription: Subtract subgroup averages from individuals without resorting to for loop


code:
import sys, re, math

def find_numbers(f):
    for line in f:
        for word in line.split():
            if word.isdigit():
                yield float(word)

lst = list(find_numbers(sys.stdin))
lst.reverse()
for x in lst:
    print('%.4f' % math.sqrt(x))

rawDescription: Python3.3: Square-root optimization

description: Python3.3: Square-root optimization


code:
# A list for all each page's text
pages_text = []

for page in PDFPage.get_pages(pdf):
    # Get (and store) the "cursor" position of stream before reading from PDF
    # On the first page, this will be zero
    read_position = retstr.tell()

    # Read PDF page, write text into stream
    interpreter.process_page(page)

    # Move the "cursor" to the position stored
    retstr.seek(read_position, 0)

    # Read the text (from the "cursor" to the end)
    page_text = retstr.read()

    # Add this page's text to a convenient list
    pages_text.append(page_text)

rawDescription: PDFMiner - export pages as List of Strings


rawDescription: Remap values in pandas column with a dict


code:
from datetime import datetime, timedelta
fourweeks = datetime.now() + timedelta(weeks=4)

rawDescription: Change the start of the year in the datetime module of Python?


code:
dt = DataTable(source=s2, columns=columns, width=300, height=300 )
source.callback = CustomJS(args=dict(s2=s2, dt=dt), code="""
        var inds = cb_obj.get('selected')['1d'].indices;
        var d1 = cb_obj.get('data');
        var d2 = s2.get('data');
        d2['x'] = []
        d2['y0'] = []
        for (i = 0; i < inds.length; i++) {
            d2['x'].push(d1['x'][inds[i]])
            d2['y0'].push(d1['y0'][inds[i]])
        }
        console.log(dt);
        s2.trigger('change');
        dt.trigger('change');
    """)

rawDescription: Bokeh DataTable won't update after trigger('change') without clicking on header


code:
'Hello, world!'.encode('hex')
'Hello, world!'.encode('base64')
'Hello, world!'.encode('zlib')

rawDescription: Python String encode method

description: Python String encode method


code: arr = np.ma.array(am.filled(1) * bm.filled(1), mask=(am.mask * bm.mask))

rawDescription: Efficient way of merging two numpy masked arrays


code:
for index, row in p.iterrows():
    if i > len(p):
       break
    else:
       f = open(str(i)+'.txt', 'w')
       f.write(row[0])
       f.close()
       i+=1

rawDescription: Write each row of pandas dataframe into a new text file - pythonic way


code:
ax3.annotate('Test',
             (df5.index[1], df5['SOLD_PRICE'][1]),
             xytext=(15, 15),
             textcoords='offset points',
             arrowprops=dict(arrowstyle='-|>'))

rawDescription: Annotating points from a Pandas Dataframe in Matplotlib plot


code:
def add_book_link(self, instance):
    if instance.id:
        url = '%s?publisher=%d' % (reverse('admin:myapp_book_add'), instance.id)
    else:
        url = reverse('admin:myapp_book_add')
    return mark_safe(u'Add'.format(u=url))

rawDescription: Admin edit view - populate fields by parameter


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

y = np.array([1,2,3,4,5,6])

f, ax = plt.subplots()

ax.plot(y, linestyle='None', marker='o')

for i in [2, 3, 4]:
    ax.annotate('', xy=(i-1, i), xytext=(i-1,i+0.5),
                arrowprops=dict(facecolor='black',
                                width=1,
                                shrink=0.1))

plt.margins(0.1)
plt.show()

rawDescription: Signal specific points in matplotlib

description: Signal specific points in matplotlib


code:
clickme = browser.find_element_by_xpath('//a[contains(@href,"http://example.com/link")]')
clickme.click()

rawDescription: Python/Selenium - Chrome Web Driver, Click Action


code:
t, y, x = numpy.indices(J.shape)
b = a[t, J, y, x]

rawDescription: Selecting from multidimensional numpy array


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

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

fig, ax = plt.subplots()
im = ax.imshow(z)
cb = fig.colorbar(im)

cb.formatter.set_powerlimits((0, 0))
cb.update_ticks()

plt.show()

rawDescription: Force use of scientific style for basemap colorbar labels


code:
inputFile = open(inputFileSpec, "rU")
inputFile2 = open(inputFileSpec, "rU")

rawDescription: How to copy a file to another variable in Python

description: Copy a file to another variable in Python


code:
# new style classes should inherit from object
class A(object):
    def __init__(self):
        # create a logger for the class and set the log level
        # here we use the root logger
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.INFO)

    def activateLogFile(self, f):
        # create a handler with the name defined by the variable f
        handler = logging.FileHandler(f)
        # add that handler to the logger
        self.logger.addHandler(handler)

    def readProblemInstance(self, fn):
        fn = fn.replace('.', '_')
        fn = fn + '_' + datetime.now().strftime('%Y_%m_%d_%H_%M_%S_%f')
        self.activateLogFile(fn)
        self.logger.info("%s" %fn)

rawDescription: Python logging fail to write into multiple log files


code:
def save(self):
    today = datetime.date.today()
    self.quote = "%s-%s" % (str(today.year)[2:4], self.quote)

rawDescription: Specific Quote Issue

description: Specific Quote Issue


code:
import time

word=['s','t','a','r','t','i','n','g']

for i in range(0,len(word)):
    lower=word[i-1].lower()
    word[i-1]=lower

    caps=word[i].upper()
    word[i]=caps

    wordstr=''.join(word) #hacky way of converting lists to strings
    print(wordstr)
    time.sleep(1)

rawDescription: How can I implement the upper case animation from Metasploit in Python?

description: Implement the upper case animation from Metasploit in Python


code:
from itertools import combinations
list(combinations(("A","b","C","D"), 3))

rawDescription: Subsets of a tuple with a fixed length

description: Subsets of a tuple with a fixed length


code:
def rreplace(s, old, new, occurrence):
 li = s.rsplit(old, occurrence)
 return new.join(li)

s
rreplace(s, '2', ' ', 2)
rreplace(s, '2', ' ', 3)
rreplace(s, '2', ' ', 4)
rreplace(s, '2', ' ', 0)

rawDescription: How to replace the last occurence of an expression in a string

description: Replace the last occurence of an expression in a string


code: ip1=[list(row) for row in temp_orig]

rawDescription: Bug in substitution decryption in python


code:
while 1:

    answer = input("What is your favorite eldest daughter's name?   ").lower()

    if answer == "a" or answer == "al": #assuming this is the right answer
        print("Of course, we all knew that")
        break
    elif answer == "c" or answer == "chris":
        print("""Oh she must be standing right there.
    But that\'s not it, try again.""")

    elif answer == "e" or answer == "ed":
        print("Not even the right gender. Try again.")
    elif answer == "n" or answer == "nic":
        print("Only biological children please.")

    else:
        print("I'm sorry. Only children. Were you thinking of the dogs?")

rawDescription: Continue to ask for input until correct answer is given(Python) (Non number values)


code:
r="whate(ever)(?:\\1)"
import sre_parse        #the module used by `re' internally for regex parsing
sre_parse.parse(r)

rawDescription: Find capturing groups in user submitted regex


code:
divs = soup.find_all("div", class_="result-item standard") + soup.find_all("div", class_="result-item standard  basic ad")
for div in divs:
    item = div.h2.a.text.split()
    item_year = item[0]
    item_make = item[1]

rawDescription: BeautifulSoup findAll tags with mutliple classes


rawDescription: How to use readline() with a pipe returned by subprocess.Popen

description: Use readline() with a pipe returned by subprocess.Popen


code:
def MultipleSave(array1, array2, key1, key2):
    insert_list = []
    update_list = []
    l = len(array1)
    for i in range(0, l):
        try:
            str1 = array1[i]
            str2 = array2[i]

            try:
                new_record = UserString.objects.filter(original=str1)
                new_record = new_record[0]

                setattr(new_record, key2, str2)
                update_list.append(new_record)
            except Exception as e:
                new_record = UserString(original=str1)

                setattr(new_record, key1, str1)
                setattr(new_record, key2, str2)
                insert_list.append(new_record)

        except Exception as e:
            print ('Exception occured: "%s"' % e)

    if len(insert_list) > 0:
        UserString.objects.bulk_create(insert_list)

    with transaction.atomic():
        for record in update_list:
            record.save()

rawDescription: Django MySQL - Save Multiple Records together in DB


code:
concat(dict(A = A, B = B),axis=1)
concat([ A, B ], keys=['A','B'],axis=1)

rawDescription: Merge Two DataFrames With Hierarchical Columns


code:
import selenium
import socket
import subprocess
import shlex
import sys
import time

# CHANGE path='/path/to/selenium-server.jar' AS NEEDED:
def start_server(path='/path/to/selenium-server.jar'):
    null=open('/dev/null')
    proc=subprocess.Popen(shlex.split('java -jar {p}'.format(p=path)),
                          stdout=null,stderr=null)
    return proc

def shutdown_server(sel):
    sel.shut_down_selenium_server()

def start_selenium(host="localhost",
                   port=4444,
                   browserStartCommand="*firefox",
                   browserURL="http://www.google.com/webhp"):
    sel=selenium.selenium(host,port,browserStartCommand,browserURL)
    try:
        sel.start()
    except socket.error as err:
        proc=start_server()
        time.sleep(1)
        try:
            sel.start()
        except socket.error as err:
            sys.exit(err)
    return sel

if __name__=='__main__':
    sel=start_selenium()
    time.sleep(1)
    sel.stop()
    shutdown_server(sel)

rawDescription: python stop selenium standalone server

description: Python stop selenium standalone server


code:
repeat = ""
with open('ref.txt') as f1:
    for line in f1:
        repeat = "".join([repeat, line])
with open('out.txt', 'w') as f2:
    f2.write(repeat*5)

rawDescription: PYTHON several times print from a reference file


code:
# python 3.3 and up, in older versions, replace "yield from" with yield loop

def missing_elements(L, start, end):
    if end - start <= 1:
        if L[end] - L[start] > 1:
            yield from range(L[start] + 1, L[end])
        return

    index = start + (end - start) // 2

    # is the lower half consecutive?
    consecutive_low =  L[index] == L[start] + (index - start)
    if not consecutive_low:
        yield from missing_elements(L, start, index)

    # is the upper part consecutive?
    consecutive_high =  L[index] == L[end] - (end - index)
    if not consecutive_high:
        yield from missing_elements(L, index, end)

def main():
    L = [10,11,13,14,15,16,17,18,20]
    print(list(missing_elements(L,0,len(L)-1)))
    L = range(10, 21)
    print(list(missing_elements(L,0,len(L)-1)))

main()

rawDescription: Efficient way to find missing elements in an integer sequence


code:
a = np.array([[1,2], [3,4], [5,6]])
np.shape(a)
a_trans = a.transpose()
np.shape(a_trans)
a_trans

rawDescription: Transforming a row vector into a column vector in Numpy


code:
class GetAttr(type):
    def __getitem__(cls, x):
        return getattr(cls, x)

class Fruit(object):
    __metaclass__ = GetAttr

    Apple = 0
    Pear = 1
    Banana = 2

rawDescription: How to implement a subscriptable class in Python (subscriptable class, not subscriptable object)?

description: Implement a subscriptable class in Python (subscriptable class, not subscriptable object)


code:
import imp
imp.reload(math)
math.pi

rawDescription: Why is "import" implemented this way?

description: Why is "import" implemented this way


rawDescription: Python Insert variables in string

description: Python Insert variables in string


code:
import requests
import json

url = 'http://bitcoincharts.com/charts/chart.json?m=itbitUSD&SubmitButton=Draw&r=60&i=12-hour&c=1&s=2015-02-03&e=2015-04-04&Prev=&Next=&t=S&b=&a1=&m1=10&a2=&m2=25&x=0&i1=&i2=&i3=&i4=&v=1&cv=0&ps=0&l=0&p=0&'
data = json.loads(requests.get(url).content)

rawDescription: Scrapping Data from bitcoincharts

description: Scrapping Data from bitcoincharts


code:
def convert_to_hex(rgba_color) :
    red = int(rgba_color.red*255)
    green = int(rgba_color.green*255)
    blue = int(rgba_color.blue*255)
    return '0x{r:02x}{g:02x}{b:02x}'.format(r=red,g=green,b=blue)

rawDescription: gtk3+ and python rgba convert to hex

description: Gtk3+ and python rgba convert to hex


rawDescription: Python Pandas - Don't sort bar graph on y axis values


code:
class Program(QtGui.QMainWindow, Interface.Ui_MainWindow):
    def __init__(self, parent=None):
        super(Program, self).__init__(parent)
        self.setupUi(self)

        self.runArea = RunArea(self)
        self.startButton.clicked.connect(self.runArea.start)
        self.clearButton.clicked.connect(self.runArea.clear)

class RunArea():
    def __init__(self, parent=None):
        self.parent = parent

    def start(self):
        self.parent.log.setPlainText("log entry")

    def clear(self):
        self.parent.runTree.clear()

rawDescription: PySide using GUI elements in another class


rawDescription: Using numpy from a local directory

description: Using numpy from a local directory


code:
from networkx.algorithms import isomorphism
G1 = nx.path_graph(4)
G2 = nx.path_graph(4)
GM = isomorphism.GraphMatcher(G1,G2)
GM.is_isomorphic()
GM.mapping

rawDescription: getting a list of matching nodes in networkx

description: Getting a list of matching nodes in networkx


code:
from itertools import chain

for x in chain(range(0, 26), range(75, 101)):
    print(x)

rawDescription: How to combine two for loops

description: Combine two for loops


code: res = [z for z in ((x, y[i]) for i in I)]

rawDescription: build list of lists using comprehension lists two at a time

description: Build list of lists using comprehension lists two at a time


code:
import sympy
x, y, z = sympy.symbols('xyz')
p = sympy.Plot(x * y ** 3 - y * x ** 3)
p.saveimage('/tmp/plot.png', format='png')

rawDescription: Python: How to export Sympy image to png?


code:
cost = '1'
cost * 10
cost = int('1')
cost * 10

rawDescription: Number formatting from cents to dollars

description: Number formatting from cents to dollars


code:
class my_range(object):
    def __init__(self, start, stop=None, step=1):
        if stop is None:
            start, stop = 0, start
        self.start, self.stop, self.step = start, stop, step
        if step < 0:
            lo, hi = stop, start
        else:
            lo, hi = start, stop
        self.length = ((hi - lo - 1) // abs(step)) + 1

    def __iter__(self):
        current = self.start
        if self.step < 0:
            while current > self.stop:
                yield current
                current += self.step
        else:
            while current < self.stop:
                yield current
                current += self.step

    def __len__(self):
        return self.length

    def __getitem__(self, i):
        if 0 <= i < self.length:
            return self.start + i * self.step
        raise IndexError('Index out of range: {}'.format(i))

    def __contains__(self, num):
        if self.step < 0:
            if not (self.stop < num <= self.start):
                return False
        else:
            if not (self.start <= num < self.stop):
                return False
        return (num - self.start) % self.step == 0

description: Why is 1000000000000000 in range(1000000000000001) so fast in Python 3


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

fig,ax = plt.subplots(1)

N = 20

from_x = np.linspace(0,0.95,N)
to_x = from_x + 0.05

for i in range(N):
    ri = float(i)/float(N)
    gi = 1.-ri
    bi = 0.

    ax.axvspan(from_x[i], to_x[i], color=(ri,gi,bi))

plt.show()

rawDescription: Coloring axvspan from range of colors (Python)


code:
__author__ = 'vinayjoseph'

from google.appengine.ext import ndb
import logging
from datetime import datetime

class Event(ndb.Model):
    """Models an individual event at xxx xxx """
    Date = ndb.DateTimeProperty()
    Location = ndb.StringProperty()
    Address = ndb.StringProperty()
    Name = ndb.StringProperty()

def get_meeting_date():
    """gets the next meeting date from the No SQL Schemaless Google Datastore
    """
    qry = Event.query(Event.Name == 'Next Meeting Location')
    for event in qry.fetch(1):
        logging.info("Meeting is on %s at %s" % (str(event.Date), event.Address))

rawDescription: Google App Engine ndb query

description: Google App Engine ndb query


code:
from nltk.tokenize import RegexpTokenizer
s = '''He said,"that's it." *u* Hello, World.'''
toker = RegexpTokenizer(r'((?<=[^\w\s])\w(?=[^\w\s])|(\W))+', gaps=True)
toker.tokenize(s)

rawDescription: How to remove punctuation?

description: Remove punctuation


code:
v="This is a  string"
v.split()

rawDescription: How to split string into words that do not contain whitespaces in python?

description: Split string into words that do not contain whitespaces in python


code:
entry = Gtk.Entry()
entry.set_placeholder_text("I am a placeholder")

rawDescription: Python Gtk.Entry placeholder text

description: Python Gtk.Entry placeholder text


rawDescription: Can't find an element Selenium Python

description: Can't find an element Selenium Python


code:
def score_func(model):
    score = do_something_to_get_score(model)
    return score

results = sorted(list_of_models, score_func)

rawDescription: Updating model method during queryset list


code:
from collections import Counter

myList = ['a','b','c','a','c','a']
res = [k for k,v in Counter(myList).most_common()]
# ['a', 'c', 'b']

rawDescription: How to sort a Python list descending based on item count, but return a list with sorted items only, and not a count also?

description: Sort a Python list descending based on item count, but return a list with sorted items only, and not a count also


code:
from django.http import QueryDict
d = QueryDict(request.POST['form'])
role = d['role']

rawDescription: Django - retrieve form data

description: Django - retrieve form data


code:
def save_object(obj, filename):
    with open(filename, 'wb') as output:
        pickle.dump(obj, output, -1)

rawDescription: Loading all objects of a dictionary from a pickle file


code:
y
DesiredResult
y[:-1]
y[:-1] == DesiredResult

rawDescription: What is happening to the output of this conversion, and why isn't it what I think it should be?


code:
import subprocess
df = subprocess.Popen(["df", "filename"], stdout=subprocess.PIPE)
output = df.communicate()[0]
device, size, used, available, percent, mountpoint = \
    output.split("\n")[1].split()

rawDescription: Find size and free space of the filesystem containing a given file


code:
from itertools import Counter

def checksub(main, sublist):
    c = Counter(sublist)
    for num, count in c.items():
        if main.count(num) < count:
            return False
    return True

all(checksub(main, sublist) for sublist in coll)

rawDescription: To check if sublist exists in another list


code:
with open('infile.txt') as infile, open('outfile.txt', 'w') as outfile:
    outfile.write(', '.join(infile.read().split('\n')) + '\n')

rawDescription: Python comma delimiting a text file

description: Python comma delimiting a text file


code:
def get_subclass(module, base_class):
    for name in dir(module):
        obj = getattr(module, name)
        try:
            if issubclass(obj, base_class):
                return obj
        except TypeError:  # If 'obj' is not a class
            pass
    return None

rawDescription: Python - Get class of type from imported module


code:
from django.db import models

class BaseMedia(models.Model):
    category    = models.ForeignKey(Categories)
    title       = models.CharField(max_length=250)
    caption     = models.CharField(max_length=250)
    date        = models.DateTimeField('date published')
    url         = models.CharField(max_length=250)

    class Meta:
        abstract = True

class Images(BaseMedia):

    class Meta:
        verbose_name_plural = 'images'

    def __unicode__(self):
        return self.category

class Videos(BaseMedia):

    PROVIDER_LIST_CHOICES   = (('YU','YouTube'),('VI','Vimeo'))
    provider        = models.CharField(max_length=2, choices=PROVIDER_LIST_CHOICES)

    class Meta:
        verbose_name_plural = 'videos'

    def __unicode__(self):
        return self.category

rawDescription: Django class inheritance to create table tables


code:
# setup.py
from distutils.core import setup
import py2exe
setup(console=["p3_exctract.py"],
      options={
              "py2exe":{
                    "packages": ["lxml"] # List of the package you want to make sure that will be imported
               }
       }
    )

rawDescription: Working with py2exe and BeautifulSoup. Script run fine but after converting into .exe , it shows error


code:
#!python3.4
import re

for fn in ('a.txt','b.txt'):
    with open(fn) as fin:
        for line in fin.readlines():
            title = re.search('^Title:(.*)$',line)
            if title:
                print(title.group(1))

rawDescription: Getting Title of a text

description: Getting Title of a text


code:
n = 10
for ind in range(len(myList)):
    # Don't overrun our bounds
    if ind == len(myList)-1:
        break

    # Check that our sequence is valid
    for i in range(ind-n, ind+1):
        if i >= 0 and myList[i] == "x":
            # we have an invalid sequence
            ind += i   # start next seq after invalid entry
            break

    # Add valid training sequence to data set
    ds.addSample(myList[ind-n:ind],myList[ind+1])

rawDescription: fill missing values of sequence with neural networks

description: Fill missing values of sequence with neural networks


code:
import re
output = '00000000001'
result = ','.join(re.findall(r'.{1,2}', output))
result

rawDescription: How can I separate pairs of zeros with delimiter

description: Separate pairs of zeros with delimiter


code:
tokens = [[y for y in (re.sub(r'[^A-Za-z0-9]+', '', x) for x in sublst) if y] for sublst in texts]
pprint.pprint(tokens)

rawDescription: remove non-letters from tokens in python lists

description: Remove non-letters from tokens in python lists


code:
def getInt(msg):
    while True:
        try:
            return int(raw_input(msg))
        except ValueError:
            pass

def total_profit(a, b, c):
    return 35.0*a + 25.0*b + 10.0*c

def main():
    class_a = getInt('Enter Class A tickets sold: ')
    class_b = getInt('Enter Class B tickets sold: ')
    class_c = getInt('Enter Class C tickets sold: ')

    print("Total profit is ${0:0.2f}.".format(total_profit(class_a, class_b, class_c)))

if __name__=="__main__":
    main()

rawDescription: Python - Check If Multiple String Entries Contain Invalid Chars


code:
import re
from django.forms import Form, ModelForm
from django import template
from django.conf import settings

numeric_test = re.compile("^\d+$")
register = template.Library()

def getattribute(value, arg):
    """Gets an attribute of an object dynamically from a string name"""
    if hasattr(value, str(arg)):
        return getattr(value, arg)
    elif hasattr(value, 'has_key') and value.has_key(arg):
        return value[arg]
    elif numeric_test.match(str(arg)) and len(value) > int(arg):
        return value[int(arg)]
    elif issubclass(value.__class__, (Form, ModelForm)) and arg in value.fields:
        return value[arg]
    else:
        return settings.TEMPLATE_STRING_IF_INVALID

register.filter('getattribute', getattribute)

rawDescription: django form dynamic attribute lookup

description: Django form dynamic attribute lookup


code:
import cStringIO
...
sound = pygame.mixer.Sound(cStringIO.StringIO(a_sound))

rawDescription: How do I coerce str to correct type for pygame.mixer (Python)?

description: Coerce str to correct type for pygame.mixer (Python)


code:
display_html(HTML('Heading'))

fig, ax = plt.subplots()
ax.plot(np.arange(100),np.random.randn(100).cumsum())
display(fig)

display_html(HTML('Sub-heading'))

fig, ax = plt.subplots()
ax.plot(np.arange(100),np.random.randn(100).cumsum())
display(fig)

plt.close('all') # this closes all of them

rawDescription: Control IPython Notebook layout of plots and other output


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

m, n = 20, 30

# Generate randomly spaced, but increasing time and frequency vectors
time = np.random.normal(0, 1, n).cumsum()
frequency = np.random.normal(0, 1, m).cumsum()
data = np.random.random((m,n))

fig, ax = plt.subplots()
ax.pcolormesh(time, frequency, data, cmap='gist_earth')
ax.axis('tight')
plt.show()

rawDescription: Color plot with specified axes

description: Color plot with specified axes


code: reduce(lambda a,c: foo(a,b), range(20), 0)

rawDescription: Passing Incomplete Parameter List in Python


code:
class YelpSpider(CrawlSpider):
    name = "yelp"
    allowed_domains = ["www.yelp.com"]
    start_urls = [
        "http://www.yelp.com/search?find_desc=Hotels&find_loc=San+Francisco%2C+CA&ns=1",
        "http://www.yelp.com/biz/ucsf-medical-center-at-mount-zion-san-francisco"
    ]

    rules = [
        Rule(LinkExtractor(allow=('.*')),follow=True,callback="parseBusiness")
    ]

rawDescription: very simple scrapy crawler not following links

description: Very simple scrapy crawler not following links


code:
items = iter(ds)
v = {a: b(next(items)) for a, b in fs}
v

rawDescription: using python map to apply type func in tuple to a list of strings

description: Using python map to apply type func in tuple to a list of strings


code:
DOMAIN_LABEL_RE = """
(?i               # case insensitive
  \A(
    ([a-z])       # need at least 1 letter and cannot start with digit or hyphen
    ([a-z\d-]*?)
    (?<!-)        # cannot end with a hyphen
  )\Z
)
"""

rawDescription: lookahead assertions

description: Lookahead assertions


code:
message = sys.stdin.read()
sys.stdin = open('/dev/tty')
selected_index = raw_input('Which URL to open?')

rawDescription: Python raw_input following sys.stdin.read() throws EOFError


code:
import numpy as np
output = np.einsum("ijk, ij -> ik", A, B)

rawDescription: multiply multidimensional arrays in python

description: Multiply multidimensional arrays in python


code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from io import StringIO

s = StringIO("""     amount     price
A     40929   4066443
B     93904   9611272
C    188349  19360005
D    248438  24335536
E    205622  18888604
F    140173  12580900
G     76243   6751731
H     36859   3418329
I     29304   2758928
J     39768   3201269
K     30350   2867059""")

df = pd.read_csv(s, index_col=0, delimiter=' ', skipinitialspace=True)

fig = plt.figure() # Create matplotlib figure

ax = fig.add_subplot(111) # Create matplotlib axes
ax2 = ax.twinx() # Create another axes that shares the same x-axis as ax.

width = 0.4

df.amount.plot(kind='bar', color='red', ax=ax, width=width, position=1)
df.price.plot(kind='bar', color='blue', ax=ax2, width=width, position=0)

ax.set_ylabel('Amount')
ax2.set_ylabel('Price')

plt.show()

rawDescription: Pandas: Bar-Plot with two bars and two y-axis


code:
def move(obj, goal):
    obj.x = ((obj.x - goal.x) * 15.0 / 16) + goal.x
    obj.y = ((obj.y - goal.y) * 15.0 / 16) + goal.y

rawDescription: How to move each figure toward the goal between the poin that I click on graphics and the center of my object in Python

description: Move each figure toward the goal between the poin that I click on graphics and the center of my object in Python


code:
import sys
def __main__():
    with open("parameters.log", "ab") as f:
        f.write(str(sys.argv))

rawDescription: PyInstaller: drag-and-drop files to the --onefile exe


code:
import platform
platform.win32_ver()
platform.system()
platform.version()
platform.release()

rawDescription: How to check if OS is Vista in Python?

description: Check if OS is Vista in Python


code:
import random
l = range(0, 100)
l
random.sample(l, 10)

rawDescription: What does random.sample() method in python do?


code: c = chars.charAt(ind);

rawDescription: Jython random string generation

description: Jython random string generation


rawDescription: Python 3: Opening A Magnet Link Contained In A Variable


code:
feature_count = sparse_matrix.sum(axis=0)
columns = tuple(np.where(feature_count == feature_count.max())[1])
columns
sparse_matrix[:, columns].toarray()
type(sparse_matrix[:, columns])
np.array(features_names)[list(columns)]

rawDescription: Filter only certain words from sklearn CountVectorizer sparse matrix


code:
import unittest

class BlackBox1():
    def calc(self, a, b):
        return a + b

class BlackBox2():
    def calc(self, a, b):
        return a * b

class TestBlackBox1(unittest.TestCase):
    test_params = {"blackbox": BlackBox1, "a": 3, "b": 5, "result": 8}
    def setUp(self):
        self.box = self.test_params["blackbox"]()
        self.param_a = self.test_params["a"]
        self.param_b = self.test_params["b"]
        self.expected_result = self.test_params["result"]

    def test_calc_method(self):
        real_result = self.box.calc(self.param_a, self.param_b)
        self.assertEqual(real_result, self.expected_result,
                        "{0} gives wrong result: {1} instead of {2}".format
                        (self.box.__class__, real_result, self.expected_result))

class TestBlackBox2(TestBlackBox1):
    test_params = {"blackbox": BlackBox2, "a": 4, "b": 7, "result": 28}

TBB1 = unittest.defaultTestLoader.loadTestsFromTestCase(TestBlackBox1)
TBB2 = unittest.defaultTestLoader.loadTestsFromTestCase(TestBlackBox2)

rawDescription: How to unittest multiple similar classes

description: Unittest multiple similar classes


code: df.index = pd.to_datetime(df.index)

rawDescription: Frequency of a data frame

description: Frequency of a data frame


code: and_(photo_content_table.c.photoId == photo_table.c.id, photo_content_table.c.locale == get_lang)

rawDescription: SQLAlchemy: relation in mappers compile result of function rather than calling the function when the relation is queried


code:
name_pairs = set((i['name'], i['last']) for i in lst)
if (d['name'], d['last']) not in name_pairs:
    lst.append(d)

rawDescription: python - list of dictionaries check key:value

description: Python - list of dictionaries check key:value


code:
output = (rdd1
   .groupByKey()
   .mapValues(set)
   .flatMap(lambda kvs: [(x, y) for x in kvs[1] for y in kvs[1] if x < y])
   .distinct())

rawDescription: How to create pair RDD with elements that share keys in source RDD?

description: Create pair RDD with elements that share keys in source RDD


code:
import random

numbers = list(range(1, 50))
operators = ["+", "-", "x"]
numbers1 = list(range(1,10))

print(str(random.choice(numbers)) + random.choice(operators) + str(random.choice(numbers1)))

rawDescription: how to have three different lists print on one line

description: Have three different lists print on one line


code:
import numpy as np
import warnings

x = np.ones((1000, 1000)) * np.nan

# I expect to see RuntimeWarnings in this block
with warnings.catch_warnings():
    warnings.simplefilter("ignore", category=RuntimeWarning)
    foo = np.nanmean(x, axis=1)

rawDescription: mean, nanmean and warning: Mean of empty slice

description: Mean, nanmean and warning: Mean of empty slice


code:
import pep8

lines = """
def a:
    pass

def b:
   pass
"""

checker = pep8.Checker(
    lines=lines.strip().splitlines(),
    filename=None,
    show_source=True
)
result = checker.check_all()

rawDescription: Can I ask pep8 in python to parse a string instead of a file?

description: Ask pep8 in python to parse a string instead of a file


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from BeautifulSoup import BeautifulSoup
import time
browser = webdriver.Firefox()
baseURL="http://www.codechef.com/users/peeyushy95"
browser.get(baseURL)
time.sleep(5)
soup=BeautifulSoup(browser.page_source)
L=str(soup)
f_out=open("/home/adi/experi/data_up.txt","w")
f_out.write(L)
f_out.close()

rawDescription: Extract Recent Activity data from Codechef Userid


code:
import Image
def handle_uploaded_file(file):
 myimg = Image.open(file)
 myimg = myimg.resize((1024,1024),Image.ANTIALIAS)
 myimg.save('/home/arpit/myimg.png')
 #... rest of the code

rawDescription: django - handle image -

description: Django - handle image -


code:
import time

# Import managed objects
( trsDeliveryTime,
  trsMessagesPerHour,
  trsGatewayIndex,
  trsGatewayName,
  trsGatewayState, ) = mibBuilder.importSymbols(
  'TRS-MIB',
  'trsDeliveryTime',
  'trsMessagesPerHour',
  'trsGatewayIndex',
  'trsGatewayName',
  'trsGatewayState',
  )

# Columnar managed objects instances implementation

class TrsDeliveryTimeInstance(MibScalarInstance):
  def readGet(self, name, val, *args):
    if name[-1] == 0:  # Row #0
      return self.name, self.syntax(int(time.time()))
    elif name[-1] == 1: # Row #1
      return self.name, self.syntax(time.time()//2)
    else:
      MibScalarInstance.readGet(self, name, val, *args)

class TrsMessagesPerHourInstance(MibScalarInstance):
  def readGet(self, name, val, *args):
    if name[-1] == 0: # Row #0
      return self.name, self.syntax(-int(time.time()))
    elif name[-1] == 1: # Row #1
      return self.name, self.syntax(-time.time()//2)
    else:
      MibScalarInstance.readGet(self, name, val, *args)

class TrsGatewayIndexInstance(MibScalarInstance):
  def readGet(self, name, val, *args):
    if name[-1] == 0: # Row #0
      return self.name, self.syntax(0)
    elif name[-1] == 1: # Row #1
      return self.name, self.syntax(1)
    else:
      MibScalarInstance.readGet(self, name, val, *args)

class TrsGatewayNameInstance(MibScalarInstance):
  def readGet(self, name, val, *args):
    if name[-1] == 0: # Row #0
      return self.name, self.syntax('SMG0')
    elif name[-1] == 1: # Row #1
      return self.name, self.syntax('SMG1')
    else:
      MibScalarInstance.readGet(self, name, val, *args)

class TrsGatewayStateInstance(MibScalarInstance):
  def readGet(self, name, val, *args):
    if name[-1] == 0: # Row #0
      return self.name, self.syntax('UP' + str(time.time()))
    elif name[-1] == 1: # Row #1
      return self.name, self.syntax('DOWN' + str(time.time()))
    else:
      MibScalarInstance.readGet(self, name, val, *args)

# Instantiate and export managed objects instances
mibBuilder.exportSymbols(
  "__TRS-MIB",
  # Row #0
  TrsDeliveryTimeInstance(trsDeliveryTime.getName(), 0, trsDeliveryTime.getSyntax()),
  TrsMessagesPerHourInstance(trsMessagesPerHour.getName(), 0, trsMessagesPerHour.getSyntax()),
  TrsGatewayIndexInstance(trsGatewayIndex.getName(), 0, trsGatewayIndex.getSyntax()),
  TrsGatewayNameInstance(trsGatewayName.getName(), 0, trsGatewayName.getSyntax()),
  TrsGatewayStateInstance(trsGatewayState.getName(), 0, trsGatewayState.getSyntax()),
  # Row #1
  TrsDeliveryTimeInstance(trsDeliveryTime.getName(), 1, trsDeliveryTime.getSyntax()),
  TrsMessagesPerHourInstance(trsMessagesPerHour.getName(), 1, trsMessagesPerHour.getSyntax()),
  TrsGatewayIndexInstance(trsGatewayIndex.getName(), 1, trsGatewayIndex.getSyntax()),
  TrsGatewayNameInstance(trsGatewayName.getName(), 1, trsGatewayName.getSyntax()),
  TrsGatewayStateInstance(trsGatewayState.getName(), 1, trsGatewayState.getSyntax())
)

rawDescription: Implementing a table in a PySNMP agent

description: Implementing a table in a PySNMP agent


code:
import matplotlib.pyplot as plt
from itertools import cycle
lines = ["-","--","-.",":"]
linecycler = cycle(lines)
plt.figure()
for i in range(10):
    x = range(i,i+10)
    plt.plot(range(10),x,next(linecycler))
plt.show()

rawDescription: Can i cycle through line styles in matplotlib

description: Cycle through line styles in matplotlib


code: highest_thing = max(things, key=lambda thing: thing.strength(some_params))

rawDescription: Pattern for finding maximum match in ordered-important list


code:
def bunnies(n,months,quantity):
    if n == months:
        return quantity
    else:
        quantity=quantity+quantity
        return bunnies(n+1,months,quantity) # Here

rawDescription: Python recursive function

description: Python recursive function


rawDescription: How to force the short summary dataframe output in Ipython Notebook

description: Force the short summary dataframe output in Ipython Notebook


code:
bool(oils & foo) ^ bool(waters & foo)
Out[19]: False

bool(oils & bar) ^ bool(waters & bar)
Out[20]: True

bool(oils & baz) ^ bool(waters & baz)
Out[21]: True

rawDescription: In Python, how to you check to see if a list of items is exclusive to one list out of two?


code:
from xml.dom import minidom

doc = minidom.parse(myXmlFile)
for element in doc.getElementsByTagName('MyElementName'):
    if element.getAttribute('name') in ['AttrName1', 'AttrName2']:
        parentNode = element.parentNode
        parentNode.insertBefore(doc.createComment(element.toxml()), element)
        parentNode.removeChild(element)
f = open(myXmlFile, "w")
f.write(doc.toxml())
f.close()

rawDescription: Match "without this"

description: Match "without this"


code:
image = pygame.Surface([640,480], pygame.SRCALPHA, 32)
image = image.convert_alpha()

rawDescription: How to make a surface with a transparent background in pygame

description: Make a surface with a transparent background in pygame


code:
def removeDuplicateArtist(stringInput):
    if "," in stringInput:
        names = stringInput.split(" ")
        artist = names[1][int(len(names[1])/2):] + " "
        names.remove(names[0])
        names.remove(names[0])
        for i in names:
            artist += str(i) + " "
        return artist

rawDescription: Cleaning Column Data Where Data Has Repeated Itself (Python)


code:
import re
r = re.compile('Master(.*?)thon')
m = r.search(str1)
if m:
    lyrics = m.group(1)

rawDescription: How to extract a string between 2 other strings in python?

description: Extract a string between 2 other strings in python


code:
content = ""
with open('Path/to/file', 'r') as content_file:
   content = content_file.read()

rawDescription: Pass variable to params unirest

description: Pass variable to params unirest


code:
pw = getpass.getpass()
from subprocess import Popen, PIPE, STDOUT
ssh_conn = Popen(["ssh", "-t", server, "sudo -S cp /etc/"+map, "/etc/"+map + "." +fulltime], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
ssh_conn.communicate(input='{0}\n'.format(pw))[0]

rawDescription: How to pass a variable to subprocess communicate

description: Pass a variable to subprocess communicate


code:
from configobj import ConfigObj
config = ConfigObj('your_config_filename')
config.keys()
config['default']

rawDescription: using configobj to read a complete section one by one

description: Using configobj to read a complete section one by one