code:
global_list = []

def non_pure_add1_func(x):
    global_list.append(x)
    return x+1

rawDescription: How to judge (or how to write) a python function with no side effects?

description: Judge (or how to write) a python function with no side effects


rawDescription: How do I make my wxpython top frame show in the middle of my desktop?

description: Make my wxpython top frame show in the middle of my desktop


code:
from scipy import zeros_like
from scipy.integrate import odeint
from pylab import * # for plotting commands

def deriv(y,t): # return derivatives of the array y
    a = 2.0
    b = 0.5 #0.1
    c = 0.1
    doty = zeros_like(y)
    for i in range(0,5):
        j=2*i   # this has no deep reason
        k=2*i+1 # just keeps notation short
        doty[j] = y[j]*a*(1-y[j]/10)-b*y[j]*y[k]
        doty[k] = b*y[j]*y[k]-c*y[k]

    return doty

time = linspace(0,500,1000)
yinit = linspace(1,1,10)
y = odeint(deriv,yinit,time)
figure()
plot(time,y[:,0],time,y[:,1],time,y[:,5],time,y[:,8])
xlabel('t')
ylabel('y')
show()

rawDescription: Implementing a loop for a system of ordinary differential equations


code:
for pattern in patterns:
    for kmer in kmers:
        mism_counter=0
        for j in range(0,k):
            if kmer[j] != pattern[j] :
                mism_counter+=1
                if mism_counter > misn:
                    break
        else:
            if pattern in frequent:
                frequent[pattern] += 1
            else:
                frequent[pattern] = 1

rawDescription: Efficient finding of string mismatches in large lists


code:
import scipy.stats as st

l = 5. # exponential parameter
dist = st.expon(0., l) # distribution object provided by scipy
f  = dist.pdf # probability density function
F  = dist.cdf # cumulative density function
rF = dist.ppf # percent point function : reverse `F^-1` function
shaped_sample = rF(uniform_sample)
# and much more!

rawDescription: Get reverse cumulative density function with NumPy?


code:
class GenAsyncHandler2(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self):
        http_client = AsyncHTTPClient()
        http_client.fetch("http://google.com",
                          callback=(yield tornado.gen.Callback("google")))

        http_client.fetch("http://python.org",
                          callback=(yield tornado.gen.Callback("python")))

        http_client.fetch("http://tornadoweb.org",
                          callback=(yield tornado.gen.Callback("tornado")))
        keys = set(["google", "tornado", "python"])
        while keys:
            key, response = yield tornado.gen.WaitAny(keys)
            keys.remove(key)
            # do something with response
            self.write(str(key)+"        ")
            self.flush()
        self.finish()

rawDescription: Tornado Async HTTP returning results incrementally


code:
string = "addressing scheme network location path query fragment_identifier".split()
url = urlparse.urlsplit("url")

dictionary = dict(zip(string,url))

rawDescription: Does Python 2.6 have a built in URL parameters parser?


code:
for line in logfile:
    if "Contact" in line:

        myIPAddress=line.split('[')[1].split(']')[0]
        myPort=line.split(']:')[1].split(';')[0]

rawDescription: python pattern match and process

description: Python pattern match and process


code:
wait.until(EC.visibility_of_element_located((By.XX, "Processing... popup locator")))
wait.until(EC.invisibility_of_element_located((By.XX, "Processing... popup locator")))

rawDescription: Wait for upload to finish or for success message to pop out


code:
from django.db.models import Count
Games.objects.filter(owned=0).annotate(vote=Count('votes')).order_by('-vote')

rawDescription: Django ORM Table Relationships

description: Django ORM Table Relationships


code:
from pymongo import MongoClient
from itertools import chain
mc = MongoClient()
db = mc["test_db"]
col = db["test_collection"]
col.insert({"aaaa":1})
col.insert({"bbbb":2})
cur1 = col.find({"aaaa":1})
cur2 = col.find({"bbbb":2})
data = [x for x in chain(cur1, cur2)]
data

rawDescription: Chain two Pymongo Cursors

description: Chain two Pymongo Cursors


code:
for i, j in ((1,0), (2,1), (3,0)):
    gui.columnconfigure(i, weight=j)

rawDescription: How to set where extra padding goes in tkinter

description: Set where extra padding goes in tkinter


rawDescription: Get the description of a status code in Python Requests


code:
from sklearn.externals import joblib
joblib.dump(clf, 'filename.pkl')

#then your colleagues can load it

clf = joblib.load('filename.pk1')

rawDescription: How to output RandomForest Classifier from python?

description: Output RandomForest Classifier from python


code:
class CustomUserAdmin(UserAdmin):
# ...code here...

    fieldsets = (
        (None, {'fields': ('email',)}),
        (_('Personal info'), {'fields': ('first_name', 'last_name')}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'first_name', 'last_name', 'password1',
                       'password2')}
         ),
    )

rawDescription: Django admin form for creating AbstractUser extended model


code: resp.set_cookie('JSESSIONID', 'your secret here.')

rawDescription: How to enable Cloud Foundry's sticky session in Python Flask project?

description: Enable Cloud Foundry's sticky session in Python Flask project


code:
def __init__(self, parent):

    Text.__init__(self, parent)
    Scrollbar.__init__(self, parent)

    self.text = Text(parent)
    scroll = Scrollbar(parent)
    self.text.focus_set()

    scroll.pack(side=RIGHT, fill=Y)
    self.text.pack(side=LEFT, fill=Y)

    scroll.config(command=self.text.yview)
    self.text.config(yscrollcommand=scroll.set)

# write line to text box
def write_line(self):

    self.text.insert(END, 'this is a test') # there

rawDescription: How can I access this text widget from another function?

description: Access this text widget from another function


code:
import itertools
[(sum(i[0] for i in group), key) for key, group in itertools.groupby(sorted(mylist, key = lambda i: i[1]), lambda i: i[1])]

rawDescription: How to sum values of tuples that have same name in Python

description: Sum values of tuples that have same name in Python


code:
new_training_data = new_training_data.astype(np.float64)
new_training_data[new_training_data == 0] = -1

rawDescription: How to convert values in a numpy matrix based on a condition?

description: Convert values in a numpy matrix based on a condition


code:
import numpy as np
a = np.array([1,3,5])
b = np.array([2,4,6])

c = np.empty((a.size + b.size,), dtype=a.dtype)
c[0::2] = a
c[1::2] = b

rawDescription: Interweaving two numpy arrays

description: Interweaving two numpy arrays


code:
img = Image.open("someimage.jpg")
qt = img.quantization
# qt is now a dictionary of arrays which is your quantization table.

width, height = img.size
crop = img.crop((8, 0, width, height))
img = img.resize((width - 8, height))
img.paste(crop, (0,0))

# pass qt in as you save your jpeg
img.save("crop.jpg",  qtables = qt)

rawDescription: Preserving image type info in PIL when cropping


code:
thelist = []
a = [0]
for i in range(5):
    thelist.append(list(a))
print(thelist)

rawDescription: List index changes multiple elements

description: List index changes multiple elements


code: waypoints = '|'.join("{0},{1}".format(p.latitude, p.longitude) for p in points)

rawDescription: Python - Building a string from a loop

description: Python - Building a string from a loop


code:
import cgi

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class EquipmentBox(db.Model):
      equipCode = db.StringProperty()

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.out.write('')

    equips = db.GqlQuery("SELECT * FROM EquipmentBox")

    for equip in equips:

      self.response.out.write('
%s
' %
                              cgi.escape(equip.equipCode))

    # Write the submission form and the footer of the page
    self.response.out.write("""
          <form action="/post" method="post">

<input type="text" name="equip_code" />

<input type="submit" value="post equipcode">

          </form>

      """)

class EquipBox(webapp.RequestHandler):
  def post(self):
    equip = EquipmentBox()
    equip.equipCode = self.request.get('equip_code')
    equip.put()
    self.redirect('/')

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/post', EquipBox)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

rawDescription: python - storing a string from a textbox to the Google App Engine Datastore

description: Python - storing a string from a textbox to the Google App Engine Datastore


code:
try:
  resume = input("Press Enter to continue.")
except SyntaxError:
  pass

rawDescription: Pause python scripts in between tasks, wait for user to continue.


code:
import numpy, scipy, scipy.ndimage, scipy.interpolate, numpy.fft, math

# create simple square
img = numpy.zeros( (10, 10) )
img[1:9, 1:9] = 1
img[2:8, 2:8] = 0

# find contour
x, y = numpy.nonzero(img)

# find center point and conver to polar coords
x0, y0 = numpy.mean(x), numpy.mean(y)
C = (x - x0) + 1j * (y - y0)
angles = numpy.angle(C)
distances = numpy.absolute(C)
sortidx = numpy.argsort( angles )
angles = angles[ sortidx ]
distances = distances[ sortidx ]

# copy first and last elements with angles wrapped around. needed so can interpolate over full range -pi to pi
angles = numpy.hstack(([ angles[-1] - 2*math.pi ], angles, [ angles[0] + 2*math.pi ]))
distances = numpy.hstack(([distances[-1]], distances, [distances[0]]))

# interpolate to evenly spaced angles
f = scipy.interpolate.interp1d(angles, distances)
angles_uniform = scipy.linspace(-math.pi, math.pi, num=100, endpoint=False)
distances_uniform = f(angles_uniform)

# fft and inverse fft
fft_coeffs = numpy.fft.rfft(distances_uniform)
# zero out all but lowest 10 coefficients
fft_coeffs[11:] = 0
distances_fit = numpy.fft.irfft(fft_coefs)

# plot results
import matplotlib.pyplot as plt
plt.polar(angles, distances)
plt.polar(angles_uniform, distances_uniform)
plt.polar(angles_uniform, distances_fit)
plt.show()

rawDescription: How to fit a closed contour?

description: Fit a closed contour


code:
import csv

def main():
    infname  = 'contacts.csv'
    outfname = 'per_contact.csv'

    with open(infname) as inf, open(outfname, 'w') as outf:
        inCsv  = csv.reader(inf)
        outCsv = csv.writer(outf)

        inCsv.next()  # skip header row
        outCsv.writerow(['ID', 'Company', 'ContactFirst', 'ContactLast', 'Title', 'Email'])

        for row in inCsv:
            id_co = row[:2]
            for contact in (row[i:i+4] for i in range(2, len(row), 4)):
                if any(c.strip() for c in contact):  # at least one cell contains data?
                    outCsv.writerow(id_co+contact)

if __name__=="__main__":
    main()

rawDescription: How to Convert multiple sets of Data going from left to right to top to bottom the Pythonic way?


code:
def selectPen(pen):
    print('called selectPen with pen', pen)

def penDown():
    print('called penDown')

def drawLine(direction, length):
    print('called drawLine with direction', direction, 'and length', length)

def penUp():
    print('called penUp')

def parseSource(source):
    tempSource = [op.split(' ') for op in source]
    parsedSource = []
    for op in tempSource:
        parsedOp = []
        for i, el in enumerate(op):
            if i == 0:
                parsedOp.append(el)
            else:
                try:
                    parsedOp.append(int(el))
                except ValueError:
                    parsedOp.append(el)
        parsedSource.append(tuple(parsedOp))

    return parsedSource

def dispatch(parsedSource):
    opDict = {'P':(selectPen,), 'D':(penDown,), 'N': (drawLine, 0), 'S':(drawLine, 180),
    'E': (drawLine, 90), 'W': (drawLine, 270), 'U': (penUp,)}

    for op in parsedSource:
        methodName = op[0]
        methodToCall = opDict[methodName][0]
        args = op[1:]
        if len(opDict[methodName])>1:
            args = opDict[methodName][1:] + args

        methodToCall(*args)

