code:
#!/usr/bin/env python

import gearman
import sys
import socket
import re
import json
from dns.resolver import Resolver, NXDOMAIN, NoNameservers, Timeout, NoAnswer
from threading import Thread

class Lookup(Thread):
    def __init__(self, host, dnslist, listed, resolver):
        Thread.__init__(self)
        self.host = host
        self.listed = listed
        self.dnslist = dnslist
        self.resolver = resolver

    def run(self):
        try:
            host_record = self.resolver.query(self.host, "A")
            if len(host_record) > 0:
                self.listed[self.dnslist]['LISTED'] = True
                self.listed[self.dnslist]['HOST'] = host_record[0].address
                text_record = self.resolver.query(self.host, "TXT")
                if len(text_record) > 0:
                    self.listed[self.dnslist]['TEXT'] = "\n".join(text_record[0].strings)
            self.listed[self.dnslist]['ERROR'] = False
        except NXDOMAIN:
            self.listed[self.dnslist]['ERROR'] = False
            self.listed[self.dnslist]['ERRORTYPE'] = NXDOMAIN
        except NoNameservers:
            self.listed[self.dnslist]['ERROR'] = True
            self.listed[self.dnslist]['ERRORTYPE'] = NoNameservers
            self.listed[self.dnslist]['TEXT'] = "%s - The operation timed out." % self.host
        except Timeout:
            self.listed[self.dnslist]['ERROR'] = True
            self.listed[self.dnslist]['ERRORTYPE'] = Timeout
            self.listed[self.dnslist]['TEXT'] = "%s - The operation timed out." % self.host
        except NameError:
            self.listed[self.dnslist]['ERROR'] = True
            self.listed[self.dnslist]['ERRORTYPE'] = NameError
            self.listed[self.dnslist]['TEXT'] = "%s - NameError" % self.host
        except NoAnswer:
            self.listed[self.dnslist]['ERROR'] = True
            self.listed[self.dnslist]['ERRORTYPE'] = NoAnswer
            self.listed[self.dnslist]['TEXT'] = "%s - The response did not contain an answer to the question." % self.host

class RBLSearch(object):
    def __init__(self, lookup_host, rbls):
        self.lookup_host = lookup_host
        self.rbls = rbls
        self._listed = None
        self.resolver = Resolver()
        self.resolver.timeout = 0.2
        self.resolver.lifetime = 1.0

    def search(self):
        if self._listed is not None:
            pass
        else:
            host = self.lookup_host.split(".")
            host = ".".join(list(reversed(host)))
            self._listed = {'SEARCH_HOST': self.lookup_host}
            threads = []
            for LIST in self.rbls:
                self._listed[LIST] = {'LISTED': False}
                query = Lookup("%s.%s" % (host, LIST), LIST, self._listed, self.resolver)
                threads.append(query)
                query.start()
            for thread in threads:
                thread.join()
        return self._listed
    listed = property(search)

    def print_results(self):
        listed = self.listed
        print("")
        print("--- DNSBL Report for %s ---" % listed['SEARCH_HOST'])
        for key in listed:
            if key == 'SEARCH_HOST':
                continue
            if not listed[key].get('ERROR'):
                if listed[key]['LISTED']:
                    print("Results for %s: %s" % (key, listed[key]['LISTED']))
                    print("  + Host information: %s" % \
                          (listed[key]['HOST']))
                if 'TEXT' in listed[key].keys():
                    print("    + Additional information: %s" % \
                          (listed[key]['TEXT']))
                else:
                    print("Not listed in %s" % (key))
            else:
                #print "*** Error contacting %s ***" % key
                pass

def task_listener_runcheck(gearman_worker, gearman_job):
    jdata = json.loads(gearman_job.data)
    host = jdata['ip']
    rbls = jdata['rbls']
    ip = host

    print("Looking up: %s (please wait)" % host)
    pat = re.compile("\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}")
    is_ip_address = pat.match(host)
    if not is_ip_address:
        try:
            ip = socket.gethostbyname(host)
            print("Hostname %s resolved to ip %s" % (host,ip))
        except socket.error:
            print("Hostname %s can't be resolved" % host)
            ip = ""
    if ip:
        searcher = RBLSearch(ip, rbls)
        searcher.print_results()
    return "RunCheck was successfull"

gm_worker = gearman.GearmanWorker(['localhost:4730'])

gm_worker.set_client_id('python-worker')
gm_worker.register_task('runcheck', task_listener_runcheck)
gm_worker.work()

rawDescription: Pass array into class in Python

description: Pass array into class in Python


code:
# -*- coding: utf-8 -*-

import matplotlib.pyplot as mp
import Tkinter as T, sys

class Application():

    def __init__(self, root):

        self.root = root

        self.x1 = []
        self.y2 = []

        self.z = 0

        self.root.title('GRAPH')
        self.root.geometry('600x600')
        self.root.config(bg="#3366ff")

        self.e = T.Entry(self.root, justify='center')

        self.l = T.Label(self.root, text='Podaj liczbę parametrów N =', bg='#3366ff')

        self.b1 = T.Button(self.root, text='OK', command=self.check)

        self.b2 = T.Button(self.root, text='Rysuj', command=self.graph)
        self.b = T.Button(self.root, text='Zakończ', command=self.end)

        self.l.pack()
        self.e.pack()
        self.b1.pack()

        self.b2.pack()
        self.b.pack()

    #------------------------------------------------------------

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

    #------------------------------------------------------------

    def end(self):
        sys.exit()

    #------------------------------------------------------------

    def check(self):
        try:
            self.entry_x = []
            self.entry_y = []

            self.z = int(self.e.get())

            self.e.config(bg='green')
            self.e.after(1000, lambda: self.e.config(bg='white'))

            self.l2 = T.Label(self.root, text='X', bg='yellow')
            self.l2.pack()

            for i in range(self.z):
                self.entry_x.append(T.Entry(self.root, justify='center'))
                self.entry_x[-1].pack()

            self.l3 = T.Label(self.root, text='Y', bg='#3366ff')
            self.l3.pack()

            for i in range(self.z):
                self.entry_y.append(T.Entry(self.root, justify='center'))
                self.entry_y[-1].pack()
        except:
            self.e.config(bg='red')
            self.e.after(1000, lambda: self.e.config(bg='white'))

    #------------------------------------------------------------

    def graph(self):

        self.x1 = []
        self.y1 = []

        for i in range(len(self.entry_x)):
            self.x1.append(float(self.entry_x[i].get()))

        for i in range(len(self.entry_y)):
            self.y1.append(float(self.entry_y[i].get()))

        mp.ion()
        mp.plot(self.x1, self.y1)
        mp.title('Wykres')
        mp.xlabel('x')
        mp.ylabel('y')
        mp.draw()

#====================================================================#

Application(T.Tk()).run()

rawDescription: Python Tkinter Graph

description: Python Tkinter Graph


code:
(moviesRDD
    .join(ratingsRDD) # Join by key
    .values() # Extract values
    .map(lambda x: (x[1][0], x[0], x[1][1]))) # Reshape

rawDescription: Spark two RDD join issue

description: Spark two RDD join issue


code:
class App:

    def __init__(self):
        master=Tk()
        self.master=master
        frame = Frame(master)
        frame.grid()
        Label(frame, text='Turn LED ON').grid(row=0, column=0)
        Label(frame, text='Turn LED OFF').grid(row=0, column=1)

        self.toggle=0
        self.newWindow=False
        self.button0 = Button(frame, text='LED 0 OFF', command=self.convert0)
        self.button0.grid(row=2, column=0)
        self.LED0 = Label(frame, text="Label")
        self.LED0.grid(row=2, column=1)

        self.buttonnewwindow = Button(frame, text='New Window',
                                     command=self.new_window)
        self.buttonnewwindow.grid(row=10, column=0)

        self.button8 = Button(frame, text='Exit', command=quit)
        self.button8.grid(row=11, column=0)

        master.mainloop()

    def convert0(self):
        self.toggle=not self.toggle
        if self.toggle:
            print('LED 0 ON')
            self.button0.config(text='LED 0 ON')
            ##self.LED0.config(image = logo)
            ##self.LED0.grid(row=2, column=2)
            ##pfio.digital_write(0,1) #turn on
        else:
            print('LED 0 OFF')
            self.button0.config(text='LED 0 OFF')
            ##self.LED0.config(image = logo2)
            ##self.LED0.grid(row=2, column=1)
            ##pfio.digital_write(0,0) #turn off

    def new_window(self):
        print('New Window')

        if not self.newWindow:
            self.newWindow = Toplevel(self.master)
            Button(self.newWindow, text="Close Window", command=self.newWindow.destroy).grid()
            ##self.app = App2(self.newWindow)
            ##self.newWindow.grab_set()   # I added this line to stop opening multiple new windows
            self.toggle=1
            self.convert0()
            self.newWindow=False
App()

rawDescription: Python - Tkinter correct way to setup an exit button on a child window and how it affects a toggle button


rawDescription: Python: how to compute min, max, median, 1st and 3rd quartiles from a dict of lists?


code:
import numpy as np
import pandas as pd

df = pd.DataFrame(dict(start=np.random.random_integers(0, 20, 10000)))

# the left-hand edges of each "interval"
intervals = np.linspace(0, 20, 9, endpoint=False)
print(intervals)
# [  0.           2.22222222   4.44444444   6.66666667   8.88888889
#   11.11111111  13.33333333  15.55555556  17.77777778]

df['start_idx'] = np.digitize(df['start'], intervals) - 1

print(df.head())
#    start  start_idx
# 0      8          3
# 1     16          7
# 2      0          0
# 3      7          3
# 4      0          0

rawDescription: generate "category-intervals" from categories

description: Generate "category-intervals" from categories


code:
ins = table.insert().values(a=None, b=2, c=func.now())
engine.execute(ins)