if __name__ == '__main__':
    source=['P 3', 'D', 'N 4', 'E 2', 'S 4', 'W 2', 'U']
    parsedSource = parseSource(source)
    dispatch(parsedSource)

rawDescription: Creating a parsing dictionary to use with sys.argv


rawDescription: initiante matrixes with ranged random numbers in python

description: Initiante matrixes with ranged random numbers in python


code:
import random
# Lists:
anchorslist = []

#Files:
anchors = open("anchors.txt", "r")

#Placed In List:
for line in anchors:
        anchorslist.append(line.replace("\n", "|"))

anchors.close()

rand_options = anchorslist  # duplicate list, better than editting the input list
rand_vals = []
length = 3  # configure to 10, or how ever many random lines you want

for _ in range(length):
    rand_val = random.choice(rand_options)
    rand_vals.append(rand_val)
    rand_options.remove(rand_val)  # remove from list so you don't get duplicates (unless you don't mind those)

what_you_want = "".join(rand_vals).rstrip("|")

rawDescription: Python Get Multiple Random Lines From File


code: del x

rawDescription: How to set a Python variable to 'undefined'?

description: Set a Python variable to 'undefined'


code:
def __call__(self, environ, start_response):
    """function used to serve files following an http request"""
    path = environ['PATH_INFO'].strip('/') or 'index.html'
    if path == 'file_upload':
        data = environ['wsgi.input'].read(int(environ.get('CONTENT_LENGTH','0')))
        f = open('./uploaded_file', 'wb')
        f.write(data)
        f.close()
        start_response('200 OK',[('Content-Type', 'text/plain')])
        return 'OK'

rawDescription: How to receive a file upload POST request using gevent on python

description: Receive a file upload POST request using gevent on python


code:
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        # Change the keyboard variables
        if event.type == KEYDOWN:
            if event.key == K_LEFT or event.key == ord('a'):
                moveLEFT = True
            elif event.key == K_RIGHT or event.key == ord('d'):
                moveRIGHT = True
            elif event.key == K_UP or event.key == ord('w'):
                moveUP = True
            elif event.key == K_DOWN or event.key == ord('s'):
                moveDOWN = True
        elif event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
            elif event.key == K_LEFT or event.key == ord('a'):
                moveLEFT = False
            elif event.key == K_RIGHT or event.key == ord('d'):
                moveRIGHT = False
            elif event.key == K_UP or event.key == ord ('w'):
                moveUP = False
            elif event.key == K_DOWN or event.key == ord('s'):
                moveDOWN = False

         # <-- Dedent

    # Background Setup
    windowSurface.fill(WHITE)
    # Player Setup + Updating Screen
    if moveDOWN and player.bottom < WINDOWHEIGHT:
        player.top += MOVESPEED
    if moveUP and player.top > 0:
        player.top-= MOVESPEED
    if moveLEFT and player.left > 0:
        player.left -= MOVESPEED
    if moveRIGHT and player.right < WINDOWWIDTH:
        player.right += MOVESPEED
    pygame.draw.rect(windowSurface, GREEN, player)
    pygame.display.update()
    mainClock.tick(40)

rawDescription: Python: Player Movement

description: Python: Player Movement


code:
from mpl_toolkits.mplot3d import Axes3D #For plotting 3D Axes
from mpl_toolkits.basemap import Basemap #For plotting polygonal surfaces
from matplotlib.collections import PolyCollection #Polygons
import matplotlib.pyplot as plot
import matplotlib, sys
matplotlib.use("TkAgg")
from matplotlib.backnds.backend_tkagg import FigureCanvasTkAgg,\
    NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import tkinter as tk

root = tk.Tk()
f = plot.figure(figsize = (5, 5), dpi = 100)
canvas = FigureCanvasTkAgg(f, master = root)
axes = Axes3D(f)

map = Basemap()

axes.add_collection3d(map.drawcoastlines(linewidth = 0.3, color = "white"))
axes.add_collection3d(map.drawcountries(linewidth = 0.3, color = "white"))
axes.add_collection3d(map.drawstates(linewidth = 0.3, color = "white"))

polygons = []
for polygon in map.landpolygons:
    polygons.append(polygon.get_coords())
    collection = PolyCollection(polygons, edgecolor = "white",
                               facecolor = "black",
                            closed = True)

axes.add_collection3d(collection)

canvas.show()
canvas.get_tk_widget().pack(side = tk.BOTTOM, fill = tk.BOTH, expand = 1)
canvas._tkcanvas.pack(side = tk.BOTTOM, fill = tk.BOTH, expand = 1)
button = tk.Button(master = root, text = "Exit", command = sys.exit)
button.pack(side = tk.TOP)

tk.mainloop()

rawDescription: Rotating an embedded matplotlib plot

description: Rotating an embedded matplotlib plot


code:
handler = logging.FileHandler(filename)
formatter = logging.Formatter(newformat)
handler.setFormatter(formatter)

log = logging.getLogger(yourloggername)
log.setHandler(handler)
log.propagate = False   # don't send messages to the root, handle it all here

rawDescription: Changing Loggers on demand

description: Changing Loggers on demand


code:
import math
print(math.__file__)

rawDescription: Which native python modules are written in C?


code:
'foo #comment'.split('#', 1)[0]
'foo comment'.split('#', 1)[0]

rawDescription: Ignoring a comment line in file

description: Ignoring a comment line in file


rawDescription: Python: Subtracting from only one column in a list based on another condition


code:
username = input("Enter your username: ")
password = input("Enter your password: ")

#hashing
p = len(password)+3
hashValue = 0
for element in password:
    hashValue += ord(element)*(37**(p*3+2))
    p += 1

#file reading
searchfile = open("users.txt","r")
for line in searchfile:
    if username in line:
        print(line)
        passwordFile = next(searchfile)
        if hashValue == int(passwordFile):
            print("Succesfully logged in.")
        else:
            print("Denied.")

rawDescription: Login System - Reading from a file and comparing values to allow or deny entry to the system


code:
from sqlalchemy.inspection import inspect

thing_relations = inspect(Thing).relationships

rawDescription: SQLAlchemy, Flask: get relationships from a db.Model


code:
S = pygame.Surface ((w,h),0,24)
r,g,b,a =S.get_masks()

rawDescription: Do indexed Surfaces support palettes with alpha values (other than 255)?


code: dict(zip(projects,hours))

rawDescription: How to build a map from two lists using zip?

description: Build a map from two lists using zip


code:
DOUGHNUT = 1.75
SALES_TAX = 0.08625

def getNumDoughnuts():
    numDoughnuts = raw_input("How many donuts would you like to order?")
    return numDoughnuts

def calculateDoughnutPrice(numDoughnuts):
    doughnutPrice = DOUGHNUT * float(numDoughnuts)
    return doughnutPrice

def calculateSalesTax(doughnutPrice):
    taxAmount = doughnutPrice*(SALES_TAX)
    priceWithTax = taxAmount + doughnutPrice
    return priceWithTax

def displayPrice(priceWithTax):
    print(priceWithTax)

def main():
    numDoughnuts = getNumDoughnuts()
    doughnutPrice = calculateDoughnutPrice(numDoughnuts)
    priceWithTax = calculateSalesTax(doughnutPrice)
    displayPrice(priceWithTax)

main()

rawDescription: Passing Arguments in Python

description: Passing Arguments in Python


code:
s = 'Vladimir_SW_crop_mask_ERA.hdr'
s.partition('_crop')[0].rpartition('_')[::2]
s = 'Ust_Ordynskiy_Buryatskiy_AO_SW_crop_mask_ERA.hdr'
s.partition('_crop')[0].rpartition('_')[::2]

rawDescription: Regular expression in python with variable strings


code:
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        response = {}

        upload_files = self.get_uploads('file')
        blob_info = upload_files[0]

        response['error'] = False
        response['message'] = "Image uploaded."
        response['image_url'] = images.get_serving_url(blob_info.key())

        self.response.headers.add_header("Access-Control-Allow-Methods", "POST")
        self.response.headers.add_header("Access-Control-Allow-Origin", "*")

        self.response.headers['Content-Type'] = 'application/json'

        self.response.out.write(json.dumps(response))

rawDescription: Handling image upload with BlobstoreUploadHandler and returning a JSON message


code:
import socket
import threading

class ThreadedServer(object):
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((self.host, self.port))

    def listen(self):
        self.sock.listen(5)
        while True:
            client, address = self.sock.accept()
            client.settimeout(60)
            threading.Thread(target = self.listenToClient,args = (client,address)).start()

    def listenToClient(self, client, address):
        size = 1024
        while True:
            try:
                data = client.recv(size)
                if data:
                    response = data
                    client.send(response)
                else:
                    raise error('Client disconnected')
            except:
                client.close()
                return False

if __name__ == "__main__":
    port_num = input("Port? ")
    ThreadedServer('',port_num).listen()

rawDescription: How to make a simple multithreaded socket server in Python that remembers clients

description: Make a simple multithreaded socket server in Python that remembers clients


code:
from subprocess import Popen
p = Popen(['/full/path/to/ppshelper', '-sms', '15062929382','warning'])
p.terminate()

rawDescription: exiting a running command in python

description: Exiting a running command in python


code:
original = [[1, 2, 3, 4], [1, 2, 3, 4], [2, 3, 4, 5]]
transposed = zip(*original)
transposed
original[2][3]
transposed[3][2]

rawDescription: How would I succinctly transpose nested lists?


code:
Popen(["nice"]).communicate()
Popen(["nice"], preexec_fn=lambda : os.nice(10)).communicate()
Popen(["nice"], preexec_fn=lambda : os.nice(20)).communicate()

rawDescription: Is it possible to renice a subprocess?

description: Is it possible to renice a subprocess


code:
def button_action():
    b.config(state='disabled')
    b.update() # <----------
    # Activate some hardware that takes a few seconds.
    b.update() # <----------
    b.config(state='normal')

rawDescription: Preventing a Button Press From Registering TKInter/Python 3.3


code:
g = df.groupby([["%s-%s" % (d.year, d.month) for d in df.date], df.tag]).size()
g
g.unstack().fillna(0)

rawDescription: Using Pandas GroupBy and size()/count() to generate an aggregated DataFrame


code:
from collections import namedtuple
Foo = namedtuple('Foo', 'name id') # this represents your class with id attribute
a = [1,2,3,4,5]
b = [Foo(name='o', id=2), Foo(name='p', id=1), Foo(name='q', id=3), Foo(name='r', id=5), Foo(name='s', id=4)]
sorted(b, key=lambda x: a.index(x.id))

rawDescription: python sort a list of objects based on attributes in the order of the other list

description: Python sort a list of objects based on attributes in the order of the other list


code:
from datetime import date
repr(date.today())        # calls date.today().__repr__()
eval(_)                   # _ is the output of the last command

rawDescription: Python object.__repr__(self) should be an expression?


code:
import glob
for file in glob.glob("*.txt"):
    with open(file, "a") as f:
        f.write("\n\n")

rawDescription: adding two blank lines in the last of each text file

description: Adding two blank lines in the last of each text file


code:
p = np.poly1d([-1, 7, -7])
x = np.arange(20)
y = p(x)
plt.plot(x, y)
plt.show()

rawDescription: Poly1d with Matplotlib

description: Poly1d with Matplotlib


code:
options = doc.xpath("//select[@name='country']/option")
option_text = [option.text for option in options]

rawDescription: Is there any way to access <option> text when parsing forms using lxml.html?


code:
class Foo(Document):
    structure = {
        'location': {
            'lat': float,
            'lon': float
        }
    }
    indexes = [
        {
            'fields': [('location', '2d'), ],
        }
    ]

rawDescription: Geospatial Index using MongoKit

description: Geospatial Index using MongoKit


code:
import sys
from PyQt4 import QtGui, QtCore

class MyView(QtGui.QGraphicsView):
    def __init__(self, parent=None):
        QtGui.QGraphicsView.__init__(self, parent=parent)

        self.scene = QtGui.QGraphicsScene(self)
        self.item = QtGui.QGraphicsRectItem(300,400,100,100)
        self.scene.addItem(self.item)
        self.setScene(self.scene)

class Window(QtGui.QMainWindow):
    def __init__(self, parent=None):
        #This initializes the main window or form
        super(Window,self).__init__(parent=parent)
        self.setGeometry(50,50,900,700)
        self.setWindowTitle("Pre-Alignment system")

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    view = MyView(GUI)
    GUI.show()
    sys.exit(app.exec_())

run()

rawDescription: QGraphicsScene on a QMainWindow

description: QGraphicsScene on a QMainWindow


code:
minimum = min(e['dist'] for e in people)
# Don't call the variable min, that would overshadow the built-in min function
print ('minimum is ' + str(minimum))

rawDescription: Finding minimum value in an array of dicts


code:
from django.core.cache import cache

class RegistrationQuerySet(models.QuerySet):

    def active_period(self):
        try:
            active_period = cache.get('active_period')
            if not active_period:
                active_period = AcademicPeriod.objects.is_active()[0]
                cache.set('active_period', active_period)
            return self.filter(academic_period=active_period)
        except:
            return self

rawDescription: Set variable on django start and have it available in all views


code:
long_title = 'Irradiance vs Time Graph at {} to {} \n Max Value: {:.2f} at {}, Mode: {:.2f}, Average: {:.2f})'

plt.title(long_title.format(
                            startTime,
                            endTime,
                            max(y),
                            t[np.argmax(y)],
                            mode(y)[0][0],
                            np.average(y)
))

rawDescription: How Do I Display My User Input as My Graph Title (Python)


code:
import os
import cherrypy

PATH = os.path.abspath(os.path.dirname(__file__))
class Root(object): pass

cherrypy.tree.mount(Root(), '/', config={
        '/': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': PATH,
                'tools.staticdir.index': 'index.html',
            },
    })

cherrypy.quickstart()

rawDescription: How to use cherrypy as a web server for static files?

description: Use cherrypy as a web server for static files


code:
class Agent(models.Model):
    ...
    regions = models.ManyToManyField(Region, through='ARM2M')

rawDescription: django manytomany and the modelform

description: Django manytomany and the modelform


rawDescription: Is there a simple way to convert a 2d list of floats into a 2d list of tuples in python?


code:
import scandir
import os
os.walk
scandir.walk
os.walk = scandir.walk
os.walk is scandir.walk
os.walk('/')

rawDescription: How to globally overwrite/overload python functions (os.path.walk)?

description: Globally overwrite/overload python functions (os.path.walk)


rawDescription: How do I use shutil to make a python file copy itself after doing a calculation?

description: Use shutil to make a python file copy itself after doing a calculation


code:
# Ancient versions of Django created plain MD5 passwords and accepted
# MD5 passwords with an empty salt.
if ((len(encoded) == 32 and '$' not in encoded) or
        (len(encoded) == 37 and encoded.startswith('md5$$'))):
    algorithm = 'unsalted_md5'

rawDescription: Can a simple MD5 hash converted to a django password?


code:
import Tkinter

class Reminder(object):
    def __init__(self, show_interval=3, hide_interval=6):
        self.hide_int = hide_interval  # In seconds
        self.show_int = show_interval  # In seconds
        self.root = Tkinter.Tk()
        Tkinter.Frame(self.root, width=250, height=100).pack()
        Tkinter.Label(self.root, text='Hello').place(x=10, y=10)
        self.root.after_idle(self.show)  # Schedules self.show() to be called when the mainloop starts

    def hide(self):
        self.root.withdraw()  # Hide the window
        self.root.after(1000 * self.hide_int, self.show) # Schedule self.show() in hide_int seconds

    def show(self):
        self.root.deiconify() # Show the window
        self.root.after(1000 * self.show_int, self.hide)  # Schedule self.hide in show_int seconds

    def start(self):
        self.root.mainloop()

if __name__ == "__main__":
    r = Reminder()
    r.start()

rawDescription: Create a tkinter window every x minutes and then automatically close it after y seconds


rawDescription: os.path.isdir returns false when folder exists?

description: Os.path.isdir returns false when folder exists


code:
import xlwt

# d can also be a datetime object
d = 40299.2501157407

wb = xlwt.Workbook()
sheet = wb.add_sheet('new')

style = xlwt.XFStyle()
style.num_format_str = 'DD-MM-YYYY'

sheet.write(5, 5, d, style)
wb.save('test_new.xls')

rawDescription: datetime issue with xlrd & xlwt python libs

description: Datetime issue with xlrd & xlwt python libs


code:
html = '''

'''
soup = bs4.BeautifulSoup(html, 'html.parser')
soup.find_all(class_='Specific')

rawDescription: Beautiful Soup (Python) : find all kind of div, p, span, etc, with a given class


code: [hex(ord(x)) for x in unichr(0x80).encode('utf-8')]

rawDescription: Split UTF-8 encoded string got from unichr


code:
from Tkinter import *

class LabeledCheckbutton(Frame):
    def __init__(self, root):
        Frame.__init__(self, root)
        self.checkbutton = Checkbutton(self)
        self.label = Label(self)
        self.label.grid(row=0, column=0)
        self.checkbutton.grid(row=0, column=1)

root = Tk()
labeledcb = LabeledCheckbutton(root)
labeledcb.label.configure(text="checkButton Text")
labeledcb.grid(row=0, column=0)
root.mainloop()

rawDescription: Change position of checkbox relative to text in Tkinter's Checkbutton


code:
import urllib
content = urllib.urlopen('http://www.google.com/').read()

rawDescription: Python: Read a file (from an external server)


rawDescription: Selecing a large number of data points in column


code:
today = date.today()
start_of_week = today - timedelta(days=today.weekday())
start_of_following_week = start_of_week + timedelta(days=7)

weekly_schedule = WeeklyHour.query.filter(
    and_(
        WeeklyHour.start_time >= start_of_week,  # On or after Monday
        WeeklyHour.end_time < start_of_following_week, # Before next Monday
        WeeklyHour.employee == employee
        )
    ).all()

rawDescription: How can I compare just the dates of datetime in SQLAlchemy?

description: Compare just the dates of datetime in SQLAlchemy


code:
import csv

ip_file = open("ipfile.csv")
position_file = open("positionfile.csv")
output = open("output.csv", "wt")

ips = {}

# create a CSV reader for the proper csv file with locations:
reader = csv.reader(position_file)
for line in reader:
    ips[line[0]] = line[1]

#now you have the IP + location association

for line in ip_file.readlines():
    ip = line.split(",")[-1].strip()
    output.write(line.strip() + ", " + (ips[ip] if ip in ips else "location unknown") + "\n" )

output.close()

rawDescription: merge columns of a csv file in python with variable entries in every row in?

description: Merge columns of a csv file in python with variable entries in every row in


code:
def raw_disc(make):
    data_make = pd.DataFrame(disc.queryRedshift(
    """select D.model_slug,
            D.cap_engine_id,
            D.dealership_id,
            D.cash_percentage,
            D.cash_post_discount_amount as cash_post
        from quotes_site.discounts D join quotes_site.dealerships DLR
                on D.dealership_id = DLR.id
        where DLR.archived <> 't'
                 and DLR.suspended <> 't',
                -> and DLR.make = '{0}'
                 group by 1,2,3,4,5""".format(make)))
    return data_make

rawDescription: How to reference function argument in a string

description: Reference function argument in a string


code:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class Log(db.Model):
    access_time = db.DateTimeProperty(auto_now_add=True)
    ip_address = db.StringProperty()

class MainPage(webapp.RequestHandler):
    def get(self):

        # obtain ip address
        ip = self.request.remote_addr

        # create a new Log record
        log = Log()

        # assign ip address to the ip_address field
        log.ip_address = ip

        # no need to set access_time because
        # of the auto_now_add=True setting defined in the Log model

        # save to the datastore
        log.put()

        # output
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Logged your visit from ip address %s' % ip)

class LogPage(webapp.RequestHandler):
    def get(self):
        logs = Log.all()

        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Ip addresses: ')
        for log in logs:
            self.response.out.write(log.ip_address + ',')