rawDescription: Using an SQL expression to insert data with SQLAlchemy (and MySQL)


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        widget = QtGui.QWidget(self)
        layout = QtGui.QVBoxLayout(widget)
        self.edit = QtGui.QLineEdit(self)
        self.list = QtGui.QListWidget(self)
        layout.addWidget(self.edit)
        layout.addWidget(self.list)
        self.setCentralWidget(widget)

    def eventFilter(self, source, event):
        if event.type() == QtCore.QEvent.MouseMove:
            if event.buttons() == QtCore.Qt.NoButton:
                pos = event.pos()
                self.edit.setText('x: %d, y: %d' % (pos.x(), pos.y()))
            else:
                pass # do other stuff
        return QtGui.QMainWindow.eventFilter(self, source, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    win = Window()
    win.show()
    app.installEventFilter(win)
    sys.exit(app.exec_())

rawDescription: PyQt4 MouseMove event without MousePress


code:
def add_localizer(event):
    request = event.request
    languages = ('en','us','es')
    deflang = 'pt'
    # CHECK current page
    if 'page' in request.matchdict:
        currentpage = DBSession.query(Pages).filter_by(url=request.matchdict['page']).first()
        #SET pages languages
        languages = currentpage.Languages.split(',')
        deflang = currentpage.defLang
    #-----  CHANGED   ----------------------
    dln = default_locale_negotiator(request)
    if not dln or dln not in languages:
        #set the default language
        request._LOCALE_ = deflang
    localizer = get_localizer(request)
    request.lang = localizer.locale_name
    def auto_translate(string):
        return localizer.translate(self.tsf(string))
    request.localizer = localizer
    request.translate = auto_translate

rawDescription: Pyramid, setting i18n by page

description: Pyramid, setting i18n by page


code:
subprocess.call(["ffmpeg", "-i", sys.argv[1], "-acodec", "alac",
                 sys.argv[1][:-5] + ".m4a"])

rawDescription: How to read argv value without escape the string?

description: Read argv value without escape the string


code: perms = product(range(1, 7), repeat=3)

rawDescription: Multiple range product in Python

description: Multiple range product in Python


code:
import json

def get_schema():
    with open('schema1.json', 'r') as f:
        return json.load(f)

rawDescription: How to include text within a python file

description: Include text within a python file


code:
import zipfile
zf = zipfile.ZipFile('Desktop.zip', 'r')
fnames = zf.namelist()
print(fnames)
for fname in fnames:
    data = zf.read(fname)
    print(fname, len(data))
    #... do other text processing here

zf.close()

rawDescription: Multiple text files analysis in a zip

description: Multiple text files analysis in a zip


code: str(guess)

rawDescription: Display Variable value in Python using print Statement?


code:
import warnings

def setup_warning_catcher():
    """ Wrap warnings.showwarning with code that records warnings. """

    caught_warnings = []
    original_showwarning = warnings.showwarning

    def custom_showwarning(*args,  **kwargs):
        caught_warnings.append(args[0])
        return original_showwarning(*args, **kwargs)

    warnings.showwarning = custom_showwarning
    return caught_warnings

caught_warnings_list = setup_warning_catcher()

# trigger warning here

assert len(caught_warnings_list) == 1

rawDescription: Count warnings in Python 2.4

description: Count warnings in Python 2.4


code: np.mean(arr.reshape(-1, 3), axis=1)

rawDescription: Averaging over every n elements of a numpy array


code:
root = Tk()

for row_number, row in enumerate(cursor):
    Label(root, text = "ID = " + str(row[0])).grid(column = 1, row = row_number)
    Label(root, text = "Forename = " + str(row[1])).grid(column = 2, row = row_number)
    print ("Surname = ", row[2]) # and so on. transform this too
    print ("DOB = ", row[3])

file.close()
root.mainloop()

rawDescription: How to make a tkinter GUI output screen following a database search

description: Make a tkinter GUI output screen following a database search


code:
class hi():
    def __init__(self):
        self.child=x()

    def __getattr__(self, attr):
        return getattr(self.child, attr)

rawDescription: When accessing Properties, send to another instance


code:
# input will prompt user for a bill amount at the command line
amount = float(input('Enter the amount of the bill: '))

tip_15 = amount * .15
tip_20 = amount * 0.2

print('A 15%% tip is: %.2f. A 15%% tip is: %.2f.' % (tip_15, tip_20))

print('Total price with 15%% tip is: %.2f' % (amount + tip_15))
print('Total price with 20%% tip is: %.2f' % (amount + tip_20))

rawDescription: How do i create a tipping program for python?

description: Create a tipping program for python


code:
my_list = ["ONE APPLE", "TWO PEAR", "THREE APPLE"]
result = [ ''.join(i.split()[0] + ' '+ i.rsplit()[1].replace('E', 'A')) for i in my_list ]
result
result = [ '{} {}'.format(i.split()[0], i.rsplit()[1].replace('E', 'A')) for i in my_list ]
result

rawDescription: How to use list.replace after a specific character in Python

description: Use list.replace after a specific character in Python


code:
import Tkinter
import turtle

def run_turtles(*args):
    for t, d in args:
        t.circle(250, d)
    root.after_idle(run_turtles, *args)

root = Tkinter.Tk()
root.withdraw()

frame = Tkinter.Frame(bg='black')
Tkinter.Label(frame, text=u'Hello', bg='grey', fg='white').pack(fill='x')
canvas = Tkinter.Canvas(frame, width=750, height=750)
canvas.pack()
frame.pack(fill='both', expand=True)

turtle1 = turtle.RawTurtle(canvas)
turtle2 = turtle.RawTurtle(canvas)

turtle1.ht(); turtle1.pu()
turtle1.left(90); turtle1.fd(250); turtle1.lt(90)
turtle1.st(); turtle1.pd()

turtle2.ht(); turtle2.pu()
turtle2.fd(250); turtle2.lt(90)
turtle2.st(); turtle2.pd()

root.deiconify()

run_turtles((turtle1, 3), (turtle2, 4))

root.mainloop()

rawDescription: How to Combine Tkinter windows?

description: Combine Tkinter windows


code:
from django.conf import settings
print(settings.SITE_ID)

rawDescription: how to get the variables from the configuration file?

description: Get the variables from the configuration file


code:
# Read your entire file into memory.
my_file = 'my_file.txt'
with open(my_file) as f_in:
    content = f_in.readlines()

# Keep track of the numbers that have already appeared
# while rewriting the content back to your file.
numbers = []
with open(my_file, 'w') as f_out:
    for line in content:
        number, country = line.split(',')
        if not number in numbers:
            f_out.write(line)
            numbers.append(number)

rawDescription: Python, In a file, that has comma separated values, how to check for duplicated values between lines and delete the duplicated lines?


rawDescription: pandas dataframe groupby datetime month

description: Pandas dataframe groupby datetime month


code:
from Queue import Queue
q = Queue()
_ = [q.put(index) for index in xrange(2, 10)]
if not q.empty():
   q.queue[-1]

rawDescription: How to find the most recently added item to a Queue in python?

description: Find the most recently added item to a Queue in python


code:
import urllib
urllib.urlretrieve('http://python.org/images/python-logo.gif', '/tmp/foo.gif')

rawDescription: How to Download a file to a specific path in the server : Python


code:
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
    cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

rawDescription: How can I automatically save and crop a produced image?

description: Automatically save and crop a produced image


code:
motifs = [ x.strip() for x in open('final motifs_11SGLOBULIN','r') ]
redact = '*****'

with open('11sglobulin.seqs','r') as data_in, open('11sglobulin.seqs.new','w') as data_out:
  for seq in data_in:
    for motif in motifs:
      while True:
        x = seq.find(motif)
        if x >= 0:
          seq = seq[:x] + redact + seq[x+len(motif):]
        else:
          break
  data_out.write(seq)

rawDescription: Finding/Replacing substrings with annotations in an ASCII file in Python


code: offline.replace("  ", " ")

rawDescription: get Total of dateTime

description: Get Total of dateTime


code:
with open('dictionary.txt', 'r') as f:
    dictionary_words = f.read().splitlines()

rawDescription: Is there a shorter way to remove line breaks when reading from a file to a list?


code:
import sys

print('Name of the script: {0}'.format(sys.argv[0]))

if len(sys.argv) == 3:
    inputfile_path = sys.argv[1]
    dictionary_path = sys.argv[2]
    print('First parameter: {0}'.format(inputfile_path))
    print('Second parameter: {0}'.format(dictionary_path))

rawDescription: How to make my python script accepts multiple positional arguments?

description: Make my python script accepts multiple positional arguments


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

def domain():
    x = np.arange(0, 10, 0.001)

    f1 = lambda x: (2*x - x**2)**0.5
    f2 = lambda x: 1 - (1-x*x)**0.5 # other part is f2 = lambda x: 1 + (1-x*x)**0.5
    plt.plot(x, f1(x), label = '$y = \sqrt{2x - x^2}$')
    plt.plot(f1(x), x, label = '$x = \sqrt{2y - y^2}$')
    plt.fill_between(x, f1(x), f2(x), where=f1(x)>=f2(x), interpolate=True, color='yellow')
    plt.xlabel('X')
    plt.ylabel('Y')
    plt.legend(loc='best')

    axes = plt.gca()
    axes.set_xlim([0, 5])
    axes.set_ylim([0, 5])
    plt.show()

domain()

rawDescription: Fill area between two functions

description: Fill area between two functions


code:
a
''.join(i for i, j in zip(a, '\0' + a) if i != j)

rawDescription: Remove duplicates but retain sequence

description: Remove duplicates but retain sequence


rawDescription: IronPython: adding references from host application


rawDescription: Django URL regular expression: make URL tolerate int or float values


code:
import requests
import eventlet
eventlet.monkey_patch()

with eventlet.Timeout(10):
    requests.get("http://ipv4.download.thinkbroadband.com/1GB.zip", verify=False)

rawDescription: Timeout for python requests.get entire response


code:
from filelock import FileLock

with FileLock("myfile.txt"):
    # work with the file as it is now locked
    print("Lock acquired.")

rawDescription: Locking a file in Python

description: Locking a file in Python


rawDescription: How to limt the digit size into single in python regex

description: Limt the digit size into single in python regex


code:
def getKey (x):
  keys = x.split()[0:6]
  keys[4] = float(keys[4])
  return tuple(keys)
rows_of_fileB = dict( [ getKey(r), r] for r in fileB)
for row in fileA:
  print( rows_of_fileB[getKey(row)] )

rawDescription: Python - How to sort the rows in a file to match another file sort order


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

x = np.linspace(0,1.6,50) + 50.0

fig, ax = plt.subplots()
ax2 = ax.twinx()

XLIM = [50.0, 51.6]
YLIM = [0.0, 1.1, 0.0, 11.0]

ax.plot(x,np.sin(x-50.0),'b')
ax2.plot(x,np.cos(x-50.0)*10.,'r')

ax.set(adjustable='box-forced',
       xlim=XLIM, ylim=YLIM[:2],
       xticks=np.arange(XLIM[0], XLIM[1], 0.2),
       yticks=np.arange(YLIM[0], YLIM[1]+0.1, 0.1)[:-1],
       aspect=(XLIM[1]-XLIM[0])/(YLIM[1]-YLIM[0]))

ax2.set(adjustable='box-forced',
        ylim=YLIM[2:],
        yticks=np.arange(YLIM[2], YLIM[3]+1.0, 1.0),
        aspect=(XLIM[1]-XLIM[0])/(YLIM[3]-YLIM[2]))

ax.grid(True, which='major',linestyle='solid')

plt.show()

rawDescription: Define aspect ratio when using twinx

description: Define aspect ratio when using twinx


code:
from PIL import Image
import numpy as np

im = Image.open("dummytext.png")
pix = np.asarray(im)
pix = pix[:,:,0:3] # Drop the alpha channel
pix = 255 - pix  # Invert the image
H =  pix.sum(axis=2).sum(axis=1) # Sum the colors, then the y-axis

rawDescription: Using python and PIL how can I grab a block of text in an image?


code:
"Hello World!"
'\'Hello World!\', he said'
"\"Hello World!\", he said"
'"Hello World!", doesn\'t cut it anymore'

rawDescription: Why the output is different?

description: Why the output is different


code:
from operator import attrgetter
import numpy as np
# code to build obj_array
...
bar_array_easy_way = np.frompyfunc(attrgetter("bar"), 1, 1)(obj_array)

rawDescription: New numpy array from attribute of objects in another numpy array


code:
from tkinter import *

bttn_clicks = 0
def on_button_click():
    global bttn_clicks
    bttn_clicks += 1
    bttn["text"] = "Total Clicks: " + str(bttn_clicks)

root = Tk()
root.title("Button Counter without OOP")
root.geometry("200x85")
app = Frame(root)
app.grid()
bttn = Button(app, command=on_button_click)  # <---------
bttn["text"] = "Total Clicks: 0"
bttn.grid()
root.mainloop()

rawDescription: Working with a GUI without using OOP

description: Working with a GUI without using OOP


code:
from PySide import QtGui, QtCore
app = QtGui.QApplication([])
d = QtGui.QDialog(None, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint)
d.exec_()

rawDescription: Remove what'sThis from a dialog in pyside


code:
class Foo(ArgumentParser): pass

parser = ArgumentParser()
parser._parser_class = Foo
subparser = parser.add_parser(...)

rawDescription: How to specify an ArgumentParser subclass as an argparse subparser?

description: Specify an ArgumentParser subclass as an argparse subparser


code:
from django.shortcuts import render_to_response
from django.template.context_processors import csrf

def my_view(request):
    csrf = unicode(csrf(request)['csrf_token'])

rawDescription: How to get the csrf_token in python(Django)

description: Get the csrf_token in python(Django)


code:
text = "GoTo: 7018 6453 12654\n"
[token for token in text.split() if token.isdigit()]

rawDescription: Split string and just get number in python?


code:
def zero_value(x):
    if x is None:
        return None
    return type(x)()

rawDescription: Getting the "zero value" corresponding to a given value


code:
import wmi
c = wmi.WMI()
for service in c.Win32_Service():
    print(service.DisplayName)

rawDescription: How to view all windows services (including those disabled or not running) in python

description: View all windows services (including those disabled or not running) in python


code:
from functools import partial

action = {'action': partial(move, 2, 3), 'other_stuff': 'stuff'}

rawDescription: Assigning a function (which is assigned dynamically) along with specific parameters, to a variable.


code:
matrix = [[5, -6, 2], [7, 2, 3], [8, 4, -9]]

hasNegativeElement = False

for i in range(len(matrix)):
    for j in range(len(matrix[i])):
        if matrix[i][j] < 0:
            hasNegativeElement = True
            break

if hasNegativeElement:
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            matrix[i][j] *= (-1)

rawDescription: Change the signs of the elements in a matrix if all rows contain at least one negative element


code:
sess = requests.Session()
req = sess.get('https://proximitybeacon.googleapis.com/v1beta1/beacons', headers={'Authorization': 'Bearer '+credentials.access_token})

rawDescription: Display list of all registered beacons

description: Display list of all registered beacons


code:
puerta_abierta = 0
while 1:
    if (GPIO.input(11) != GPIO.HIGH ):
        puerta_abierta += 1
        if(puerta_abierta == 1 ):
            call(["mpg123", "file.mp3"])
    else:
        puerta_abierta = 0

rawDescription: Execute command only once inside of infinite loop


rawDescription: Group DataFrame by Business Day of Month


code:
def front_back(a, b):
    ad = (len(a) + 1) // 2
    bd = (len(b) + 1) // 2
    return a[:ad] + b[:bd] + a[ad:] + b[bd:]

rawDescription: Help me simplify this code (Python)

description: Help me simplify this code (Python)


code:
fives = 0
twos = 0
for i in range(10, 201):
   while i % 5 == 0:
      fives = fives + 1
      i /= 5
   while i % 2 == 0:
      twos = twos + 1
      i /= 2
print(min(fives, twos))

rawDescription: Simplify this python code

description: Simplify this python code


code:
d = {}
with open('file.txt') as f:
  for line in f.readlines():
    k, v = line.strip().split(":")
    if (k not in d) or d[k] < int(v):
      d[k] = int(v)

rawDescription: Alphabetically sorting keys with their matching values


code:
setup(...,
          data_files=[...,
                      ('/etc/xdg/app/', ['config/config.yaml'])]
     )

rawDescription: How to make pip write a default config file when installing a python package?

description: Make pip write a default config file when installing a python package


code:
import re
a = "test string with %(experiment1)s and %(experiment2)s"
re.findall(r'%\((.*?)\)', a)

rawDescription: Extracting a template substitution object from the string


code:
from tkinter import *
root = Tk()

class StopWatch(Frame):
    def __init__(self, parent=None, **kw):
        Frame.__init__(self, parent, kw)
        self.on = 1
        TimeAdjustLabel = LabelFrame(root, text='Frame',)
        TimeAdjustLabel.grid(column=0, row=1, padx=10, pady=10)
        self.b1 = Button(TimeAdjustLabel, text='Reset', width=10, command=lambda:self.Start(self.on))
        self.b1.grid(row=0, column=0)

    def Start(self, onoff):
        if onoff == 0:
            onoff = 1
        else:
            onoff = 0
        self.enable(onoff)

    def enable(self,enableonoff):
        if enableonoff == 0:
            self.b1.configure(state='disabled')
        else:
            self.b1.configure(state='normal')

def main():
    app = StopWatch(root)
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Python 3 Tkinter - Disabling buttons out of order code


rawDescription: Why nested functions can access variables from outer functions, but are not allowed to modify them


code:
import lxml.etree
tree = lxml.etree.fromstring(xmlasstring)
tree.xpath('//node')

rawDescription: How I modify the following Python script to ignore tags and attributes within tags?


code:
from xml.etree import ElementTree

tree = ElementTree.parse(somefile)

for network in tree.findall('.//network_object'):
    for name in network.findall('.//Name'):
        if name.text is not None and 'cluster' in name.text:
            continue  # skip this one

rawDescription: Python XML parsing - equivalent of "grep -v" in bash


code: MyDiccoSorted = sorted(MyDicco.items(), key=lambda s: s[1][2])

rawDescription: Sort a complex Python dictionary by just one of its values


rawDescription: eval backward print __dict__ SyntaxError: invalid syntax

description: Eval backward print __dict__ SyntaxError: invalid syntax


code:
import math
def function_name(lst, background):
    ab, cb, gb, tb = background[0], background[1], background[2], background[3]
    a, c, g, t = lst[0][:], lst[1][:], lst[2][:], lst[3][:]
    pos = 0
    IC = 0
    for pos in range(len(a)):
        loga = math.log(((a[pos])/ab), 2)
        logc = math.log(((c[pos])/cb), 2)
        logg = math.log(((g[pos])/gb), 2)
        logt = math.log(((t[pos])/tb), 2)
        ICi = (a[pos]*loga + c[pos]*logc + g[pos]*logg + t[pos]*logt)
        IC += ICi
    return IC

rawDescription: python log2 over index of list of lists

description: Python log2 over index of list of lists


code:
def parse(self, response):
    # Get the list of URLs, for example:
    list = ["http://a.com", "http://b.com", "http://c.com"]

    for link in list:
        request = scrapy.Request(link)
        yield request

rawDescription: Scrapy - Scrape multiple URLs using results from the first URL


code:
def justified(title, amount, titlewidth=20, amountwidth=10):
    return title.ljust(titlewidth) + " = $ " + ('%.2f' % amount).rjust(amountwidth)

print(justified('Parts', 12.45))
print(justified('Labor', 100))
print(justified('Tax', 2.5))
print(justified('Total', 114.95))

rawDescription: Aligning Separate Parts of Print

description: Aligning Separate Parts of Print


rawDescription: How to reverse order of keys in python dict?

description: Reverse order of keys in python dict


code:
import os
import stat

BUF_SIZE = 4096
size = os.stat("large_file")[stat.ST_SIZE]
chunk_size = size // N
# or simply set a fixed chunk size based on your free disk space
c = 0

in_ = open("large_file", "r+")

while size > 0:
    in_.seek(-min(size, chunk_size), 2)
    # now you have to find a safe place to split the file at somehow
    # just read forward until you found one
    ...
    old_pos = in_.tell()
    with open("small_chunk%2d" % (c, ), "w") as out:
        b = in_.read(BUF_SIZE)
        while len(b) > 0:
            out.write(b)
            b = in_.read(BUF_SIZE)
    in_.truncate(old_pos)
    size = old_pos
    c += 1

rawDescription: Change python file in place

description: Change python file in place


code:
import pygame

pygame.init()
screen = pygame.display.set_mode((800,600))

while True:
    for event in pygame.event.get():
        print(event)
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                if upRun or tRun == 1: #Cancel any scrollers
                    upRun = 0
                    tRun = 0
                n()
            elif event.button == 2:
                up()
            else:
                art()

rawDescription: Pygame does not detect Mouse presses

description: Pygame does not detect Mouse presses


code:
class MyModelAdmin(admin.ModelAdmin):
    def get_urls(self):
        urls = super(MyModelAdmin, self).get_urls()
        my_urls = patterns('',
            (r'^my_view/$', self.my_view)
        )
        return my_urls + urls

    def my_view(self, request):
        # custom view which should return an HttpResponse
        pass

rawDescription: Create Django Admin Intermediate page

description: Create Django Admin Intermediate page


code:
def get(*keys):
    ret = mydict
    for key in keys:
        ret = ret[key]
    return ret

rawDescription: Variable number of keys to access dictionary through a function in Python


code:
s = struct.Struct('= B B H H 6h 6h 6h 6H')
fields = s.unpack(packet_data)
seq, _type, flags, upTimestamp = fields[:4]
x = fields[4:10]
y = fields[10:16]
z = fields[16:22]
lowTimestamp = fields[22:]

rawDescription: Unpacking nested C structs in Python

description: Unpacking nested C structs in Python


code:
'{:<30}'.format('left aligned')
'{:>30}'.format('right aligned')
'{:^30}'.format('centered')
'{:*^30}'.format('centered')  # use '*' as a fill char

rawDescription: Python - How can I pad a string with spaces from the right and left?


code: listOfObjects = sorted(listOfObjects, key=lambda item: item.number1)

rawDescription: Sort a list of python objects based on a local vairable


rawDescription: How to efficiently get matrix of the desired form in Python?

description: Efficiently get matrix of the desired form in Python


code:
class Translation(db.Model):
    origin = db.ReferenceProperty(Expression, required=True, collection_name='translation_origins')
    target = db.ReferenceProperty(Expression, required=True, collection_name='translation_targets')

rawDescription: How to reference the same Model twice from another one?

description: Reference the same Model twice from another one


code:
dt = clock.tick(60)
player.position.x += player.xSpeed * dt
player.position.y += player.ySpeed * dt

rawDescription: Setting a fixed FPS in Pygame, Python 3

description: Setting a fixed FPS in Pygame, Python 3


code:
import socket
s = socket.socket()
help(s.connect)
s.connect('127.0.0.1', 80)
s.connect(('127.0.0.1', 80))  # works

rawDescription: Cannot iterate list of strings into connect function with socket


code:
import urllib2
urllib2.quote('한글')

rawDescription: How to convert text into URL syntax on Python?

description: Convert text into URL syntax on Python


code:
import numpy
masses = numpy.array([[0,  0,  0,  0],
[0,  1,  0,  0],
[0,  2,  0,  0],
[1,  0,  0,  0],
[1,  1,  0,  1],
[1,  2,  0,  1],
[2,  0,  0,  0],
[2,  1,  0,  0],
[2,  2,  0,  0]])

nonZeroMasses = masses[numpy.nonzero(masses[:,3])] # Not really necessary, can just use masses because 0 mass used as weight will work just fine.

CM = numpy.average(nonZeroMasses[:,:3], axis=0, weights=nonZeroMasses[:,3])

rawDescription: python: calculate center of mass

description: Python: calculate center of mass


code:
# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore

class ColorDisplay(QtGui.QWidget):
    def __init__(self, parent):
        super(ColorDisplay, self).__init__(parent)

        self.color = None

    def setColor(self, color):
        self.color = QtGui.QColor(color)
        self.update()

    def paintEvent(self, event=None):
        painter = QtGui.QPainter(self)
        if self.color is not None:
            painter.setBrush(QtGui.QBrush(self.color))
            painter.drawRect(self.rect())

    def getColorName(self):
        return unicode(self.color.name())

rawDescription: How simply display a QColor using PyQt?

description: How simply display a QColor using PyQt


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

fig  = plt.figure()

grid_top = ImageGrid(fig, 211, nrows_ncols = (2, 1),
                     cbar_location = "right",
                     cbar_mode="single",
                     cbar_pad=.2,
                     aspect=False)
grid_bot = ImageGrid(fig, 212, nrows_ncols = (1, 1),
                     cbar_location = "right",
                     cbar_mode="single",
                     cbar_pad=.2,
                     aspect=False)

# Some random data so the script will run
array1=np.random.rand(10,250)
array2=np.random.rand(10,250)
array3=np.random.rand(10,250)

im1 = grid_top[0].pcolormesh(np.arange(0,len(array1[0])),np.arange(0,len(array1)+1),array1, vmin=0, vmax=0.8)
im2 = grid_top[1].pcolormesh(np.arange(0,len(array2[0])),np.arange(0,len(array2)+1),array2, vmin=0, vmax=0.8)
im3 = grid_bot[0].pcolormesh(np.arange(0,len(array3[0])),np.arange(0,len(array3)+1),array3, vmin=-0.5, vmax=0.5, cmap='seismic')

grid_top.cbar_axes[0].colorbar(im1)
grid_bot.cbar_axes[0].colorbar(im3)

plt.show()

rawDescription: Crushed subplots not occupying the whole plot


code:
def count_messages(folder):
    messages = folder.item.count
    for sub_folder in folder.folders:
        messages += count_messages(sub_folder)
    return messages

total_messages = count_messages(root)

rawDescription: Python iteration over unknown folders

description: Python iteration over unknown folders


code:
f = 'filename'
for path, dirs, files in os.walk('.'):
    if f in files:
        os.chdir(path)
        break

rawDescription: python find file and change directory to file path

description: Python find file and change directory to file path


code:
from twisted.internet.protocol import ServerFactory

class LocalOnlyFactory(ServerFactory):
    def buildProtocol(self, addr):
        if addr.host == "127.0.0.1":
            return ServerFactory.buildProtocol(self, addr)
        return None

rawDescription: Python Twisted: restricting access by IP address


code:
import numpy as np
from bokeh.plotting import figure, show, output_file
from bokeh.models import CustomJS, ColumnDataSource, Slider
from bokeh.io import vform

N = 100

x = np.linspace(0, 10, N)
y = np.linspace(0, 10, N)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx)*np.cos(yy)