application = webapp.WSGIApplication([('/', MainPage), ('/logs', LogPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

rawDescription: Get IP address in Google App Engine + Python


code:
from collections import Counter

Counter(map(tuple,data))
Counter(map(tuple,data)).items()

rawDescription: Python: create frequency table from 2D list


code:
import sys

try:
    from lxml import etree
except:
    import xml.etree.cElementTree as etree

doc = etree.parse('settings.xml')

settings_dict = dict([(el.attrib['id'], el) for el in doc.findall('setting')])
settings_order = ['exitonbackspace','screen2', 'refreshonload', 'hidemousepointer']

foo = open('settings.cfg', 'w')
for setting_id in settings_order:
    if setting_id in settings_dict:
        el = settings_dict[setting_id]
        foo.write("%s=%s\n" % (el.attrib['id'], el.attrib['value']))
foo.close()

rawDescription: Sorting a parsed XML file into cfg file

description: Sorting a parsed XML file into cfg file


code:
import matplotlib.pyplot as plt
import numpy as np
import Tkinter as tk
import matplotlib.figure as mplfig
import matplotlib.backends.backend_tkagg as tkagg
pi = np.pi

class App(object):
    def __init__(self, master):
        self.master = master
        self.thisPlayer = Bunch(
            rebounds=20.0,
            freeThrows=5.0,
            steal=5.0,
            underRim=10,
            distance=10)
        self.fig = mplfig.Figure(figsize=(1.5, 1.5))
        self.ax = self.fig.add_axes([0.025, 0.025, 0.95, 0.95], polar=True)
        self.canvas = tkagg.FigureCanvasTkAgg(self.fig, master=master)
        self.ax.grid(False)

        N = 5
        theta = np.arange(0.0, 2 * pi, 2 * pi / N)
        radii = [self.thisPlayer.rebounds, self.thisPlayer.freeThrows,
                 self.thisPlayer.steal, self.thisPlayer.underRim,
                 self.thisPlayer.distance]
        width = [2 * pi / (N)] * 5
        bars = (
            # self.ax.bar(0, 20, width=2 * pi, linewidth=0) +
            self.ax.bar(theta, radii, width=width, bottom=0.2))
        cmap = plt.get_cmap('jet')
        for r, bar in zip(radii, bars):
            bar.set_facecolor(cmap(r / 20.))
            bar.set_alpha(0.5)
        self.ax.set_xticklabels([])
        self.ax.set_yticklabels([])
        self.canvas.get_tk_widget().pack()
        self.canvas.draw()

class Bunch(object):
    """
    http://code.activestate.com/recipes/52308
    foo=Bunch(a=1,b=2)
    """
    def __init__(self, **kwds):
        self.__dict__.update(kwds)

def main():
    root = tk.Tk()
    app = App(root)
    tk.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Python Tkinter: Embed a matplotlib plot in a widget


code: dict((x['id'], x) for x in L).values()

rawDescription: How do I remove dicts from a list with duplicate fields in python?

description: Remove dicts from a list with duplicate fields in python


code:
from django.contrib.auth.views import login

urlpatterns = ('',
    #snip
    url(r'^login/$', login)
)

rawDescription: Can we use the login page at /admin in django for our own use?


code:
class Meter():
    def __init__(self, dev):
        self.dev = dev
    def __enter__(self):
        #ttysetattr etc goes here before opening and returning the file object
        self.fd = open(self.dev, MODE)
        return self.fd
    def __exit__(self, type, value, traceback):
        #Exception handling here
        close(self.fd)

meter = Meter('dev/tty0')
with meter as m:
    #here you work with the file object.
    m.read()

rawDescription: Implementing use of 'with object() as f' in custom class in python


code:
from datetime import datetime

for tr in browser.find_by_tag("tr"):
    sorted_on = tr.find_by_css(".sorted-on")

    try:
        datetime.strptime(sorted_on.text, "%B %d, %Y")
    except ValueError:
        continue

rawDescription: Splinter find_by_xpath: using regex for element text()


code:
from Tkinter import *
import tkFont

def on_enter(event):
    event.widget.configure(font="underlined_font")

def on_leave(event):
    event.widget.configure(font="normal_font")

root=Tk()
root.geometry('100x100+100+100')

normal= tkFont.Font(name="normal_font")
underlined = tkFont.Font(name="underlined_font", underline=True)

lbl1 = Label(root, text='Label 1', font="normal_font")
lbl1.bind('<Enter>', on_enter)
lbl1.bind('<Leave>', on_leave)
lbl1.pack()
lbl2 = Label(root, text='Label 2', font="normal_font")
lbl2.bind('<Enter>', on_enter)
lbl2.bind('<Leave>', on_leave)
lbl2.pack()
lbl3 = Label(root, text='Label 3', font="normal_font")
lbl3.bind('<Enter>', on_enter)
lbl3.bind('<Leave>', on_leave)
lbl3.pack()

mainloop()

rawDescription: Python, Tkinter, tkFont: Label resize

description: Python, Tkinter, tkFont: Label resize


code:
def _tuple_to_list(self, el):

    if type(el) is tuple:
        el = self._tuple_to_list(list(el))
    elif type(el) is dict:
        for (key, value) in el.items():
            el[key] = self._tuple_to_list(value)
    elif type(el) is list:
        for i in range(len(el)):
            el[i] = self._tuple_to_list(el[i])

    return el

rawDescription: Tuple in Couchdbkit

description: Tuple in Couchdbkit


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

fig = plt.figure(figsize=(8, 8))
ax = fig.add_axes([.1, .1, .8, .8])
im = ax.imshow(np.random.rand(150, 150), cmap='gray', interpolation='none')
sc = ax.scatter(2 + 146 * np.random.rand(150), 2 + 146 * np.random.rand(150),
                c=np.random.rand(150), cmap='Accent', s=50, lw=0)

ax_cb1 = fig.add_axes([.1, .05, .8, .02])
ax_cb2 = fig.add_axes([.92, .1, .02, .8])

cb1 = fig.colorbar(im, cax=ax_cb1, orientation='horizontal')
cb1.ax.xaxis.set_label_position('top')
cb2 = fig.colorbar(sc, cax=ax_cb2, orientation='vertical')

rawDescription: Positioning color bars - Matplotlib

description: Positioning color bars - Matplotlib


rawDescription: filter with more than one value on flask-sqlalchemy

description: Filter with more than one value on flask-sqlalchemy


code:
maxsize = (1028, 1028)
image.thumbnail(maxsize, PIL.Image.ANTIALIAS)

rawDescription: Python / Pillow: How to scale an image

description: Python / Pillow: How to scale an image


code:
def load_ui(ui_file, parent=None):
    loader = QUiLoader()
    file = QFile(ui_file)
    file.open(QFile.ReadOnly)
    myWidget = loader.load(file, None)
    file.close()
    return myWidget

main_window = load_ui("ui/main_window.ui")
dock_widget = load_ui("ui/console.ui", main_window)
main_window.show()
main_window.addDockWidget(Qt.LeftDockWidgetArea, dock_widget)

rawDescription: dock widget loaded from separate ui file to main window

description: Dock widget loaded from separate ui file to main window


code:
already_seen = set()
for line in sys.stdin:
   if line not in already_seen:
      already_seen.add(line)
      sys.stdout.write(line)

rawDescription: how to prevent duplicate text in the output file while using for loop

description: Prevent duplicate text in the output file while using for loop


code:
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chromedriver = "path/to/chromedriver"

os.environ["webdriver.chrome.driver"] = chromedriver
chrome_options = Options()

# this is the preference we're passing
prefs = {'profile.default_content_settings.multiple-automatic-downloads': 1}
chrome_options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)

# just downloading some files...
for _ in range(5):
    driver.get("http://code.jquery.com/jquery-1.11.3.min.map")

driver.quit()

rawDescription: Python Selenium Chrome disable prompt for "Trying to download multiple files"


code:
# http://docs.python.org/2/library/itertools.html
def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

def avg(xs):
    xs = [x for x in xs if x is not None]
    return sum(xs) / len(xs)

# Retrieve all `total` values as a flat list-like ValueListQuerySet.
values = resume.objects.all().values_list('total', flat=True)
avgs = [avg(xs) for xs in grouper(values, 3)]

rawDescription: DJANGO Average (mean) of a whole model field in groups of 3


code:
import os
import time

def checkfile(filename):
    filestats = os.stat(filename) # Gets infromation on file.
    if time.time() - filestats.st_mtime > 120: # Compares if file modification date is more than 120 less than the current time.
        os.remove(filename) # Removes file if it needs to be removed.

path = '/path/to/folder'

dirList = os.listdir(path) # Lists specified directory.
for filename in dirList:
    checkfile(os.path.join(path, filename)) # Runs checkfile function.

rawDescription: Converting a system command to python for file search and delete


code:
import csv

def addRowToDict(row):
    global myDict
    key=row[1]
    if key in myDict.keys():
        #append values if entry already exists
        myDict[key].append(row[0])
    else:
        #create entry
        myDict[key]=[row[1],row[0]]

global myDict
myDict=dict()
inFile='C:/Users/xxx/Desktop/pythons/test.csv'
outFile='C:/Users/xxx/Desktop/pythons/testOut.csv'

with open(inFile, 'r') as f:
    reader = csv.reader(f)
    ignore=True
    for row in reader:
        if ignore:
            #ignore first row
            ignore=False
        else:
            #add entry to dict
            addRowToDict(row)

with open(outFile,'w') as f:
    writer = csv.writer(f)
    #write everything to file
    writer.writerows(myDict.itervalues())

rawDescription: Python CSV writer

description: Python CSV writer


code:
class MySurface(object):
    def __init__(self, surface):
        self._surface = surface

    def blit(self, source, dest, area=None, special_flags = 0):
        return self._surface.blit(source, dest, area, special_flags)

    # code to forward all the other members

    def myblit(self, source, dest):
        # code that modifies source and dest
        return self._surface.blit(source, dest)

mysurf = MySurface(pygame.display.set_mode())

rawDescription: How to, in A.py, extend class defined in B.py that is used by C.py


code:
from bigpackage.subpackage.modulefile import function1, function2

function1(bla, bla, bla)

rawDescription: Python package/module import functions from sub packages


code:
import openpyxl as xl
import pandas as pd

wb = xl.load_workbook('deleteme.xlsx')
ws = wb.get_sheet_by_name('Sheet1')
df = pd.read_excel('deleteme.xlsx')

def replace_first_null(df, col_name, value):
    """
    Replace the first null value in DataFrame df.`col_name`
    with `value`.
    """
    return_df = df.copy()
    idx = list(df.index)
    last_valid = df[col_name].last_valid_index()
    last_valid_row_number = idx.index(last_valid)
    # This next line has mixed number and string indexing
    # but it should be ok, since df is coming from an
    # Excel sheet and should have a consecutive index
    return_df.loc[last_valid_row_number + 1, col_name] = value
    return return_df

def write_df_to_worksheet(ws, df):
    """
    Write the values in df to the worksheet ws in place
    """
    for i, col in enumerate(replaced):
        for j, val in enumerate(replaced[col]):
            if not pd.isnull(val):
                # Python is zero indexed, so add one
                # (plus an extra one to take account
                #  of the header row!)
                ws.cell(row=j + 2, column=i + 1).value = val

# Here's the actual replacing happening
replaced = replace_first_null(df, 'C', 'xxx')
write_df_to_worksheet(ws, df)
wb.save('changed.xlsx')

rawDescription: Python Find highest row in a given column


code:
filen = 'filename.txt'
x = loadtxt(fn,unpack=True,usecols=[0])
y = loadtxt(fn,unpack=True,usecols=[1])

n = ma.masked_where(gradient(y) < 0, y)
p = ma.masked_where(gradient(y) > 0, y)

pylab.plot(x,n,'r',x,p,'g')

rawDescription: Assigning colour to data depending on sign of gradient (Python)


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
epsi = 0.01
# Declare the model
f_dir = np.arange(0,1.3,0.01)
A_s = np.zeros(len(f_dir))

def myModel(y, t, f):
    dy0 = y[1]
    dy1 = -epsi*y[1]-np.sin(y[0]) - f*np.cos((1.01)*t)*np.cos(y[0])
    return [dy0, dy1]

i = 0
for f in f_dir:
    time = np.arange(0.0, 2000,0.01)
    yinit = np.array([np.pi/2, 0])
    y = odeint(myModel, yinit, time, args=(f,))
    A_s[i] = np.abs(np.max(y[-600:-1,0])- np.min(y[-600:-1,0]))
    i += 1

plt.plot(f_dir,A_s,'*')
plt.xlabel(r'$f_s$')
plt.ylabel(r'$A_s$')
plt.hold
plt.show()

rawDescription: Loop and bifurcation diagram

description: Loop and bifurcation diagram


code:
def answer(census):
    size = len(census)
    return size if sum(census) % size == 0 else (size-1)

rawDescription: Evenly distribute within a list (Google Foobar: Maximum Equality)


code:
YEAR_IN_SCHOOL_CHOICES = (
    ('FR', 'Freshman'),
    ('SO', 'Sophomore'),
    ('JR', 'Junior'),
    ('SR', 'Senior'),
)
class Student(models.Model):
    year_in_school = models.CharField(max_length=2,
                                  choices=YEAR_IN_SCHOOL_CHOICES, default='FR')

rawDescription: how to model status for a task in django model

description: Model status for a task in django model


code:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([[2,10],[5,8],[3,8],[6,9]]),columns=["start","end"])

active_events= {}
for i in df.index:
    active_events[i] = len(df[(df["start"]<=df.loc[i,"start"]) & (df["end"]> df.loc[i,"start"])])
last_columns = pd.DataFrame({'No. active events' : pd.Series(active_events)})

df.join(last_columns)

rawDescription: Pandas Cumulative Sum using Current Row as Condition


code:
import re

regex = re.compile(r"[;>](?P<description>[^\n]*)\n(?P<sequence>[^;>]+)")

with open("datafile.txt","r") as f:

    sequences = regex.findall(f.read())
    for i, info in enumerate(sequences):
            description, sequence = info
            print("sequence%d: %s" % (i, sequence.replace("\n","")))

rawDescription: How to read in specific lines from file

description: Read in specific lines from file


code: grouped.apply(lambda x: pd.Series([tuple(i) for i in x.values]))

rawDescription: Grouping a dataframe and applying tuple

description: Grouping a dataframe and applying tuple


code:
means = df.groupby(['Comp', 'Dept'])['Salary'].mean()
means.unstack(0).sort(ascending=False)
df.groupby(['Comp', 'Dept'])['Salary'].max().unstack(0).sort(ascending=False)

rawDescription: Python Pandas : Pivot groupby object

description: Python Pandas : Pivot groupby object


code:
def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

rawDescription: Pythonic way to emulate itertools.product in python 2.4


code:
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://www.nike.com/us/en_us/c/men")
driver.maximize_window()

wait = WebDriverWait(driver, 10)
actions = ActionChains(driver)

# open men's hover menu in top nav bar
men_menu = driver.find_element_by_css_selector("li[data-nav-tracking=men]")
actions.move_to_element(men_menu).perform()

# click shirt
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "li[data-nav-tracking=men] a[data-subnav-label$=Shirts]"))).click()

rawDescription: How to click a link in a hover menu with Selenium webdriver?

description: Click a link in a hover menu with Selenium webdriver


code:
class Labeller(type):
    def __new__(meta, name, bases, dct):
        dct.setdefault('label', name)
        return super(Labeller, meta).__new__(meta, name, bases, dct)

# Python 2
# class Super(object):
#    __metaclass__ = Labeller

class Super(metaclass=Labeller):
    pass

class Sub(Super):
    pass

class SecondSub(Super):
    label = 'Pie'

class ThirdSub(SecondSub):
    pass

rawDescription: Python Class Name as Class Variable

description: Python Class Name as Class Variable


code: a = dict.fromkeys(range(n))

rawDescription: python dict set min_size

description: Python dict set min_size


code:
boundaries = [0.009, 380.2, 389.8, 390.2, 399.8, 410.2]
values = [None, -39, -94, -39, -60, -39, None]

# what you need
import bisect
values[bisect.bisect_left(boundaries, x)]

rawDescription: General python function with many interval cases that returns specific values depending on interval


code:
def run():
    while True:
        item = work_queue.get()
        work(item)
        work_queue.task_done()

rawDescription: Determine if worker threads are doing any work


code: opt = Toplevel()

rawDescription: Widgets on created window appear on parent window instead


code:
def my_decorator(f):
    def inner_func(calling_obj, *args, **kwargs):
        stack = inspect.stack()
        caller_obj = stack[1][0].f_locals["self"]
        # caller_obj is the caller of my_method
        return f(calling_obj, *args, **kwargs)
    return inner_func

class caller_class():
    def __init__(self):
        p = test_class()
        p.my_method()

class test_class():
    @my_decorator
    def my_method(self):
        pass

rawDescription: How to get the caller of a method in a decorator, in python?

description: Get the caller of a method in a decorator, in python


code:
from pprint import pprint
import re
x = ['this is a foo bar', 'you are a foo bar black sheep']
def words_and_char_bigrams(text):
    words = re.findall(r'\w{3,}', text)
    for w in words:
        yield w
        for i in range(len(w) - 2):
            yield w[i:i+2]

v = CountVectorizer(analyzer=words_and_char_bigrams)
pprint(v.fit(x).vocabulary_)

rawDescription: How do I use sklearn CountVectorizer with both 'word' and 'char' analyzer? - python

description: Use sklearn CountVectorizer with both 'word' and 'char' analyzer? - python


rawDescription: What is the simplest way to concatenate all of the DataFrames in a Pandas Panel?


code:
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM YOUR_TABLE")
result_set = cursor.fetchall()
field_names = [val[0] for val in cursor.description]

with open('mytable1.txt', 'a') as f:
    for row in result_set:
       line = ','.join(row[field_name] for field_name in field_names)
       f.write(line)

rawDescription: Write database rows to file in python

description: Write database rows to file in python


code:
def export(modeladmin, request, queryset):
    """
    not sure if this will work
    """
    request.session['export_querset'] = queryset

    """
    if above does not work then just set this and check for it in view and u can make the queryset again if this is set
    """
    request.session['export_querset'] = 1
    return HttpResponseRedirect("/export/")

rawDescription: Django: Passing a queryset to another view with HttpResponseRedirect


code:
def get_stats(group):
    return {'mean': group.mean(), 'std': group.std(),
            'hit_r': group.apply(lambda x: x >= 0).sum() / float(group.count())}

rawDescription: How to apply a custom formula over a group element in a grouped.apply().unstack() method?

description: Apply a custom formula over a group element in a grouped.apply().unstack() method


code:
from matplotlib.patches import Rectangle, FancyBboxPatch
import matplotlib.pyplot as plt

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

bbox1 = Rectangle((0.4, 0.4), .1, .1,
                  transform=ax.transData, ec='red',fill=False)

bbox2 = FancyBboxPatch((0.4, 0.4), .1, .1, boxstyle='square,pad=0',
                       transform=ax.transData, ec='green',fill=False)
ax.add_patch(bbox1)
ax.add_patch(bbox2)

f.show()

rawDescription: Behavior inconsistency between Rectangle and FancyBboxPatch


code:
from collections import defaultdict

d1 = defaultdict(list)

for k, v in l:
    d1[k].append(v)

d = dict((k, tuple(v)) for k, v in d1.iteritems())

rawDescription: Python: list to dictionary, multiple values per key


code:
counter.most_common()
[key for key, _ in counter.most_common()]

rawDescription: Counter to List

description: Counter to List


code:
from textwrap import dedent
import types

def lol(code):
    globals_ = {"__builtins__": None}  # no built-ins for safety
    locals_ = {}

    exec(code, globals_, locals_)

    if len(locals_) != 1:
        raise ValueError("code didn't define exactly one item")
    value = locals_.popitem()[1]  # get value of the one item defined
    if type(value) != types.FunctionType:
        raise ValueError("code didn't define a function")

    return value  # return function object that was defined

my_code = dedent("""
    def foo():
        return 'bar'
""")

a = lol(my_code)
print(a())

rawDescription: Returning a function of unknown name from within a function


code: b.config(text="new text goes here")

rawDescription: Changing attributes of a button in python


code:
new={tuple(i) for i in map(sorted,X)}
new

rawDescription: Get all unique combinations from list of permutations


code:
dict={'000': 'A', '001': 'B', '010': 'C'}

[int(ele, 2) for ele in dict]
# getting this shuffled, since the `dict items` are `random`
{int(k, 2): v for k, v in dict.items()}

rawDescription: Binary to integer, python, dictionary

description: Binary to integer, python, dictionary


code:
def stripcell(cell, pattern):
    """Check if the first line of the cell's content matches `pattern`"""
    if cell["cell_type"] == "code":
        content = cell["input"]
    else:
        content = cell["source"]
    return ( len(content) > 0 and re.search(pattern, content[0]) )

pattern = r"^# SOLUTION:"

struct = json.load(open("input.ipynb"))
cells = struct["worksheets"][0]["cells"]
struct["worksheets"][0]["cells"] = [ c for c in cells if not stripcell(c, pattern) ]

json.dump(struct, open("output.ipynb", "wb"), indent=1)

rawDescription: Maintaining two versions of an ipython notebook


code:
import requests, re
from xml.etree import ElementTree
from collections import Counter

def main(n=10):

    # A list of feeds to process and their xpath
    feeds = [
        {'url': 'http://www.nyartbeat.com/list/event_type_print_painting.en.xml', 'xpath': './/Description'},
        {'url': 'http://feeds.feedburner.com/FriezeMagazineUniversal?format=xml', 'xpath': './/description'},
        {'url': 'http://www.artandeducation.net/category/announcement/feed/', 'xpath': './/description'},
        {'url': 'http://www.blouinartinfo.com/rss/visual-arts.xml', 'xpath': './/description'},
        {'url': 'http://www.art-agenda.com/category/reviews/feed/', 'xpath': './/description'}
    ]

    # A place to hold all feed results
    results = []

    # Loop all the feeds
    for feed in feeds:
        # Append feed results together
        results = results + process(feed['url'], feed['xpath'])

    # Join all results into a big string
    contents=",".join(map(str, results))

    # Remove double+ spaces
    contents = re.sub('\s+', ' ', contents)

    # Remove everything that is not a character or whitespace
    contents = re.sub('[^A-Za-z ]+', '', contents)

    # Create a list of lower case words that are at least 6 characters
    words=[w.lower() for w in contents.split() if len(w) >=6 ]

    # Count the words
    word_count = Counter(words)

    # Clean the content a little
    filter_words = ['artist', 'artists']
    for word in filter_words:
        if word in word_count:
            del word_count[word]

    # And the survey says...
    print("The Top {0} words".format(n))
    for word, count in word_count.most_common(n):
        print("{0}: {1}".format(word, count))

def process(url, xpath):
    """
    Downloads a feed url and extracts the results with a variable path
    :param url: string
    :param xpath: string
    :return: list
    """
    contents = requests.get(url)
    root = ElementTree.fromstring(contents.content)
    return [element.text.encode('utf8') if element.text is not None else '' for element in root.findall(xpath)]

if __name__ == "__main__":
    main()

rawDescription: How to parse multiple XMLs (rss) from different websites for a single processing

description: Parse multiple XMLs (rss) from different websites for a single processing


code:
from sqlalchemy.ext.hybrid import Comparator, hybrid_property

class ProgramComparator(Comparator):
    def __eq__(self, other):
        # Should check for case of `other is None`
        return self.__clause_element__() == other.raw

class Member(Base):
    # ...
    program_raw = Column(String(80), index=True)

    @hybrid_property
    def program(self):
        return Program(self.program_raw)

    @program.comparator
    def program(cls):
        # program_raw becomes __clause_element__ in the Comparator.
        return ProgramComparator(cls.program_raw)

    @program.setter
    def program(self, value):
        self.program_raw = value.raw

rawDescription: Filter by an object in SQLAlchemy

description: Filter by an object in SQLAlchemy


code:
if PythonVersion < 2.6: # obviously not how it's done
  def myextract(self, member, path=None, pwd=None):
     ...
  zipfile.ZipFile.extract = myextract

rawDescription: How to let Python 2.4.3 have the ability of extracting ZIP file that is introduced in Python 2.6?

description: Let Python 2.4.3 have the ability of extracting ZIP file that is introduced in Python 2.6


code:
import os
for root, dirs, files in os.walk(path):
    for filename in files:
        filename = os.path.join(root, filename)
        print(filename)

rawDescription: Is there existing any utilities to get all absolute path of leaf file under a given directory?


code:
from pymongo import Connection
connection = Connection('localhost', 27017) #Connect to mongodb

print(connection.database_names())  #Return a list of db, equal to: > show dbs

db = connection['testdb1']          #equal to: > use testdb1
print(db.collection_names())        #Return a list of collections in 'testdb1'
print("posts" in db.collection_names())     #Check if collection "posts"
                                            #  exists in db (testdb1)

collection = db['posts']
print(collection.count() == 0)    #Check if collection named 'posts' is empty

collection.drop()                 #Delete(drop) collection named 'posts' from db

rawDescription: to determine whether collection in mongodb exists in python

description: To determine whether collection in mongodb exists in python