output_file("image.html", title="image.py example")

source = ColumnDataSource(data={'d': [d], 'xx': [x], 'yy': [y]})

p = figure(x_range=[0, 10], y_range=[0, 10])
p.image(image="d", x=[0], y=[0], dw=[10], dh=[10], palette="Spectral11",source=source)

callback = CustomJS(args=dict(source=source), code="""
        var xx = source.get('data')['xx'][0];
        var yy = source.get('data')['yy'][0];
        var d = source.get('data')['d'][0];
        var f = slider.get('value');
        for (var i = 0; i < xx.length; i++) {
            for (var j = 0; j < yy.length; j++){
                d[i][j] = Math.sin(f * xx[i]) * Math.cos(yy[j]);
            }
        }
        source.trigger('change');
    """)

slider = Slider(start=0.1, end=4, value=1, step=.1, title="angular frequency", callback=callback)
callback.args['slider'] = slider
layout = vform(slider, p)
show(layout)

rawDescription: Bokeh: implementing custom javascript in an image plot


code:
ball1 = ball[:]

for i,lst in enumerate(ball):
    for j,item in enumerate(lst):
        ball1[i][j] = (ball[i][j][0]+offsets[0][0], ball[i][j][1]+offsets[0][1])

rawDescription: Offsetting tuples in a nested list