code:
import importlib
import os.path

name2decode = os.path.splitext(name2decode)[0]
module = importlib.import_module(name2decode)
dictionary = getattr(module, dictname)

rawDescription: Importing a dictionary from a module which has its name in a variable


code:
analytics_ids = {
  'mydomain.br': 'UA-637933-12',
  'mydomain.com': 'UA-637933-18',
}

data['analytics'] = analytics_ids[self.request.host]

rawDescription: Making google analytics ID a variable

description: Making google analytics ID a variable


code:
def Strings():

  strings = input("Please enter a list of strings: ")
  List = strings.replace('"','').replace('[','').replace(']','').split(",")

  return List

def Capitalize(parameter):
  r = []
  for i in parameter:
    m = ""
    for j in i.split():
      m += j[0].upper() + j[1:] + " "
    r.append(m.rstrip())

  return '["' + '","'.join(r)+ '"]'

def main():
  y = Strings()
  x = Capitalize(y)
  print(x)

main()

rawDescription: How to capitalize the title of each string in a list?

description: Capitalize the title of each string in a list


code: inputfield.bind('<Return>', lambda _: program())

rawDescription: Press Enter Instead of Clicking Button

description: Press Enter Instead of Clicking Button


code:
import sounddevice as sd
myrec = sd.playrec(mydata, input_mapping=[2])

rawDescription: How do you specify input channel for multiple mics in pyaudio?

description: Specify input channel for multiple mics in pyaudio


code:
import Tkinter as tk

def demo(master):
    listbox = tk.Listbox(master)
    listbox.pack(expand=1, fill="both")

    # inserting some items
    for names in [0,1,-2,3,4,-5,6]:
        listbox.insert("end", names)
        listbox.itemconfig("end", bg = "red" if names < 0 else "green")

        #instead of one-liner if-else, you can use common one of course
        #if item < 0:
        #     listbox.itemconfig("end", bg = "red")
        #else:
        #     listbox.itemconfig("end", bg = "green")

if __name__ == "__main__":
    root = tk.Tk()
    demo(root)
    root.mainloop()

rawDescription: Changing colour of item in Tkinter listbox


code: ranksdf["t_wins"]  = ranksdf.apply(lambda x: len(matchesdf[(matchesdf['t_date'] < x['date']) & (matchesdf['w_name'] == x['player']) & (matchesdf['round'] == 'F')]), axis =1)

rawDescription: adding column to dataframe based on count from another dataframe

description: Adding column to dataframe based on count from another dataframe


code:
parts = rule.split(" ")
aclName, _, lineNumber, _, action, protocol = parts[:6]
endpoints = parts[6:]

def get_endpoint(eps):
    host, port = "*", "*"
    if eps[0] == "host":
        host = eps[1]
        eps = eps[2:]
    elif eps[0] == "any":
        eps = eps[1:]
    else:
        host = eps[0] + "/" + mask_to_bits(eps[1])
        eps = eps[2:]

    if eps and eps[0] == 'eq':
        port = eps[1]
        eps = eps[2:]
    return host, port, eps

sourceIP, sourcePort, endpoints = get_endpoint(endpoints)
destIP, destPort, endpoints = get_endpoint(endpoints)

rawDescription: Parsing firewall rules in Python

description: Parsing firewall rules in Python


code:
import serial, time, struct

ser = serial.Serial("/dev/ttyAMA0", 9600)

while True:

    count = 0
    AValue = []
    for ch in ser.read():
        if ch == "\n":
            AValue = []
            time.sleep(0.1)

    while count < 4:
        for ch in ser.read():
            AValue.append(ch)
            count += 1

rawDescription: how to show UART received data (on PIN 10, RX) of Raspberry pi on Tkinter Window

description: Show UART received data (on PIN 10, RX) of Raspberry pi on Tkinter Window


code:
# Flush after 100 messages, or 10 seconds.
@app.task(base=Batches, flush_every=100, flush_interval=10)
def count_click(requests):
    from collections import Counter
    count = Counter(request.kwargs['url'] for request in requests)
    for url, count in count.items():
        print('>>> Clicks: {0} -> {1}'.format(url, count))

rawDescription: Celery Task Grouping/Aggregation

description: Celery Task Grouping/Aggregation


code:
from fabric.api import *
from fabric.decorators import hosts, parallel, serial
import random

@task
@serial
@with_settings(warn_only=False)
def maybe_fail():
    if random.randint(0,3) == 0:
        run("/bin/false")
    else:
        run("/bin/true")

rawDescription: Is there a way to conduct rolling deployment in fabric files?


code:
#Modified code from main loop:
s = serial.Serial(5)

#Modified code from thread reading the serial port
while 1:
  tdata = s.read()           # Wait forever for anything
  time.sleep(1)              # Sleep (or inWaiting() doesn't give the correct value)
  data_left = s.inWaiting()  # Get the number of characters ready to be read
  tdata += s.read(data_left) # Do the read and combine it with the first character

  ... #Rest of the code

rawDescription: Using PySerial is it possble to wait for data?


code: c = Checkbutton(master, ... ,selectcolor="blue") #instead of name, it can be #RGB

rawDescription: How to set the background color of little box in Tkinter Checkbox widget

description: Set the background color of little box in Tkinter Checkbox widget


code:
bins = [0.1 * i for i in range(12)]
plt.hist([random.triangular(0,1,0) for i in xrange(2500)], bins)

rawDescription: Random numbers that follow a linear drop distribution in Python


rawDescription: Why mutable entities cannot be a dictionary key?


code:
...
gui.after(1, do_something)
gui.mainloop()

rawDescription: tkinter sequential execution ordering

description: Tkinter sequential execution ordering


code:
url(r'^public/search/$', MyView.as_view(template_name="search1.html"), name= 'public_search')
url(r'^private/search/$', MyView.as_view(template_name="search2.html"), name= 'private_search')

rawDescription: How can i change the template for different urls

description: Change the template for different urls


code:
class StartMenu(Screen):

  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.save_state = None
    no_save = Label('No save file found. Please press new game.', hidden=True)
    self.add_widget(no_save)

  def check_save(self):
    if not self.save_state:
       self.no_save.hidden = False
       def hide_label(w): w.hidden = True
       Animation(opacity=0, duration=1, on_complete=hide_label).start(self.no_save)

rawDescription: Having a label fade out in kivy

description: Having a label fade out in kivy


code:
import math
def calculate_area(func):
    def _area(a, b):
        return a + b
    return _area

class Donut():
    def __init__(self, outer, inner):
        self.inner = inner
        self.outer = outer

    @staticmethod
    @calculate_area
    def area(cls):
        outer, inner = self.radius, self.inner
        return ""

rawDescription: Bound functions and decorators in python


code:
class ToggleAction(argparse.Action):
    def __call__(self, parser, ns, values, option):
        setattr(ns, self.dest, bool("-+".index(option[0])))
ap = ArgumentParser(prefix_chars='-+')
ap.add_argument('-s', '+s', action=ToggleAction, nargs=0)

ap.parse_args(['+s'])
Namespace(s=True)

ap.parse_args(['-s'])
Namespace(s=False)

rawDescription: Python argparse toggle flags

description: Python argparse toggle flags


code:
import inspect

class MyObject(object):
    def __init__(self):
        self.b = 1
        self.c = 'a'
    def func(self):
        pass

obj = MyObject()
# Get all the user created attributes for the object
attributes = [d for d in dir(obj)
              if not d.startswith('__')]
# Filter those to get the non functions
properties = [a for a in attributes
              if not inspect.ismethod(getattr(obj,a))]

rawDescription: SwigPyObject and JSON communication inside python code


rawDescription: Fill the gap in every row of ObjectListView how?


code: new_api_form = ChangeApiForm(request.POST, instance=request.user.userprofile)

rawDescription: Django form not overwriting previous entry


code:
string_input = raw_input()
input_list = string_input.split() #splits the input string on spaces
# process string elements in the list and make them integers
input_list = [int(a) for a in input_list]

rawDescription: How to make a list from a raw_input in python?

description: Make a list from a raw_input in python


code:
#    import your java package by this way
import com.yourcomp.yourpackage as yourpackage

#   gets superclass
def get_ancestor_4_class( c ):
    if not c or not c.__bases__: return java.lang.Object
    return c.__bases__[0].__name__

#   there all class to ancestor
#   mapping will be placed
class2ancestor = {}

#   list (generator) of all classes in yourpackage
yourclasses = (eval('yourpackage.%s' % classname) \
    for classname in dir( yourpackage ))

#    showtime!
for c in yourclasses:
    class2ancestor[ c.__name__ ] = get_ancestor_4_class( c ).__name__

rawDescription: How to create a dict that contains Java Classes hierarchy (in Python)?

description: Create a dict that contains Java Classes hierarchy (in Python)


code:
for number, row in enumerate(cursor.fetchall()):
    for column, cell in enumerate(row):
        sheet.write(number, column, cell)

rawDescription: How to insert data from a SQL SELECT into a spreadsheet

description: Insert data from a SQL SELECT into a spreadsheet


code:
for indx, f in enumerate(os.listdir(path), start=1):
    image = cv2.imread(os.path.join(my_dir, 'attachments', f))
    cv2.imshow("Image-{}".format(indx), image)
    cv2.waitKey(600)

rawDescription: Using Python and OpenCv to sequentially display all the images in a directory


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

@app.route("/")
def hello():
    return "Hello World!"

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

rawDescription: create html with python script

description: Create html with python script


code:
sock = socket.socket()
sock.connect(('localhost', 9999))
sock.sendall('update')
sock.close()

rawDescription: Best way to pass variable from python to C in real time

description: Pass variable from python to C in real time


code:
where = "Month(posted_date)='09'"
monthPillDetails=Revenue_Report.objects.extra(where=[where])

rawDescription: filter result based on the date(month and year)

description: Filter result based on the date(month and year)


code:
env.user = 'root'

@roles('web')
def deploy():
    dev_path = '/srv/web/prod'
    app_path = '/srv/web/prod/rhino'
    workon = 'workon rhino_env; '
    with settings(warn_only=True):
        run('kill -9 `cat /srv/web/run/rhino/rhino.pid`')
        puts('Stopped rhino...')
    with cd(app_path):
        sudo('git reset --hard HEAD', user='web')
        puts('Discarded all untracked and modified files')
        sudo('git checkout master', user='web')
        sudo('git pull origin master', user='web')
        users = run('users')
        puts('Output from `users` command: %s' % users)

        with prefix(workon):
            sudo('build_assets -m build', user='web')
    with cd(dev_path):
        run('chown -R web:ebalu rhino')

    with cd(app_path):
        sudo('./run', user='web')

    pid = run('cat /srv/web/run/rhino/rhino.pid')
    puts('Rhino started again with pid: %s.' % pid)

rawDescription: Switching user in Fabric

description: Switching user in Fabric


code:
import datetime
date_to = max(dates)
date_from = date_to - datetime.timedelta(days=num_days)
item_count = len([d for d in dates if d >= date_from])

rawDescription: Plotting specific number of days from a csv in python


code:
from Tkinter import *
root = Tk()

text2 = Text(root, height=20, width=50)

## create separate tags for separate fonts
text2.tag_configure('normal', font=('Arial', 20))
text2.tag_configure('italics', font=('Arial', 20,'italic'))
text2.tag_configure('bold', font=('Arial', 20,'bold'))
text2.tag_configure('underline', font=('Arial', 20,'underline'))
text2.tag_configure('all', font=('Arial', 20,'bold','italic','underline'))

##use the tags to print text in a particular font
text2.insert(END,'This text is Normal\n','normal' )
text2.insert(END,'This text is Bold\n', 'bold')
text2.insert(END, "this text is italics\n", 'italics')
text2.insert(END, "this text is underline\n", 'underline')
text2.insert(END, "this text is everything\n", 'all')
text2.pack(side=LEFT)

root.mainloop()

rawDescription: Adding emphasis to a text editor?

description: Adding emphasis to a text editor


code:
def timedcall(fn, *args):
    "Call function with args; return the time in seconds and result."
    t0 = time.clock()
    result = fn(*args)
    t1 = time.clock()
    return t1-t0, result

rawDescription: Which is faster: using django database order_by or list sort?


code:
import logging
import logging.handlers

class AssertingHandler(logging.handlers.BufferingHandler):

    def __init__(self,capacity):
        logging.handlers.BufferingHandler.__init__(self,capacity)

    def assert_logged(self,test_case,msg):
        for record in self.buffer:
            s = self.format(record)
            if s == msg:
                return
        test_case.assertTrue(False, "Failed to find log message: " + msg)

def cook_eggs():
    logging.warn("eggs are ready!")

import unittest

class TestLogging(unittest.TestCase):

    def test(self):
        asserting_handler = AssertingHandler(10)
        logging.getLogger().addHandler(asserting_handler)
        cook_eggs()
        asserting_handler.assert_logged(self,"eggs are ready!")
        logging.getLogger().removeHandler(asserting_handler)

unittest.main()

rawDescription: Python + nose: make assertions about logged text?


code:
import os
top = 'C:\\CIRP\\Velocidata\\Test\\'

# Getting the list of all files
for root, dirs, files in os.walk(top):

    # Filtering for group names that are 'Inprogress'
    groups_in_progress = []
    for name in files:
        if 'Inprogress' in name:
            group = name[0:name.lower().find('infile')]
            groups_in_progress.append(group.lower())

    # Delete the files where a group is in progress
    for name in files:
        for group in groups_in_progress:
            if name.lower().startswith(group):
                os.remove(os.path.join(root, name))

rawDescription: Identify a group of file and process based on a pattern : Python


code:
f = open('file.txt', 'r+')
f.seek(-2, 2) # last character in file
if f.read(2) == '\n\n':
   f.seek(-1, 1) # wow, we really did find a newline! rewind again!
f.write('orange')
f.close()

rawDescription: Appending line to a existing file having extra new line in Python


code:
pdcurses_path = ctypes.util.find_library('pdcurses.dll')
if pdcurses_path:
    pdcurses = ctypes.CDLL(pdcurses_path)
else:
    raise ImportError("could not locate pdcurses.dll library")

rawDescription: Avoiding having to put DLLs in CWD

description: Avoiding having to put DLLs in CWD


code:
from functools import partial
from difflib import SequenceMatcher

rawDescription: Longest common substring between two long lists


code:
import json
data={}
with open('data.txt', 'w') as outfile,open("tree_0","r") as f:
    for line in f:
       sp=line.split()
       data.setdefault("data",[]).append({"text": sp[-1],"id": sp[0]})
    json.dump(data, outfile)

rawDescription: Writing a tab delimited file as json object in python


rawDescription: python find elements using selenium.webdriver

description: Python find elements using selenium.webdriver


code:
execCd = """
if (abs(22.0) >= abs(-162.0)):
    retVal = 22.0
else:
    retVal = -162.0
"""

safe_list = ['math','acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'de grees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ])
safe_dict['abs'] = abs
exec(execCd,{"__builtins__":None},safe_dict)
retVal = safe_dict["retVal"]

rawDescription: How to safely use exec() in Python?

description: Safely use exec() in Python


code:
import itertools
for tup in itertools.product(range(0x100), repeat=3):
    ...

rawDescription: How to use itertools to output results of only a certain length

description: Use itertools to output results of only a certain length


code:
import unittest
unittest.TestLoader.sortTestMethodsUsing = lambda _, x, y: cmp(y, x)

rawDescription: changing order of unit tests in Python

description: Changing order of unit tests in Python


code:
parser = argparse.ArgumentParser(prog='frobble')
parser.add_argument('--foo', help=argparse.SUPPRESS)
parser.print_help()

rawDescription: Creating hidden arguments with Python argparse


rawDescription: How to save file in hadoop with python

description: Save file in hadoop with python


code:
import pygame
import time
import math
# Some config width height settings
canvas_width=1308
canvas_height=720
canvas_s=1004
# Just define some colors we can use
rojo=pygame.Color(255,0,0)
verde=pygame.Color(0,255,0)
azul=pygame.Color(0,0,255)
amarillo=pygame.Color(255,255,0,0)
marron=pygame.Color(85,65,0)
morado=pygame.Color(255,0,255)
naranja=pygame.Color(255,128,0)
lin=pygame.Color(255,255,255)
background_color=pygame.Color(0,0,0)

pygame.init()
#initialization of font module and creating a font to draw with
pygame.font.init()
fontdir = pygame.font.match_font('TimesNewRoman', False, False)
myfont = pygame.font.Font(fontdir,16)
# Set the window title
pygame.display.set_caption("Monitor Signos Vitales")
# Make a screen to see
screen=pygame.display.set_mode((canvas_width,canvas_height))
screen.fill(background_color)
# Make a surface to draw on
surface=pygame.Surface((canvas_width,canvas_s))
surface.fill(background_color)
#creating the random list and their corresponding surfaces
random_list = [random.randrange(0,1000) for x in range(5)]
text_list = [myfont.render(str(x),True,lin) for x in random_list]

# Simple main loop
running=True
while running:
    pos = (1220,0)
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False

    # Redraw the background and some guide lines
    surface.fill(background_color)

    #--------------------------#
    #-------FIX POSITION-------#
    #--------------------------#
    for text in text_list:
        surface.blit(text,pos)
        pos = (pos[0],pos[1]+180)
    pygame.draw.line(surface, lin, (0, 90), (1004, 90))
    pygame.draw.line(surface, lin, (0, 180), (1004, 180))
    pygame.draw.line(surface, lin, (0, 270), (1004, 270))
    pygame.draw.line(surface, lin, (0, 360), (1004, 360))
    pygame.draw.line(surface, lin, (0, 450), (1004, 450))
    pygame.draw.line(surface, lin, (0, 540), (1004, 540))
    pygame.draw.line(surface, lin, (0, 630), (1004, 630))
    pygame.draw.line(surface, lin, (1004, 0), (1308, 720))
    pygame.draw.line(surface, lin, (1004, 180), (1308, 180))
    pygame.draw.line(surface, lin, (1004, 360), (1308, 360))
    pygame.draw.line(surface, lin, (1004, 540), (1308, 540))

    # Update sine wave
    frecuency=2;frecuency0=4;frecuency1=8;frecuency2=16;frecuency3=5;frecuency4=10
    frecuency5=15
    amplitude=30 # in pixels
    speed=2
    for x0 in range(0,canvas_s):
        y0=int((canvas_height/2)+amplitude*math.sin(frecuency*((float(x0)/canvas_s)*    (2*math.pi)+(speed*time.time()))+270)-270)
        surface.set_at((x0,y0),amarillo)
    for x1 in range(0,canvas_s):
        y1=int((canvas_height/2)+amplitude*math.sin(frecuency0*((float(x1)/canvas_s)*(2*math.pi)+(speed*time.time()))+180)-180)
        surface.set_at((x1,y1),verde)
    for x2 in range(0,canvas_s):
        y2=int((canvas_height/2)+amplitude*math.sin(frecuency1*((float(x2)/canvas_s)*(2*math.pi)+(speed*time.time()))+90)-90)
        surface.set_at((x2,y2),naranja)
    for x3 in range(0,canvas_s):
        y3=int((canvas_height/2)+amplitude*math.sin(frecuency2*((float(x3)/canvas_s)*(2*math.pi)+(speed*time.time()))))
        surface.set_at((x3,y3),azul)
    for x4 in range(0,canvas_s):
        y4=int((canvas_height/2)+amplitude*math.sin(frecuency3*((float(x4)/canvas_s)*(2*math.pi)+(speed*time.time()))-90)+90)
        surface.set_at((x4,y4),rojo)
    for x5 in range(0,canvas_s):
        y5=int((canvas_height/2)+amplitude*math.sin(frecuency4*((float(x5)/canvas_s)*(2*math.pi)+(speed*time.time()))-180)+180)
        surface.set_at((x5,y5),marron)
    for x6 in range(0,canvas_s):
        y6=int((canvas_height/2)+amplitude*math.sin(frecuency5*((float(x6)/canvas_s)*(2*math.pi)+(speed*time.time()))-270)+270)
        surface.set_at((x6,y6),morado)

    # Put the surface we draw on, onto the screen
    screen.blit(surface,(0,0))
    # Show it.
    pygame.display.flip()

rawDescription: stop blinking numbers in pygame

description: Stop blinking numbers in pygame


code:
def delete(self, i):
    self.A[i] = self.A[-1] #put the bottom rightmost element in i
    del self.A[-1]         # <--- shrink the list
    self.min_heapify(i)

rawDescription: python - deleting element at index i from heap

description: Python - deleting element at index i from heap


code: os.environ["PATH"] += ";" + dllpath

rawDescription: kernel32 library via excel com in Python

description: Kernel32 library via excel com in Python


code: new = ["yes" if x else "no" for x in list]

rawDescription: Problems using Python logical operators with 0


code:
', '.join([str(x) for x in list])  # list comprehension
', '.join(str(x) for x in list)    # generator expression

rawDescription: Python string.join(list) on object array rather than string array


code:
def readSacredAttribute(holyInput):
    raw = [ x.strip() for x in holyInput.readline()[:-1].split(':') ]
    newRaw = []
    for i in range(len(raw) - 1):
        for x in [ x.strip() for x in raw[ i + 1 ].split(',') ]:
            newRaw.append(x)

    raw[ 1 : ] = newRaw

    parameters = {}
    if '(' in raw[0]:
        base = raw[0].index('(') + 1
        to = raw[0].index(')')
        splitted = [ x.strip() for x in raw[1].split(',') ]
        for i, x in enumerate([ x.strip() for x in raw[0][ base : to ].split(',') ]):
            parameters[x] = splitted[i]

    return (raw, parameters)

def splitThisStupidMess(holyInput):
    holyHeader = []
    for i in range(6):
        holyHeader.append([ float(x) for x in holyInput.readline().split()])

    sacredAttributes = { x[0][0] : (x[0][1], x[1]) for x in [  readSacredAttribute(holyInput) for i in range(9) ] }

    # Ignore the '\' lines
    for i in range(2):
        holyInput.readline()

    nominalTime = readSacreAttribute(holyInput)
    sacredAttributes[nominalTime[0][0]] = (nominalTime[0][1], nominalTime[1])

    divineNames = holyInput.readline().split()
    divineUnits = holyInput.readline().split()
    holyInput.readline()    # Avoid decoration...
    divineValues = [ float(x) for x in holyInput.readline().split() ]

    divineFooter = { divineNames[i] : (divineUnits[i], divineValues[i]) for i in len(divineNames) }

    return (holyHeader, sacredAttributes, divineFooter)

rawDescription: python How to split irreguarly delimited file?

description: Python How to split irreguarly delimited file


code:
with app.app_context():
    data = render_template(path, **context)

rawDescription: render jinja2 template without a Flask context