description: Offsetting tuples in a nested list


code:
def do_something():
    f= open('input.txt', 'r')
    lines=f.readlines()
    s = []
    for line in lines:
        line= line.replace("x","y")
        s.append(line)
    return s

def do_anotherthing(buffers):
    f1= open('output2.txt', 'w')
    lines=buffers
    for line in lines:
        line=line.replace ("z", "a")
        f1.write(line)

if __name__ == '__main__':
    do_anotherthing(do_something())

rawDescription: python how to combine scripts without writing multiple files

description: Python how to combine scripts without writing multiple files


code:
A = np.arange(1,10).reshape(3,3)
B = np.ones((3,3,2))
C = A[..., None] * B
C
C.shape

rawDescription: Efficient element by element multiplication of 3D matrix elements with copies of a 2D matrix?


code:
def __init__(self, parent):
    wx.Panel.__init__(self, parent)

    self.figure = Figure()
    canvas = FigureCanvas(self, -1, self.figure)
    canvas.mpl_connect('button_release_event', self.mouse_up_handler)

    # make axes
    self.ax = self.figure.add_subplot(1, 1, 1)
    # set up details
    self.ax.set_yscale('log')
    self.ax.autoscale(enable=True)
    self.ax.set_xlim(x_values[0], x_values[-1])
    # make the line
    self.ln, = self.ax.plot([], []) # add what ever parameters you want

    sizer = wx.BoxSizer(wx.VERTICAL)
    sizer.Add(canvas, 1, wx.GROW)
    self.SetSizer(sizer)

    self.generate_new_data()

def generate_new_data(self):
    x_values = range(16384)
    y_values = [exp(normalvariate(0, 10)) for _ in range(16384)]

    sleep(0.4)  # simulate some additional work being done with the data

    # update your existing line
    self.ln.set_data(x_values, y_values, antialiased=False)

    self.figure.canvas.draw()

    Timer(1.0, self.generate_new_data).start()

rawDescription: How can I update a matplotlib figure in a way that prevents xdata from being None?

description: Update a matplotlib figure in a way that prevents xdata from being None


code:
def base64_encode(match):
    """
    This function takes a re 'match object' and performs
    The appropriate substitutions
    """

    group = match.group(1)
    ... #Code to encode as base 64
    return result

re.sub(...,base64_encode,s,flags=re.I)

rawDescription: Calling a function on captured group in re.sub()


rawDescription: Add specific list elements in list of lists


code:
df['Date'] = pd.PeriodIndex(df['Date'], freq='Q')
df2 = df.copy()
df2['Date'] += 1
df.merge(df2, on=['Date','ID'], suffixes=('', '_lag1'), how='left')

rawDescription: Pandas dataframe shift column by date

description: Pandas dataframe shift column by date


rawDescription: Pandas DataFrame - select rows that match one of many conditions


rawDescription: Tuning of a Web handler regex routes configuration


rawDescription: Python Floating Point Formatting

description: Python Floating Point Formatting


code:
from module import function

def foo(x):
    return function(x)

rawDescription: Python: Why is global needed only on assignment and not on reads?


code:
import requests

def my_django_view(request):
    if request.method == 'POST':
        r = requests.post('https://www.somedomain.com/some/url/save', params=request.POST)
    else:
        r = requests.get('https://www.somedomain.com/some/url/save', params=request.GET)
    if r.status_code == 200:
        return HttpResponse('Yay, it worked')
    return HttpResponse('Could not save data')

rawDescription: Calling a restApi from django view

description: Calling a restApi from django view


code:
url(r'service/(?P<function>\w+)/$', 'core.service.function_router')

def function_router(request, function):
    return globals()[function](request)

rawDescription: Django url routing - include url part for dispatching


code:
import matplotlib
from pylab import *
import numpy as np
import matplotlib.pyplot as plt

image_iter = ('images/image_%03d.txt' % i for i in xrange(1, 11))
image_sum = np.loadtxt(next(image_iter))

for image in image_iter:
   image_sum += np.loadtxt(image)

plt.imshow(image_sum, cmap=cm.Greys_r, interpolation='none')
plt.show()

rawDescription: Sum a stack of images

description: Sum a stack of images


code:
import urllib2
import re
url = "https://rrtp.comed.com/rrtp/ServletFeed?type=instant"
s = urllib2.urlopen(url).read()
float(re.findall("\d+.\d+", s)[0])

rawDescription: Getting text from HTML using BeautifulSoup


code:
# Over-explaining a bit:
def magic(numList):         # [1,2,3]
    s = map(str, numList)   # ['1','2','3']
    s = ''.join(s)          # '123'
    s = int(s)              # 123
    return s

# How I'd probably write it:
def magic(numList):
    s = ''.join(map(str, numList))
    return int(s)

# As a one-liner
num = int(''.join(map(str,numList)))

# Functionally:
s = reduce(lambda x,y: x+str(y), numList, '')
num = int(s)

# Using some oft-forgotten built-ins:
s = filter(str.isdigit, repr(numList))
num = int(s)

rawDescription: Python: Convert list of ints to one number?


code:
list = []
line = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
list.append(line)

rawDescription: how to create a list of lists

description: Create a list of lists


code:
bin_width = int(round(duration / bins))
followers = [sum(followersList[i:i+bin_width]) for i in xrange(0, duration, bin_width)]

rawDescription: How to bin the sum of list values in Python?

description: Bin the sum of list values in Python


code:
class Foo(object):
    def __init__(self, x):
        self.x = x

class Bar(Foo):
    def __init__(self, x):
        super(Bar, self).__init__(x)
        self.initial_status = False

rawDescription: What is the use of super(ClassName,self)._init_()


code:
import pickle

try:
    foo = pickle.load(open("var.pickle", "rb"))
except (OSError, IOError) as e:
    foo = 3
    pickle.dump(foo, open("var.pickle", "wb"))

rawDescription: Pickle - Load variable if exists or create and save it


code:
q = s.query(User)  # lazy loads 'addresses'
q = s.query(User).options(contains_eager('addresses'))  # eager loads
q = s.query(User).options(contains_eager('addresses'))\
        .options(lazyload('addresses'))  # lazy loads
q = s.query(User).options(contains_eager('addresses'))\
        .options(lazyload('addresses'))\
        .options(contains_eager('addresses'))  # eager loads

rawDescription: Undo `lazyload()` with the relationship default


code:
import turtle

def window(ttl,colr):
    wn=turtle.Screen()
    wn.title(ttl)
    wn.bgcolor(colr)
    return wn

def turtles(siz,col,shp):
    tl=turtle.Turtle()
    tl.pensize(siz)
    tl.color(col)
    tl.shape(shp)
    return tl

def square(sz):
    for i in range(4):
        trtl.fd(sz)
        trtl.rt(90)
    trtl.pu()
    trtl.rt(180)         #Turns around
    for x in range(2):   #Repeat twice
        trtl.fd(10)      #Moves half the size of 20 forward (away from the square)
        trtl.rt(90)      #Turns right
    trtl.pd()

def draw_circle():
    z=120                #You can change this to make the circle more choppy/finer and larger/smaller
    for x in range(z):
        trtl.fd(5)       #You can change this to make the circle larger/smaller
        trtl.rt(360/z)

dg=window('Concentric Square','lightgreen')
trtl=turtles('3','blue','turtle')
trtl.speed(0)
size=20
for i in range(5):
    square(size)
    size=size+20

trtl.pu()
trtl.fd(300)
trtl.pd()
draw_circle()

dg.listen()
dg.mainloop()

rawDescription: Figures with python's turtle

description: Figures with python's turtle


code:
def placemarks(n):
    return ','.join(['%s']*n)

sql = """SELECT CAST ((SUM(r.SalesVolume)/1000.0) AS decimal(6,1))
         FROM RawData r
         INNER JOIN Product p
         ON r.ProductId = p.ProductId
         INNER JOIN Calendar c
         ON r.DayId = c.DayId
         WHERE c.WeekCodeInYear BETWEEN 30 AND 50
         AND p.VODEST IN ({})
         AND p.Distributor IN ({})
         GROUP BY c.WeekCodeInYear
         ORDER BY c.WeekCodeInYear""".format(
             placemarks(len(_vodest)),
             placemarks(len(_studios)))
args = [_vodest + _studios]
res_vod = db.execute(sql, args)

rawDescription: Python: Use JSON list as parameters in SQL


code: state

rawDescription: GAE redirect the user to oauth2 without loosing the information from the initial request?


code:
from collections import defaultdict
d = defaultdict(int)
for i,j in enumerate(L):
    d[j]+=i

d

rawDescription: Create dictionary where keys are from a list and values are the sum of corresponding elements in another list


code:
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=3, ncols=4)

# Set the ticks and ticklabels for all axes
plt.setp(axes, xticks=[0.1, 0.5, 0.9], xticklabels=['a', 'b', 'c'],
        yticks=[1, 2, 3])

# Use the pyplot interface to change just one subplot...
plt.sca(axes[1, 1])
plt.xticks(range(3), ['A', 'Big', 'Cat'], color='red')

fig.tight_layout()
plt.show()

rawDescription: Python xticks in subplots

description: Python xticks in subplots


code:
import os
path = r'C:\Users\me\Desktop\output'
for counter in xrange(100):
    with open(os.path.join(path,'{:02x}.txt'.format(counter)),'wb') as f:
        f.write(chr(counter))

rawDescription: Write a "string" as raw binary into a file Python


code:
def read_matrix(count):
    list_of_lists = [list(map(int, input('Enter a row: ').split())) for _ in range(count)]

    return list_of_lists

x = input("enter the list of lists of numbers?")
print(read_matrix(int(x)))

rawDescription: How to read matrix from stdin(console)?

description: Read matrix from stdin(console)


code:
class ServerThread(threading.Thread):

    def __init__(self, port):
        threading.Thread.__init__(self)

    def run(self):
        srv = make_server(...)
        srv.serve_forever()

if '__main__'==__name__:
    ServerThread().start()
    webbrowser.open_new_tab(...)

rawDescription: Start simple web server and launch browser simultaneously in Python


code:
def __new__(cls, value):
    return type("A", (type(value), A), {})(value)

rawDescription: Instance that returns value (not instance) when called directly


code:
import subprocess
import re