description: Render jinja2 template without a Flask context


code:
"Dataset","Parent","XVal","YVal"
DataSet1,None,1,1
DataSet1,None,2,4
...
DataSet2,None,1,21
DataSet2,None,2,23

rawDescription: Smart way to use .csv files to store multiple data series in Python?


rawDescription: Reorder Columns Based on a Dictionary

description: Reorder Columns Based on a Dictionary


code:
class MyButton(Button):
    def on_release(self):  # or on_press
        new_button = Button(text='hello')
        self.root.ids.grid_1.add_widget(new_button)

rawDescription: kivy add a button to a specific location when pressing another button

description: Kivy add a button to a specific location when pressing another button


code:
def output(*items, end="\n", file=sys.stdout):
    pass

rawDescription: Overriding the newline generation behaviour of Python's print statement


rawDescription: Python simultaneous assign only from some elements of a list


code:
first_syl = 'ib' # the characters to be added
word = 'dOg'     # the input word

vowels = "aeiou" # instead of a long list of possibilities, we'll use the
                 # <string>.lower() func. It returns the lowercase equivalent of a
                 # string object.
first_vowel_count = True # This will tell us if the iterator is at the first vowel
final_str = ""           # The output.

for ch in word:
    if ch.lower() not in vowels:     # If we're at a consonant,
        first_vowel_count = True     # the next vowel to appear must be the first in
                                     # the series.

    elif first_vowel_count:          # So the previous "if" statement was false. We're
                                     # at a vowel. This is also the first vowel in the
                                     # series. This means that before appending the vowel
                                     # to output,

        final_str += first_syl       # we need to first append the vowel-
                                     # predecessor string, or 'ib' in this case.
        first_vowel_count = False    # Additionally, any vowels following this one cannot
                                     # be the first in the series.

    final_str += ch                  # Finally, we'll append the input character to the
                                     # output.
print(final_str)                     # "dibOg"

rawDescription: How Do I Fix This String Issue in Python?


code:
from Tkinter import *
root = Tk()

scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)

listbox = Listbox(root)
listbox.pack()

for i in range(100):
   listbox.insert(END, i)

# attach listbox to scrollbar
listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)

mainloop()

rawDescription: Is there a tkinter equivalent for Perl/Tk's Scrolled pseudo-widget?


code:
pd.concat([pan1, pan2],axis=1)
pd.concat([pan1, pan2],axis=1).loc[:,:,'B']

rawDescription: Pandas: How to concatenate two Panels without duplicating Items axis (i.e. like columns in DataFrames)?


code:
def mynonrandom():
 return 0.1

q
[1, 2, 3, 4]
random.shuffle(q, mynonrandom)
q
[2, 3, 4, 1]
random.shuffle(q, mynonrandom)
q
[3, 4, 1, 2]

rawDescription: random.shuffle Randomness

description: Random.shuffle Randomness


code:
user = authenticate(username=user, password=pswd)
if user is not None:
    #This will actually log the user in to the web request
    login(request, user)

rawDescription: Django Authentication System Implementation


code:
from IPython.utils import coloransi
from IPython.core import prompts

termcolors = coloransi.TermColors() # the color table
# IPython's two color schemes:
dark = prompts.PColLinux.colors
light = prompts.PColLightBG.colors

# colors.in_normal affects input code
dark.in_normal = termcolors.Green
light.in_normal = termcolors.Blue
# colors.normal affects output
dark.normal = light.normal = termcolors.Red

rawDescription: How do I customize text color in IPython?

description: Customize text color in IPython


code:
def get_cookie_by_name(cj, name):
    return [cookie for cookie in cj if cookie.name == name][0]

cookie = get_cookie_by_name(cj, "PHPSESSID")

rawDescription: How to display specific cookie?

description: Display specific cookie


code:
import curses
scr = curses.initscr()
curses.halfdelay(5)           # How many tenths of a second are waited, from 1 to 255
curses.noecho()               # Wont print the input
while True:
    char = scr.getch()        # This blocks (waits) until the time has elapsed,
                              # or there is input to be handled
    scr.clear()               # Clears the screen
    if char != curses.ERR:    # This is true if the user pressed something
        scr.addstr(0, 0, chr(char))
    else:
        scr.addstr(0, 0, "Waiting")

rawDescription: Using curses, how do I update the screen or wait for a key?


code:
def mytodo(self):
    self.progress_textEdit.append(u"==== 20 % first step finish")
    self.main_app.processEvents()
    self.progress_textEdit.append(u"==== 40 % first step finish")
    self.main_app.processEvents()
    # etc...

rawDescription: how to make QtextEdit can update data realtime and no stuck UI

description: Make QtextEdit can update data realtime and no stuck UI


code:
def has_change_permission(self, request, obj=None):
    if obj is None and '_popup' in request.GET:
        return True

    return super(MyAdmin, self).has_change_permission(request, obj)

rawDescription: Django raw_id_fields read_only permission


code: role = models.ForeignKey(UserRole, on_delete=models.CASCADE, default=None, blank=True, db_column='roleid')

rawDescription: Django add an underscore in Foreign key field, is there a way to remove it?


code:
import hashlib
m = hashlib.md5()
m.update("some string")
str(int(m.hexdigest(), 16))[0:12]

rawDescription: Generate ID from string in Python

description: Generate ID from string in Python


code:
def _render(request, form):
    return render(request, 'projects/project_list.html',
                  {"form": form, 'projects': request.user.project_set.all()})

@login_required
def project_list(request):
    projects = request.user.project_set.all()
    form = ProjectForm()
    return _render(request, form)

@login_required
def new_project(request):
    form = ProjectForm()
    if request.method == 'POST':
        form = ProjectForm(data=request.POST)
        if form.is_valid():
            project = form.save(commit=False)  #must specify user before commit
            project.owner = request.user
            project.save()
            return redirect(project)

    return _render(request, form)

rawDescription: How do I use the same render in 2 separate view functions? (django)

description: Use the same render in 2 separate view functions? (django)


code:
import csv
def phoneNumber(number):
    ...
def userName(name):
    ...
def targetDate(datestring):
    ...
control = [phoneNumber, userName, userName, targetDate]
with open("csvFile", "r") as inFile:
    reader = csv.reader(inFile)
    for row in reader:
        for op, item in zip(control, row):
            op(item)

rawDescription: Design help: Configurable behavior based on input


code:
stokes_list = np.array([])
for i in range(numrows):
    epoch_name = y['filename'][i]
    os.system('pdv -t {0} > temp.txt '.format(epoch_name))
    stokes_line = np.genfromtxt('temp.txt', usecols=3, dtype=[('stokesI','float')], skip_header=1)
    stokes_list = vstack(stokes_list, stokes_line)

stokes_columns = np.transpose(stokes_list)

rawDescription: writing a list or array to file

description: Writing a list or array to file


code:
from tkinter import *
from time import sleep
root = Tk()
l = Label ( root , text = "bla" )
b = Button ( root , text = "python je glup" )

def glupsam ():
    b.grid_forget()
    b.update_idletasks()
    l.grid ( row = 0 , column = 0 )
    l.update_idletasks()
    def f():
        l.grid_forget()
        l.update_idletasks()
        b.grid(row = 0 , column = 0)
    root.after(2000, f)

b.grid( row = 0 , column = 0 )
b.configure ( command = glupsam )

root.mainloop()

rawDescription: tkinter python switching widgets

description: Tkinter python switching widgets


code:
import sys
from tkinter import *
from PIL import Image, ImageTk

# Create the Class. Everything goes in the class,
# and passing variables is very easy because self is passed around
class SWLoad():
    # __init__ runs when the class is called
    def __init__(self):
        # Create window
        SWH = Tk()
        SWH.geometry("1024x950+130+0")
        SWH.title("ServiceWhiz.")

        # Initialize a list for the images
        self.img_list = []

        # Load the first image
        load = Image.open("Logo.png")
        render = ImageTk.PhotoImage(load)
        # Add the label to the list of images.
        # To access this label you can use self.img_list[0]
        self.img_list.append(Label(SWH, image=render))
        self.img_list[0].image = render
        self.img_list[0].place(x=458,y=250)

        # Load the second image
        load = Image.open("PoweredByServiceWhiz.png")
        render = ImageTk.PhotoImage(load)
        # Add the label to the list of images.
        # To access this label you can use self.img_list[1]
        self.img_list.append(Label(SWH, image=render))
        self.img_list[1].image = render
        self.img_list[1].place(x=362,y=612.5)

        # Fire the command that removes the images after 3 seconds
        SWH.after(3000, self.removewidgets)
        # Initialize the main loop
        SWH.mainloop()

    # Here, the function that removes the images is made
    # Note that it only needs self, which is passed automatically
    def removewidgets(self):
        # For every widget in the self.img_list, destroy the widget
        for widget in self.img_list:
            widget.destroy()

# Run the app Class
SWLoad()

rawDescription: How to put a Tkinter app into a Class

description: Put a Tkinter app into a Class


code:
def palindrome(s):
    i = 0
    while i <= len(s) / 2:
        if s[i] != s[-i - 1]:
            return False
        i += 1
    return True

rawDescription: How to check for palindrome using while loop python

description: Check for palindrome using while loop python


code:
import sys
import os
import glob
import numpy
from PIL import Image

def tau_gamma_correct(pixel_channel):
    pixel_channel = pixel_channel**(1/2.2)
    return pixel_channel

#@param: rgb
#@result: returns grayscale value
def gleam(rgb):
    #convert rgb tuple to list
    rgblist = list(rgb)
    #gamma correct each rgb channel
    rgblist[0] = tau_gamma_correct(rgblist[0])
    print('gleamed red ' + str(rgblist[0]))
    rgblist[1] = tau_gamma_correct(rgblist[1])
    print('gleamed green ' + str(rgblist[1]))
    rgblist[2] = tau_gamma_correct(rgblist[2])
    print('gleamed blue ' + str(rgblist[0]))
    grayscale = (rgblist[0] + rgblist[1] + rgblist[2])/3
    print('grayscale '+ str(grayscale))
    return grayscale

# get a glob list of jpg filenames
files = glob.glob('*.jpg')
for file in files:
    file = open(file)
    filename = file.name
    image = Image.open(file)
    pix = image.load()
    width, height = image.size
    new_image = Image.new('L', image.size)
    #pixelmatrix = [width][height]
    pixelmatrix = numpy.zeros((width, height))
    #print(width,height)
    for x in range(0, width):
        for y in range(0, height):
            rgb = pix[x,y]
            print('current pixel value: '+str(rgb))
            # calc new pixel value and set to pixel
            #print(gleam(rgb))
            gray = gleam(rgb)
            print('changing to pixel value: '+str(gray))
            pixelmatrix[x,y] = gray
            new_image.save(filename + 'gray.gleam'+'.jpg')
    new_image.putdata(pixelmatrix)
    file.close()

rawDescription: Convert an images pixel value from rgb to grayscale manually python PIL?


code:
gr = df.groupby(['code', df['date'] > 201403])
pv = gr['count'].sum().unstack().fillna(0)
namer = {True:'last 6 months', False:'before that'}.get
pv.columns = list(map(namer, pv.columns))
pv

rawDescription: Intra-group calculations on Pandas dataframe


code:
theModule = __import__("the_module")
toImport = getattr(theModule, "ToImport")
toImport.initialize("parameter")

rawDescription: Dynamically import class by name for static access


rawDescription: How can the value of a SubFactory be set when creating a Factory object