POWER_MGMT_RE = re.compile(r'IOPowerManagement.*{(.*)}')

def display_status():
    output = subprocess.check_output(
        'ioreg -w 0 -c IODisplayWrangler -r IODisplayWrangler'.split())
    status = POWER_MGMT_RE.search(output).group(1)
    return dict((k[1:-1], v) for (k, v) in (x.split('=') for x in
                                            status.split(',')))

rawDescription: How to check whether screen is off in Mac/Python?

description: Check whether screen is off in Mac/Python


code:
if elem1.tag == 'Components':
    temp = 0
    for elem2 in list(elem1):
        if elem2.tag == 'Component':
            for elem3 in list(elem2):
                if elem3.tag == 'ComponentID':
                    asset['CompID'+str(temp)] = elem3.text
                if elem3.tag == 'ComponentName':
                    asset['CompName'+str(temp)] = elem3.text
                if elem3.tag == 'Description':
                    asset['Description'+str(temp)] = elem3.text
            temp+=1

rawDescription: How to grab text from each xml tag when the tags have multiple duplications

description: Grab text from each xml tag when the tags have multiple duplications


code:
with open("myFile.json") as f:
    objects = json.load(f)

rawDescription: How do I read a list of JSON files from file in python?

description: Read a list of JSON files from file in python


code:
db.collection.find({_id: 1234}, {
    'parentfield1.childfield1': 1,
    'parentfield1.childfield2': 1,
    'parentfield1.childfield3': 1
});

rawDescription: Selectively retrieving depending on existence of key in map


code: xl.DisplayAlerts = False

rawDescription: How can I confidently set the attributes of dispatched objects using win32com

description: Confidently set the attributes of dispatched objects using win32com


code:
from Tkinter import *

sentence = [ 'this', 'is', 'an', 'example' ]
result   = [ 'x.Det', 'be.V', 'a.Det', 'example.N' ]

line_start = [0, len(sentence)] # Used to split the sentence into lines no longer than line_len
line_len = 20 # Max characters in each line, including extra spaces
segment_len = 0

for i in range(len(sentence)):
    s_len = len(sentence[i])
    r_len = len(result[i])

    # Pad words (or word groups) so the segments of sentence and result have the same width
    if s_len > r_len:
        result[i] += ' ' * s_len - r_len
    elif s_len < r_len:
        sentence[i] += ' ' * (r_len - s_len)

    segment_len += max(r_len, s_len) + 1

    # Check the line length
    if segment_len > line_len:
        segment_len = 0
        line_start.insert(1, i)

root = Tk()

for i in range(len(line_start)-1):
    sentence_segment = ' '.join( sentence[line_start[i]:line_start[i+1]] )
    ts = Text(root, font='TkFixedFont', width = line_len, height = 1)
    ts.insert(END, sentence_segment)
    ts.pack()

    result_segment = ' '.join( result[line_start[i]:line_start[i+1]] )
    tr = Text(root, font='TkFixedFont', width = line_len, height = 1, foreground='grey')
    tr.insert(END, result_segment)
    tr.pack()

root.mainloop()

rawDescription: How to modify Text widget in Tkinter for interlinear anotation

description: Modify Text widget in Tkinter for interlinear anotation


code:
def tfidf_gpu(appearance_in_documents,num_documents,document_words,TFIDF):
    start = perf_counter()
    ret = TFIDF(num_documents,appearance_in_documents,document_words)
    end = perf_counter()
    print("\nTFIDF_GPU ",end-start," secs.")
    return ret

APP = T.scalar('APP',dtype='int32')
N = T.scalar('N',dtype='int32')
SF = T.scalar('S',dtype='int32')
F = (T.log(N)-T.log(APP)) / SF
TFIDF = theano.function([N,APP,SF],F)

tfidf_gpu(appearance_in_documents,num_documents,document_words,TFIDF)

rawDescription: Theano GPU calculation slower than numpy


code:
def test_routes_cached(self):
    self.assertTrue(cache.get("/chart/upgrade/") is None)
    r1 = self.client.get("/chart/upgrade/")
    self.assertTrue(cache.get("/chart/upgrade/") is not None)

    # ... snip ...

    update_data(app)

    self.assertTrue(cache.get("/chart/upgrade/") is None)
    r_new = self.client.get("/chart/upgrade/")
    self.assertTrue(cache.get("/chart/upgrade/") is not None)

    # ... etc. ...

rawDescription: make unittest to test the caching status of several routes

description: Make unittest to test the caching status of several routes


rawDescription: Binary numbers in Python

description: Binary numbers in Python


code: [i[1] for i in sorted(zip(L, range(4)))]

rawDescription: Convert list of N items to relative ordering (0-(N-1))?


code:
car1 = []
car2 = []
car3 = []
car4 = []
car5 = []
cars = [car1,car2,car3,car4,car5]
for i in range(5):
    rand0m = randint(1,5)
    cars[i].append(rand0m)

rawDescription: How to change multiple variables ever iteration of a for loop

description: Change multiple variables ever iteration of a for loop


rawDescription: Python Cut Example

description: Python Cut Example


rawDescription: understanding csv DictWriter syntax in python

description: Understanding csv DictWriter syntax in python


code:
x = np.arange(16).reshape((4,2,2))
x.reshape(2,2,2,2).swapaxes(1,2).reshape(4,-1)

rawDescription: 3d Numpy array to 2d

description: 3d Numpy array to 2d


code:
cProfile.run('sum([number for number in range(9999999) if number % 2 == 0])')
cProfile.run('sum((number for number in range(9999999) if number % 2 == 0))')

rawDescription: Generators vs List Comprehension performance in Python


rawDescription: PyMongo find by multiple values

description: PyMongo find by multiple values


code:
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    '/var/www/static/',
)

rawDescription: Make two directories static in django

description: Make two directories static in django


code:
from traits.api import HasTraits, Float
class AA(HasTraits):
    a =Float()
class BB(HasTraits):
    b = Float()
aa = AA()
bb = BB()
aa.sync_trait("a", bb, "b")

# aa.a and bb.b are synchronized
# Now we use non-official API functions
info = aa._get_sync_trait_info()

synced = info.has_key("a") # True if aa.a is synchronized to some other trait
if synced:
    sync_info = info["a"] # fails if a is not a synchronized trait
    # sync_info is a dictionary which maps (id(bb),"b") to a tuple (wr, "b")
    # If you do not know the id() of the HasTraits-object and the name of
    # the trait, you have to loop through all elements of sync_info and
    # search for the entry you want...
    wr, name = sync_info[(id(bb), "b")]
    # wr is a weakref to the class of bb, and name is the name
    # of the trait which aa.a is synced to
    cls = wr() # <__main__.BB at 0x6923a98>

rawDescription: Inspect for synchronized traits: Traits/TraitsUI


code:
#TODO: must make sure about the indentation
import argparse
import re
import sys

PATCH_LINE = "import sys; sys.exit(0)  # PATCHED"

def parse_arguments():
    # take the file and the line to patch, or maybe we can take a
    # diff file generated via uniform_diff
    parser = argparse.ArgumentParser(description='enable and disable the automatic exit')
    parser.add_argument('file', help='file to patch')

    parser.add_argument('line', help='line where to quit')

    parser.add_argument('-m', '--msg',
                        default=PATCH_LINE)

    parser.add_argument('-d', '--disable',
                        action='store_true')

    return parser.parse_args()

if __name__ == '__main__':
    ns = parse_arguments()
    text = open(ns.file).readlines()
    line_no = int(ns.line)

    if ns.disable:
        # the line should not be necessary in that case?
        text.remove(text[line_no])
    else:
        # count spaces
        prev = text[line_no - 1]
        m = re.match('\s*', prev)
        to_insert = m.group() + ns.msg
        print("inserting line %s" % to_insert)
        text.insert(line_no, to_insert)

    open(ns.file, 'w').writelines(text)

rawDescription: Profile GUI application bootstrap

description: Profile GUI application bootstrap


code:
import pylab as plt
from numpy import random

plots, legend_names = [], []

x1 = [10,20,30]
y1 = [10,20,30]
# some fake data
x2 = [15, 25, 35]
y2 = [15, 25, 35]
x_vars = [x1, x2]
y_vars = [y1, y2]
legend_names = ['a','b']

# create figure
plt.figure()
plt.hold(True)

plots = []
proxies = []

for x_var, y_var in zip(x_vars, y_vars):
    markerline, stemlines, baseline = plt.stem(x_var, y_var)
    plots.append((markerline, stemlines, baseline))

    c = color = random.rand(3,1)

    plt.setp(stemlines, linewidth=2, color=c)     # set stems to random colors
    plt.setp(markerline, 'markerfacecolor', 'b')    # make points blue

    #plot proxy artist
    h, = plt.plot(1,1,color=c)
    proxies.append(h)
# hide proxies
plt.legend(proxies, legend_names, loc='best', numpoints=1)
for h in proxies:
    h.set_visible(False)
plt.show()

rawDescription: matplotlib: changing stem plot legend colors

description: Matplotlib: changing stem plot legend colors


code:
from flask.ext.testing import TestCase

from myapp import create_app, db

class MyTest(TestCase):

    SQLALCHEMY_DATABASE_URI = "sqlite://"
    TESTING = True

    def create_app(self):

        # pass in test configuration
        return create_app(self)

    def setUp(self):

        db.create_all()

    def tearDown(self):

        db.session.remove()
        db.drop_all()

rawDescription: testing flask sql alchemy

description: Testing flask sql alchemy


code:
import urllib

def recursive_urlencode(d):
    """URL-encode a multidimensional dictionary.

    >>> data = {'a': 'b&c', 'd': {'e': {'f&g': 'h*i'}}, 'j': 'k'}
    >>> recursive_urlencode(data)
    u'a=b%26c&j=k&d[e][f%26g]=h%2Ai'
    """
    def recursion(d, base=[]):
        pairs = []

        for key, value in d.items():
            new_base = base + [key]
            if hasattr(value, 'values'):
                pairs += recursion(value, new_base)
            else:
                new_pair = None
                if len(new_base) > 1:
                    first = urllib.quote(new_base.pop(0))
                    rest = map(lambda x: urllib.quote(x), new_base)
                    new_pair = "%s[%s]=%s" % (first, ']['.join(rest), urllib.quote(unicode(value)))
                else:
                    new_pair = "%s=%s" % (urllib.quote(unicode(key)), urllib.quote(unicode(value)))
                pairs.append(new_pair)
        return pairs

    return '&'.join(recursion(d))

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

rawDescription: urlencode a multidimensional dictionary in python

description: Urlencode a multidimensional dictionary in python


code: filter = ''.join([['.', chr(x)][chr(x) in string.printable[:-5]] for x in xrange(256)])

rawDescription: Munging non-printable characters to dots using string.translate()


code:
app.config["CACHE_TYPE"] = "null"
# change to "redis" and restart to cache again

# some time later
cache.init_app(app)

# All caching functions will simply call through
# to the wrapped function, with no caching
# (since NullCache does not cache).

rawDescription: How to disable Flask-Cache caching

description: Disable Flask-Cache caching


code:
import matplotlib.pyplot as plt
import numpy as np
import cartopy.crs as ccrs
import matplotlib.path as mpath

# Mollweide projection
fig = plt.figure()
ax = fig.add_subplot(111, projection=ccrs.Mollweide())

# Here I define a matplotlib Path object to use as the boundary
outlinex = np.concatenate([[-30],np.tile(-30,180), np.tile(30,180),[-30]])
outliney = np.concatenate([[-90],np.arange(-90,90),np.arange(89,-91,-1),[-90]])
outlinecodes = np.array([mpath.Path.MOVETO]+[mpath.Path.LINETO]*360+[mpath.Path.MOVETO])
outlinepath = mpath.Path(np.column_stack([outlinex[::-1], outliney[::-1]]), outlinecodes[::-1])

# For good measure, plot some data
ax.plot(np.arange(-10,25), np.linspace(80,45,35), transform=ccrs.Geodetic())
ax.plot(np.tile(25,91),np.arange(45,-46,-1), transform=ccrs.Geodetic())

# Plot gridlines and set the boundary
ax.gridlines(xlocs=np.arange(-30,31,10), ylocs=np.arange(-90,91,45))
ax.set_boundary(outlinepath, transform=ccrs.Geodetic(), use_as_clip_path=False)

# The plotting will have automatically set the extents, so set them to what we want
ax.set_extent((-30,30,-90,90))

plt.show()

rawDescription: matplotlib Basemap Fundamental Lune

description: Matplotlib Basemap Fundamental Lune


code:
y_normed = {k: (data-np.mean(data))/np.std(data)
            for k, data in my_time_series.items()}

maxlength = max(my_time_series)
x_interped = {k: np.interp(np.linspace(0, 1, maxlength),
                           np.linspace(0, 1, k), data)
              for k, data in y_normed.items()}

[plot(data) for data in x_interped.values()]

rawDescription: Normalization of several time-series of different lengths and scale


code:
def count_list(l):
    count = 0
    for e in l:
        if isinstance(e, list):
            count = count + 1 + count_list(e)
    return count

rawDescription: How to find the number of nested lists in a list?

description: Find the number of nested lists in a list


code: attr=(o.attr for o in objsm)

rawDescription: Extract list of attributes from list of objects in python


code:
import os

os.chdir(get_script_dir())

rawDescription: Setting a working folder to where my script lives in Python


rawDescription: pandas: extract a subset of columns where the column name contains a string

description: Pandas: extract a subset of columns where the column name contains a string


code:
def create_ini(db_file_paths):

    #array of file tmpfs ini filehandles
    file_handles = []

    for path in db_file_paths:
        #make a tempfs file handle
        f_handle = tempfile.NamedTemporaryFile(delete=False)
        #match and replace db dummy file path
        f_handle = replace( f_handle.name, source_ini, pattern, path )
        file_handles.append(f_handle)
    return file_handles # <-- change of indentation here

rawDescription: Create an array of temp files in python

description: Create an array of temp files in python


code:
class foo:
    def __init__(self,x):
        self.x = x
    def __eq__(self,y):
        return int(self.x)==int(y)

f = foo(5)
f == '5'
5 == '5'

rawDescription: Do Python equal types have different values ever?


code: E[x] = sum(x.P(x))

rawDescription: python scipy.stats pdf and expect functions

description: Python scipy.stats pdf and expect functions


rawDescription: access elements of a list from a modified list

description: Access elements of a list from a modified list


$oid: xxxxxxxxxxxxxxxxxx

username: boatzart

rawDescription: Sanitizing user input when inserting nested fields with pymongo


code:
import re
p = re.compile("lalala(I want this part)lalala")
p.match("lalalaI want this partlalala").group(1)

rawDescription: How can I get part of regex match as a variable in python?

description: Get part of regex match as a variable in python


code:
import numpy as np
from matplotlib import pyplot
x0 = 4; a = 5  # x center, half width
y0 = 2; b = 3  # y center, half height
x = np.linspace(-10, 10, 100)  # x values of interest
y = np.linspace(-5, 5, 100)[:,None]  # y values of interest, as a "column" array
ellipse = ((x-x0)/a)**2 + ((y-y0)/b)**2 <= 1  # True for points inside the ellipse
pyplot.imshow(ellipse, extent=(x[0], x[-1], y[0], y[-1]), origin="lower")  # Plot

rawDescription: Producing an array from an ellipse

description: Producing an array from an ellipse


code:
from redis import Redis

try:
    r_client = Redis() # assuming standard settings
    sentinel = r_client.incr("my_sentinel")
    if sentinel == 1:
        run_command()
    else:
        r_client.decr("my_sentinel")
except Exception as e:
    r_client.decr("my_sentinel")
    raise e

rawDescription: Monitor Management Command Execution in Django


rawDescription: using binary operator in Python... translating if (c1 >= "\xc0" & c1 <= "\xdf")

description: Using binary operator in Python... translating if (c1 >= "\xc0" & c1 <= "\xdf")


code:
import re
import fileinput

#  write concepts which are not not in log

with open("log.txt", 'r') as f,  open("substance.txt", "r") as oldfile, open('new_substance.txt', 'w') as newfile:
    # read f only once and convert it to a list
    logList = list(f)
    # remove everything that exists in f either with a +\t or a -\t
    withconceptsremoved = [x for x in oldfile if ('-\t'+x not in logList and '+\t'+x not in logList)]
    # convert to string and write to file
    withconceptsremoved = "".join(withconceptsremoved)
    newfile.write(withconceptsremoved)
    #  so the new file only has comments which are neither positive or negative in log.  If we now copy positive ones, we've removed the negatives
    #  write new additions to bottom of new file
    for line in logList:
        if '+\t' in line:
            addedconcept = line.replace('+\t','1\t')
            newfile.write(addedconcept)

rawDescription: python: updating file by finding unique values between two files, and then appending further data to bottom

description: Python: updating file by finding unique values between two files, and then appending further data to bottom


code:
userSelectionOptions = ['e', 'd', 'x']
print ("Please choose an option from the menu.")
user_input = ''
user_input = input("Please type E for encrypt message\n D for decrypt message or\n X to exit the program: \n")
while user_input.lower() not in userSelectionOptions:
    print ("Please choose an option from the menu.")
    user_input = input("Please type E for encrypt message\n D for decrypt message or\n X to exit the program: \n")

# do stuff with the input

rawDescription: Show menu until user input meets condition


code:
a = np.power(np.sin(np.deg2rad(range(0,180))),4 )
plt.plot(a)
plt.plot(np.gradient(a, np.deg2rad(1)))

rawDescription: Gradient of Sin(x)^4 is not same when calculated from its derivative


code:
from paradocx import Document
from paradocx.headerfooter import HeaderPart

template = 'template.docx'
newimg = open('new_file.png', 'r')

doc = Document.from_file(template)
header = doc.get_parts_by_class(HeaderPart).next()
img = header.related('http://schemas.openxmlformats.org/officeDocument/2006/relationships/image')[0]

img.data = newimg.read()
newimg.close()

doc.save('prueba.docx')

rawDescription: Replace picture (from page header)

description: Replace picture (from page header)


code:
from flask import Flask, request
import unittest
from werkzeug.routing import Rule

app = Flask(__name__)
app.url_map.add(Rule('/', endpoint='index'))

@app.endpoint('index')
def index():
    return request.method

class TestMethod(unittest.TestCase):

    def setUp(self):
        self.client = app.test_client()

    def test_custom_method(self):
        resp = self.client.open('/', method='BACON')
        self.assertEqual('BACON', resp.data)

if __name__ == '__main__':
    unittest.main()

rawDescription: Allow ALL method types in flask route

description: Allow ALL method types in flask route


code: person = db.ReferenceProperty(Person, collection_name="cars")

rawDescription: google-app-engine: How can I have a list of objects as property in another class?

description: Google-app-engine: How can I have a list of objects as property in another class


code:
cd1 = self.cleaned_data['string1_val']
lsi1 = latestSI.string1_val
cd2 = self.cleaned_data['string2_val']
lsi2 = latestSI.string2_val
if lsi1 is None:
  lsi1 = ''
if lsi2 is None:
  lsi2 = ''
return not (cd1 == lsi1 and cd2 == lsi2)

rawDescription: Looking for something more pythonic

description: Looking for something more pythonic


code:
f = open('another_csv.csv','w+')
for row in reader:
    try:
       url = row[4]
       req=urllib2.Request(url)
       tree = lxml.html.fromstring(urllib2.urlopen(req).read())
       print >>f,','.join(row)
    except:
       #can log the faulty links in another file
       continue
f.close()

rawDescription: Removing csv rows in Python

description: Removing csv rows in Python


code:
def fetch(entries):
   filename = ''.join(entries[f].get() for f in fields)
   print(filename)
   #whatever you want to do with the result

rawDescription: How do I assign a variable to a Tkinter input?

description: Assign a variable to a Tkinter input


code:
results = ...

inputs['open'] = np.array([r.get('open') for r in results], dtype=float)
...

rawDescription: better way to build numpy array for ta-lib

description: Better way to build numpy array for ta-lib


code:
s = df.choices.apply(Series).stack()
s.name = 'choices' # needs a name to join
del df['choices']
df1 = df.join(s.reset_index(level=1))
df1.columns = ['name', 'rank', 'choice']
df1.sort(['name', 'rank']).reset_index(drop=True)

rawDescription: Build a new DataFrame from an existing one with a column containing a list (populate new lines using a list)


code:
from array import array

width, height = 1000, 1000
array2d = [array('l', (0 for _ in xrange(width))) for _ in xrange(height)]

array2d[999][999] = 42

rawDescription: Can array.array() be used to define a 2d array?


code:
import numpy as np
from pandas import DataFrame
import matplotlib.pyplot as plt

Index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
Cols = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=Index, columns=Cols)

plt.pcolor(df)
plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.show()

rawDescription: python Making heatmap from DataFrame

description: Python Making heatmap from DataFrame


code: [(key1, key2) for key1, value1 in dicKeyEnc.items() for key2, value2 in dicKeyDec.items() if value1 == value2]

rawDescription: How can I use dic in python to search values and get a key?

description: Use dic in python to search values and get a key


code:
from OpenSSL import SSL
from twisted.internet import reactor, ssl
from twisted.web import client

class MyPolicy(client.BrowserLikePolicyForHTTPS):
    def creatorForNetloc(self, hostname, port):
        return ssl.optionsForClientTLS(
            hostname.decode("ascii"),
            extraCertificateOptions={'method': SSL.SSLv3_METHOD},
            trustRoot=self._trustRoot
        )

myAgent = client.Agent(reactor, contextFactory=MyPolicy())

rawDescription: Python Twisted How To Set the SSL Method for twisted.web.client.Agent using new IPolicyForHTTPS?


code:
from collections import namedtuple
A = namedtuple('A', 'x y')
lis = [A(100, 200), A(10, 20), A(1, 2)]
any(a.x==1 for a in lis)
[getattr(a, 'x')==1 for a in lis]

rawDescription: Check if namedtuple with value x exists in list


code:
from math import radians, cos, sin, asin, sqrt

def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a))
    km = 6367 * c
    return km

haversine(-1.7297, 53.3205, -1.6997, 53.3186)

rawDescription: How to calculate distance between points on python side of my appplication in way that is consistent in what database does

description: Calculate distance between points on python side of my appplication in way that is consistent in what database does


code:
from re import findall
somestr = 'ABCDABCDABCDABCDABCDABCD'
# no overlapping
for i in findall(".{3}", somestr):
    print(i)
# overlapping
for i in findall("(?=(.{3}))", somestr):
    print(i)

rawDescription: Looking for alternative, more pythonic, way to iterate over multiple characters on a string


code:
class MyView(QtGui.QGraphicsView):
    def __init__(self):
        QtGui.QGraphicsView.__init__(self)

        self.scene = QtGui.QGraphicsScene(self)
        self.item = QtGui.QGraphicsRectItem(400, 400, 400, 400)
        self.scene.addItem(self.item)
        self.setScene(self.scene)
    def paintMarkers(self, event):
        # event position is in coordinates relative to the view
        # so convert them to scene coordinates
        p = self.mapToScene(event.x(), event.y())
        self.circleItem = QtGui.QGraphicsEllipseItem(0,0,10,10)
        self.circleItem.setPos(p.x()-self.circleItem.boundingRect().width()/2.0,
                               p.y()-self.circleItem.boundingRect().height()/2.0)
        self.scene.addItem(self.circleItem)
        self.circleItem.setPen(QtGui.QPen(QtCore.Qt.red, 1.5))
        # self.setScene(self.scene) # <-- this line should not be needed here

    # Note, I've renamed the second argument `event`. Otherwise you locally override the QMouseEvent class
    def mousePressEvent(self, event):
        self.paintMarkers(event)
        # you may want to preserve the default mouse press behaviour,
        # in which case call the following
        return QGraphicsView.mousePressEvent(self, event)

rawDescription: Qgraphicsview items not being placed where they should be


rawDescription: merge data frames with duplicated indices

description: Merge data frames with duplicated indices


code:
import tarfile
tar = tarfile.open("docs.tar.gz")
f = tar.extractfile("docs.json")

# do something like f.read()
# since your file is json, you'll probably want to do this:

import json
json.loads(f.read())

rawDescription: Python read file within tar archive

description: Python read file within tar archive


code:
from scipy.cluster.hierarchy import linkage
from scipy.cluster.hierarchy import dendrogram
from scipy.spatial.distance import pdist
import matplotlib
from matplotlib import pyplot as plt
import numpy as np
from numpy import arange

fig = plt.figure(figsize=(5,7))
ax1 = plt.subplot(2, 1, 1)
cm = matplotlib.cm.Blues
X = np.random.random([5,5])
pmat = pdist(X, "euclidean")
linkmat = linkage(pmat)
dendrogram(linkmat)
x0,x1 = ax1.get_xlim()
y0,y1 = ax1.get_ylim()
ax1.set_aspect((x1-x0)/(y1-y0))

plt.subplot(2, 1, 2, aspect=1)
labels = ["a", "b", "c", "d", "e", "f"]
Y = np.random.random([6,6])
plt.xticks(arange(0.5, 7.5, 1))
plt.gca().set_xticklabels(labels)
plt.pcolor(Y)
plt.colorbar()

# add a colorbar to the first plot and immediately make it invisible
cb = plt.colorbar(ax=ax1)
cb.ax.set_visible(False)

plt.show()

rawDescription: how to make square subplots in matplotlib with heatmaps?

description: Make square subplots in matplotlib with heatmaps


code:
x=[]
y=[]
for line in open("data.dat"):
    if line.split()[1]=='950.0':
        newdata.write(line)
        x.append(line.split()[1])

rawDescription: Choosing specific lines from a data file


code:
from django.conf import settings
from myapp import myapp_defaults

settings.configure(default_settings=myapp_defaults, DEBUG=True)

description: Setting DJANGO_SETTINGS_VARIABLE manually


code:
SEV = PRI & 7
FAC = PRI >> 3

rawDescription: Reading least significant bits in Python


code:
data = ssn.query(models.MedicationLog.dose_date,
                         func.sum(func.array_length(
                             models.MedicationLog.dose_taken_times, ARRAY_DEPTH
                         )).label('dose_taken_times')).order_by(models.MedicationLog.dose_date).\
        group_by(models.MedicationLog.dose_date).all()

rawDescription: Sqlalchemy array_length function

description: Sqlalchemy array_length function


code:
soup = BeautifulSoup(html_doc)

def get_movie_info():
  tbl = soup.find('table')
  rows = tbl.findAll('tr')
  for row in rows:
    (imageTitle, dataTConst, number) = ('', '', '')
    cols = row.find_all('td')
    for col in cols:
        if col.has_attr('class') and col['class'][0] == 'image':
            href = col.find('a')
            imageTitle = href.get('title')
        elif col.has_attr('class') and col['class'][0] == 'title':
            span = col.find('span')
            if span.has_attr('class') and span['class'][0] == 'wlb_wrapper':
                dataTConst = span.get('data-tconst')
        elif col.has_attr('class') and col['class'][0] == 'number':
            number = col.text

    yield (imageTitle, dataTConst, number)

#################################################
import csv
outfile=csv.writer(open('outputrows.csv','wb'), delimiter='\t')
for row in get_movie_info():
    outfile.writerow(row)

rawDescription: How to output parsed HTML into a file?

description: Output parsed HTML into a file


code:
def forwards(self, orm):
    db.execute("CREATE TABLE new_table LIKE old_table")
    db.execute("INSERT new_table SELECT * old_table")

def backwards(self, orm):
    db.drop_table('new_table')

rawDescription: duplicate table (identical) including primary key - using django south

description: Duplicate table (identical) including primary key - using django south


code:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='subparser_name')

base_subparser = argparse.ArgumentParser(add_help=False)
# define common shared arguments
base_subparser.add_argument('--disable')

sp = subparsers.add_parser('compile', parents=[base_subparser])
# define custom arguments
sp = subparsers.add_parser('launch', parents=[base_subparser])
# define custom arguments

rawDescription: Permit argparse global flags after subcommand


code:
import thread

def give_output():
    while True:
        pass  # output stuff here

def get_input():
    while True:
        pass  # get input here

thread.start_new_thread(give_output, ())
thread.start_new_thread(get_input, ())

rawDescription: How to keep a While True loop running with raw_input() if inputs are seldom?

description: Keep a While True loop running with raw_input() if inputs are seldom


code:
string_list = ['this is a string', 'and this', 'also this',
           'this and this is a string', 'is this a string']
seen = set()
for ele in reversed(string_list):
    tp = tuple(sorted(ele.split()))
    if tp in seen:
        string_list.remove(ele)
    seen.add(tp)

print(string_list)
['this is a string', 'and this', 'also this', 'this and this is a string']

rawDescription: Python: remove strings with same words

description: Python: remove strings with same words


rawDescription: Python like sed using regexes

description: Python like sed using regexes


code:
def get_name(employee):
    return employee.name

rawDescription: Python - Apply member function in a map

description: Python - Apply member function in a map


code:
def special_replace(s):
    p=re.compile(r"(http://.*?)(\.?source\.com)")
    spl=p.split(s)
    newtext=[]
    for text in spl:
        if text.startswith("http://"):
            text=text.replace(".","_")
        elif text.endswith("source.com"):
            text=text.replace("source.com", "target.com")
        newtext.append(text)
    return "".join(newtext)

rawDescription: Python regex if group-match then put-different-character


code: df.to_excel('output.xlsx', 'Sheet1')

rawDescription: Does xlwings require an excel install

description: Does xlwings require an excel install


rawDescription: Formating number string with commas for currency type dispaly


code:
import urllib3, requests, json

url = "https://myjenkins.com/job/myjob"

params = {"parameter": [
    {"name": "integration.xml", "file": "file0"},
    ]}
with open("integration.xml", "rb") as f:
    file_data = f.read()
data, content_type = urllib3.encode_multipart_formdata([
    ("file0", (f.name, file_data)),
    ("json", json.dumps(params)),
    ("Submit", "Build"),
    ])
resp = requests.post(url, auth=("myuser", "mypassword"), data=data,
        headers={"content-type": content_type}, verify=False)
resp.raise_for_status()

rawDescription: How to trigger authenticated Jenkins job with file parameter using standard Python library

description: Trigger authenticated Jenkins job with file parameter using standard Python library


code:
import flask
# patch flask.render_template()
_render_template = flask.render_template
def _my_render_template(*args, **kwargs):
    if detect_mobile_browser(flask.request.user_agent.string):
        args = ('m/' + args[0],) + args[1:]
    return _render_template(*args, **kwargs)
flask.render_template = _my_render_template

rawDescription: How to organize code for a Flask application with multiple set of templates

description: Organize code for a Flask application with multiple set of templates


code: db = sqlite.connect(filename, timeout=30.0)

rawDescription: Multiprocess sqlite INSERT: "database is locked"


code:
import django
from django.conf import settings

settings.configure(INSTALLED_APPS=['mathfilters'])
django.setup()

rawDescription: Use Django templates and tags without the rest of Django


code:
from os.path import expanduser
home = expanduser("~")

rawDescription: How to get the home directory in Python?

description: Get the home directory in Python


code:
from urlparse import urlparse
urlparse('http://www.google.com/').hostname
urlparse('http://www.google.com/').hostname.split('.')[1]

rawDescription: Extract domain name from the url

description: Extract domain name from the url


code:
def handle_uploaded_file(f):
    with open('some/file/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

rawDescription: python script to handle uploaded file via http post

description: Python script to handle uploaded file via http post


code:
import itertools
a = 'what are you doing to this cat?'.split()
for permutation in itertools.permutations(a,):
    print(*permutation)

rawDescription: Python 3.4.3 - How to save a itertools.permutations list usable?


code:
#!/usr/bin/python

from PIL import Image

margin=20
X=150
Y=150
in_path="flower.jpg"
out_path="thumbnail.png"

#creates a transparent background, RGBA mode, and size 150 by 150.
background = Image.new('RGBA', (X,Y))

# opening an image and converting to RGBA:
img = Image.open(in_path).convert('RGBA')

# Resizing the image

img = img.resize((X, Y-margin*2), Image.ANTIALIAS)

# Putting thumbnail on background

background.paste(img, (0, margin), img)
background.save(out_path)

rawDescription: Python generate thumbnail with transparancy and fixed width


code:
def build_tree(preord, inord):
    tree = BinaryTree()
    tree.root = buildTreeHelper(preord, inord)
    return tree

def buildTreeHelper(preorder, inorder):
    if len(inorder) == 0:
        return empty

    elem = preorder[0]
    elemInorderIndex = inorder.find(elem)

    if elemInorderIndex > -1:
        leftPreorder = preorder[1:elemInorderIndex + 1]
        rightPreorder = preorder[elemInorderIndex + 1:]
        leftInorder = inorder[0:elemInorderIndex]
        rightInorder = inorder[elemInorderIndex + 1:]
        left = buildTreeHelper(leftPreorder, leftInorder)
        right = buildTreeHelper(rightPreorder, rightInorder)
        return BinaryTreeNode(elem, left, right)
    else:
        return "No valid tree for the given args"

class BinaryTree:
    def __init__(self):
        self.root = empty
    def preorder(self):
        return self.root.preorder()
    def inorder(self):
        return self.root.inorder()
    def postorder(self):
        return self.root.postorder()

class EmptyNode:
    def preorder(self):
        return ()
    inorder = postorder = preorder
empty = EmptyNode()

class BinaryTreeNode:
    def __init__(self, element, left=empty, right=empty):
        self.element = element
        self.left = left
        self.right = right
    def preorder(self):
        yield self.element
        for e in self.left.preorder():
            yield e
        for e in self.right.preorder():
            yield e
    def inorder(self):
        for e in self.left.inorder():
            yield e
        yield self.element
        for e in self.right.inorder():
            yield e
    def postorder(self):
        for e in self.left.postorder():
            yield e
        for e in self.right.postorder():
            yield e
        yield self.element

if __name__ == "__main__":
    t = build_tree("BAC", "ABC")
    for e in t.inorder():
        print(e)

rawDescription: Python: binary tree traversal iterators without using conditionals


code:
def foo(self, bar):
    session = Session.object_session(self)
    #....

rawDescription: How can I use the Engine within a SQLAlchemy declarative class?

description: Use the Engine within a SQLAlchemy declarative class


code:
import csv
with open('t.txt') as f:
   reader = csv.DictReader(f,dialect='excel-tab')
   rows = list(reader)

rows[0]

rawDescription: Python table construction

description: Python table construction


code:
# setup the plot
fig, ax = plt.subplots(1,1, figsize=(6,6))

# define the data
x = np.random.rand(20)
y = np.random.rand(20)
tag = np.random.randint(0,20,20)
tag[10:12] = 0 # make sure there are some 0 values to showup as grey

# define the colormap
cmap = plt.cm.jet
# extract all colors from the .jet map
cmaplist = [cmap(i) for i in range(cmap.N)]
# force the first color entry to be grey
cmaplist[0] = (.5,.5,.5,1.0)
# create the new map
cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)

# define the bins and normalize
bounds = np.linspace(0,20,21)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# make the scatter
scat = ax.scatter(x,y,c=tag,s=np.random.randint(100,500,20),cmap=cmap, norm=norm)

# create a second axes for the colorbar
ax2 = fig.add_axes([0.95, 0.1, 0.03, 0.8])
cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap, norm=norm, spacing='proportional', ticks=bounds, boundaries=bounds, format='%1i')

ax.set_title('Well defined discrete colors')
ax2.set_ylabel('Very custom cbar [-]', size=12)

rawDescription: Matplotlib discrete colorbar

description: Matplotlib discrete colorbar


rawDescription: How to round by a total digits(including integer part) instead of a fixed digit in python?

description: Round by a total digits(including integer part) instead of a fixed digit in python


code:
import numpy as np
from scipy import integrate

a = np.array([2,4,6,8])
b = np.array([1,2,3,4])
d = np.empty_like(b)
d[0] = a[0] * b[0]
for i in range(2, len(a) + 1):
    d[i-1] = integrate.simps(b[0:i], a[0:i])
print(d)

rawDescription: Cumulative integration of elements of numpy arrays


code:
import numpy as np
from scipy import stats
logsample = stats.norm.rvs(loc=10, scale=3, size=1000) # logsample ~ N(mu=10, sigma=3)
sample = np.exp(logsample) # sample ~ lognormal(10, 3)
shape, loc, scale = stats.lognorm.fit(sample, floc=0) # hold location to 0 while fitting
shape, loc, scale
np.log(scale), shape  # mu, sigma

rawDescription: scipy, lognormal distribution - parameters

description: Scipy, lognormal distribution - parameters


code:
from flask import Flask
app = Flask(__name__)
data_loader = lambda: range(10) # this function should load your data from some external store
@app.route("/")
def main():
    body = "\n".join(["
%s
" % datum for datum in data_loader()])
    page = """%s
              """ % body
    return page

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

rawDescription: Pass data from python script to HTML

description: Pass data from python script to HTML


code:
import random
import time
import threading
import logging
import Queue

logger=logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)

sentinel=None
queue = Queue.Queue()
num_threads = 5

def foobar_task(queue):
    while True:
        n = queue.get()
        logger.info('task called: {n}'.format(n=n))
        if n is sentinel: break
        n=random.random()
        if n > .25:
            logger.info("task appended to queue")
            queue.put(n)
        queue.task_done()

# set up initial queue
for i in range(num_threads):
    queue.put(i)

threads=[threading.Thread(target=foobar_task,args=(queue,))
         for n in range(num_threads)]
for t in threads:
    t.start()

queue.join()
for i in range(num_threads):
    queue.put(sentinel)

for t in threads:
    t.join()
logger.info("threads are closed")

rawDescription: Determining when a ThreadPool has finished processing a queue


code:
class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

rawDescription: Best way to auto-update Python Class Attributes

description: Auto-update Python Class Attributes


rawDescription: Simple syntax for bringing a list element to the front in python?


code:
def someFunc(self):
    i = 0
    someSelector = objc.selector(self.someSelector, signature='v@:')
    while i < 20:
        self.performSelectorOnMainThread_withObject_waitUntilDone(someSelector, None, False)
        NSLog(u"Hello I am in someFunc")
        i = i + 1

@objc.IBAction
def buttonPress(self, sender):
    NSThread.detachNewThreadSelector_toTarget_withObject_(self.threadedFunc, self, 1)

def threadedFunc(self):
    NSLog(u"Entered threadedFunc")
    self.t = NSTimer.NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(1/150., self,self.someFunc,None, True)
    NSLog(u"Kicked off Runloop")
    self.t.fire()

rawDescription: How to spawn threads in pyobjc

description: Spawn threads in pyobjc


code:
attrs = xattr.getxattr('/path/to/dir', u'com.apple.FinderInfo')
ispackage = bool(ord(attrs[8]) & 0x20)  # I *think* this is correct; works for hidden dirs and & 0x40

rawDescription: Identify directories that are packages in Mac OS X with Python


code:
def encrypt(data):
    n = len(data)
    for i in range(n-1, 0, -1):
        data[i] ^= data[i-1]      # for this to work, data has to be mutable

f = open('somefile.bin', 'rb')
buf = bytearray(f.read())
f.close()

encrypt(buf)

rawDescription: for loop c++ vs python

description: For loop c++ vs python


code:
cost_f = []
while (abs(theta1_guess-theta1_last) > variance or abs(theta0_guess - theta0_last) > variance):

    theta1_last = theta1_guess
    theta0_last = theta0_guess

    hypothesis = create_hypothesis(theta1_guess, theta0_guess)
    cost_f.append((1./(2*m))*sum([ pow(hypothesis(point[0]) - point[1], 2) for point in data]))

    theta0_guess = theta0_guess - learning_rate * (1./m) * sum([hypothesis(point[0]) - point[1] for point in data])
    theta1_guess = theta1_guess - learning_rate * (1./m) * sum([ (hypothesis(point[0]) - point[1]) * point[0] for point in data])

import pylab
pylab.plot(range(len(cost_f)), cost_f)
pylab.show()

rawDescription: How to determine the learning rate and the variance in a gradient descent algorithm？

description: Determine the learning rate and the variance in a gradient descent algorithm？


code:
import re
pattern = re.compile("\t+")

rdd = sc.parallelize([
    u"foo\t\t\t\tbar",
    u"123\t\t\t456\t\t789\t0"
])

rdd.map(lambda x: pattern.split(x)).collect()

## [[u'foo', u'bar'], [u'123', u'456', u'789', u'0']]

rawDescription: PySpark - Split records of an RDD by one or more tabs


code:
import numpy as np
from scipy.interpolate import UnivariateSpline

def make_norm_dist(x, mean, sd):
    return 1.0/(sd*np.sqrt(2*np.pi))*np.exp(-(x - mean)**2/(2*sd**2))

x = np.linspace(10, 110, 1000)
green = make_norm_dist(x, 50, 10)
pink = make_norm_dist(x, 60, 10)

blue = green + pink

# create a spline of x and blue-np.max(blue)/2
spline = UnivariateSpline(x, blue-np.max(blue)/2, s=0)
r1, r2 = spline.roots() # find the roots

import pylab as pl
pl.plot(x, blue)
pl.axvspan(r1, r2, facecolor='g', alpha=0.5)
pl.show()

rawDescription: Finding the full width half maximum of a peak


code:
import numpy as np
import cv2

params = np.zeros([1, 2])  # init params
s_img = np.zeros((512, 512, 3), np.uint8)
window_name = 'img'

def main():
    global s_img
    img = np.ones([512, 512, 3]) * 255
    s_img = cv2.resize(img, (0, 0), fx=0.5, fy=0.5)

    cv2.startWindowThread()
    cv2.imshow(window_name, s_img)

    print ('Click corners to determine the field')
    cv2.setMouseCallback(window_name, on_mouse, None)

    while True:
        k = cv2.waitKey(0) & 0xFF

        if k == 27:
            break # destroy window

def on_mouse(event, x, y, flag, param):
    global s_img
    if event == cv2.EVENT_LBUTTONDOWN:
        print ('here')
        cv2.circle(s_img, (x, y), 100, (255, 0, 0), -1)
        cv2.imshow(window_name, s_img)

if __name__ == '__main__':
    main()

rawDescription: cv2.circle() not showing

description: Cv2.circle() not showing


code:
Hashes = {
    'MD5': hashlib.md5,
    'SHA1': hashlib.sha1,
    'SHA224': hashlib.sha224,
    'SHA256': hashlib.sha256,
    'SHA384': hashlib.sha384,
    'SHA512': hashlib.sha512
}

...

return Hash(data.encode("utf8")).hexdigest()

rawDescription: Python 3: Hashes not generating correctly


code: import seaborn.apionly as sns

rawDescription: How can I use seaborn without changing the matplotlib defaults?

description: Use seaborn without changing the matplotlib defaults


code:
def quicksort(aList, start, last):
  i = start + 1
  j = start + 1
  pivot = aList[start]
  while j <= last:
    if pivot > aList[j]:
      temp = aList[i]
      aList[i] = aList[j]
      aList[j] = temp
      i = i + 1
    j = j + 1

  temp = aList[start]
  aList[start] = aList[i-1]
  aList[i-1] = temp
  if i - start > 2:
    quicksort(aList, start, i-2)
  if last - i > 0:
    quicksort(aList, i, last)

rawDescription: Quicksort in python

description: Quicksort in python


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

fig = plt.figure()
# create a 1-row 3-column container as the left container
gs_left = gridspec.GridSpec(1, 3)

# create a 1-row 1-column grid as the right container
gs_right = gridspec.GridSpec(1, 1)

# add plots to the nested structure
ax1 = fig.add_subplot(gs_left[0,0])
ax2 = fig.add_subplot(gs_left[0,1])
ax3 = fig.add_subplot(gs_left[0,2])

# create a
ax4 = fig.add_subplot(gs_right[0,0])

# now the plots are on top of each other, we'll have to adjust their edges so that they won't overlap
gs_left.update(right=0.65)
gs_right.update(left=0.7)

# also, we want to get rid of the horizontal spacing in the left gridspec
gs_left.update(wspace=0)

rawDescription: control wspace for matplotlib subplots

description: Control wspace for matplotlib subplots


rawDescription: Removing duplicates in lists

description: Removing duplicates in lists


code:
plt.Figure()
thismanager = get_current_fig_manager()
thismanager.window.wm_iconbitmap("icon.ico")

rawDescription: Change icon in a Matplotlib figure window


code:
def square(length, level):
    # Start from the bottom-left corner
    if level == 0:
        return
    else:
        # Draw the bottom side
        forward(length)
        # Draw the right square
        square(length // 2, level - 1)
        # Assume we ended at the same position
        # Draw the right side
        lt(90); forward(length)
        # Draw the upper side
        lt(90); forward(length)
        # Draw the left side
        lt(90); forward(length)
        # Go backward
        lt(90); backward(length // 2) ;
        # Draw the left square
        square(length // 2, level - 1)
        # Go back to the original position
        forward(length // 2)

rawDescription: Generate fractal squares using recursion


code:
import time

import pykeyboard

# TODO: Replace following two lines with the code that activate the application.
print('Activate the application 3 seconds.')
time.sleep(3)

k = pykeyboard.PyKeyboard()
k.press_key(k.left_key)
time.sleep(1) # Hold down left key for 1 second.
k.release_key(k.left_key)

rawDescription: Can Python be used to send a true key down event to Mac


code:
from mock import Mock, call

preprocess_sentinels = [Mock() for _ in range(5)]
mock_preprocess.side_effect = preprocess_sentinels
rows = [Mock() for _ in range(5)]

convert(rows)

mock_preprocess.assert_has_calls([call(r) for r in rows])
args, kwargs = mock_batch_process.call_args
assert args[0]
for v, e in zip(args[1], preprocess_sentinels):
    assert v == e

rawDescription: How to assert that a mock function is called with a generator?

description: Assert that a mock function is called with a generator


code:
from datetime import datetime
from random import shuffle

def timer(data, sortfn):
    start = datetime.now()
    sortfn(data)
    end = datetime.now()
    return end - start

def tester():
    lengths = (25, 100, 1000, 10000)
    sortfns = (selectionSort, bubbleSort, pythonSort, insertionSort)
    for length in lengths:
        myList = list(range(length))
        shuffle(myList)
        for sortfn in sortfns:
            # Take a deep copy of the shuffled data
            shuffled = myList[:]
            # Sort the shuffled data
            elapsed = timer(shuffled, sortfn)
            print("{0}({1}): {2}".format(sortfn.__name__, length, elapsed))

tester()

rawDescription: Python - need help looping a list through functions using 4 different ranges (0-25, 0-100, 0-1000, 0-10000)


code: Popen(['/bin/bash', '-c', 'cat <(%s)' % cmd])

rawDescription: Python Popen can't open bash shell in CentOS/Red Hat


code:
class UserViewSet(viewsets.ModelViewSet):
    ...

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        # Define how would you like your response data to look like.
        response_data = {
            "success": "True",
            "message": "Successfully sent",
            "user": serializer.data
        }
        return Response(response_data, status=status.HTTP_201_CREATED, headers=headers)

rawDescription: custom json response after creating user in django rest framework

description: Custom json response after creating user in django rest framework


code:
import re
import pandas as pd
import numpy as np

# clear quoting characters
def filterTheField(s):
    m = re.match(r'^"?(.*)?"$', s.strip())
    if m:
        return m.group(1)
    else:
        return np.nan

file = 'test.csv'

y = np.genfromtxt(file, delimiter = ',', filling_values = np.nan, names = True, dtype = type(None), converters = {'row_ID': filterTheField, 'label': filterTheField,'val': float})

d = pd.DataFrame(y)

print(d)

rawDescription: read csv-data with missing values into python using pandas

description: Read csv-data with missing values into python using pandas