code:
class JsonType(types.TypeDecorator):
    impl = types.Unicode

    def process_bind_param(self, value, dialect):
        return json.dumps(value)

    def process_result_value(self, value, dialect):
        return json.loads(value)

rawDescription: SQL Alchemy ORM Getter

description: SQL Alchemy ORM Getter


code:
import tarfile
tar=tarfile.open('folder1.tar.gz')
for member in tar.getmembers():
  if member.name.startswith('folder2/') and member.isfile():
    inputfile = tar.extractfile(member)
    with open(os.path.join(targetdirectory, member.name.replace('folder2/', '')), 'wb') as outputfile:
      outputfile.write(inputfile.read())
    inputfile.close()

rawDescription: How to go one level back directory during untar the tar file in python

description: Go one level back directory during untar the tar file in python


code:
import turtle
import Tkinter
import sys
import easygui as eg

def isNum(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

run = True
while run:

    msg         = "Input"
    title       = "Koch snowflake"
    fieldNames  = ["Length","Depth"]
    fieldValues = []  # we start with blanks for the values
    fieldValues = eg.multenterbox(msg,title, fieldNames)

    a=0
    iterations=0
# make sure that none of the fields was left blank
    while 1:  # do forever, until we find acceptable values and break out
        if fieldValues == None:
            break
        errmsg = ""

        # look for errors in the returned values
        for i in range(len(fieldNames)):
            if fieldValues[i].strip() == "":
                errmsg = errmsg + ('"%s" must be filled.\n\n' % fieldNames[i])
            elif not (isNum(fieldValues[i].strip())):
                errmsg = errmsg + ('"%s"  requires a number.\n\n' % fieldNames[i])

        if (isNum(fieldValues[1])):
            if float(fieldValues[1].strip()) > 13:
                errmsg = errmsg + ('Depth cannot be more than 13!')

        if errmsg == "":
            break # no problems found
        else:
            # show the box again, with the errmsg as the message
            fieldValues = eg.multenterbox(errmsg, title, fieldNames, fieldValues)

    #a=float(input("Length: "))
    if not fieldValues == None:
        if isNum(fieldValues[0]) and isNum(fieldValues[1]):
            a=float(fieldValues[0])
            iterations=int(fieldValues[1])
    else:
        sys.exit(0)

    root = Tkinter.Tk()
    cv = turtle.Canvas(root, width=200, height=200)
    cv.pack()
    screen = turtle.TurtleScreen(cv)
    screen.bgcolor("black")
    myturtle = turtle.RawTurtle(screen)

    def lastAction():
        global myturtle
        del myturtle
        root.destroy()
    root.protocol('WM_DELETE_WINDOW', lastAction)

    try:
#turtle settings
        screen.bgcolor("black")
        myturtle.reset()
        myturtle.up()
        myturtle.setpos(-a*1.5 ,a)
        myturtle.down()
        turtle.delay(0)
        myturtle.speed(0)
        myturtle.pencolor("white")

        koch_flake = "EJEJE"

        for i in range(iterations):
            koch_flake = koch_flake.replace("E","EBEJEBE\n")

        myturtle.down()

        for move in koch_flake:
            if move == "E":
                myturtle.forward(a / (3 ** (iterations - 1)))
            elif move == "B":
                myturtle.left(60)
            elif move == "J":
                myturtle.right(120)
        myturtle.hideturtle()
    except NameError:
        pass

    image   = "KochSnowflake.gif"
    msg = "Run it again?"
    title = "Please Confirm"
    if eg.ynbox(msg, title,('Yes', 'No'),image):     # show a Continue/Cancel dialog
        run = True
    else:  # user chose Cancel
        sys.exit(0)

rawDescription: Get tkinter.tclerror when closing python turtle before it finished it's draw


code:
import os
replacement = """some
multi-line string"""
for dname, dirs, files in os.walk("some_dir"):
    for fname in files:
        fpath = os.path.join(dname, fname)
        with open(fpath) as f:
            s = f.read()
        s = s.replace("{$replace}", replacement)
        with open(fpath, "w") as f:
            f.write(s)

rawDescription: Python - Way to recursively find and replace string in text files


code:
sample="""
blah

        html content to extract

test

other blah

    """

import htql
htql.query(sample, "
2")
# [('\n        html content to extract \n
test
\n        ',)]

htql.query(sample, "
 {a=
:tx; b=
2 | a='blah'} ")
# [('blah', '\n        html content to extract \n
test
\n        ')]

rawDescription: How to extract html between two different tags in python?

description: Extract html between two different tags in python


code:
table = gtk.Table(rows=1, columns=3)
table.attach(photo_container, 0, 2, 0, 1) # Span column 0..2
table.attach(exif_container, 2, 3, 0, 1)  # Span final column
window.add(table)

rawDescription: Equivalent of a "weight" parameter in pyGTK?


code:
a = df["Volume"].cumsum().clip_upper(20)
b = a.shift().fillna(0)
filled_a = a - b

rawDescription: Pandas cumulative/elementwise

description: Pandas cumulative/elementwise


code:
from collections import Counter

cn = Counter(s)
print([x for x in s if cn[x] > k])

rawDescription: inserting variable inside if of list filter [ ]

description: Inserting variable inside if of list filter [ ]


code:
from bs4 import BeautifulSoup
import paramiko

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.connect('example.com', username='Oli', look_for_keys=True, timeout=5)

stdin, stdout, stderr = ssh.exec_command('/usr/bin/wget -qO- "%s"' % url)
soup = BeautifulSoup(stdout)

ssh.close()

rawDescription: Python version of ssh -D (SOCKS proxy over SSH)


code:
def fun(a, b):
    if not (isinstance(a, set) and isinstance(b, set)):
        raise TypeError("Please only call this function with sets as the arguments")
    a.pop()
    a.pop()
    b.add(a.pop())
    return b

rawDescription: How to specify that a function parameter should be of a specific data type?

description: Specify that a function parameter should be of a specific data type


code:
prof = cProfile.Profile()
retval = prof.runcall(self.method_actual, *args, **kwargs)
prof.dump_stats(datafn)

rawDescription: Return value while using cProfile

description: Return value while using cProfile


code:
df_columns = ['a', 'b', 'a', 'a_2', 'a_2', 'a', 'a_2', 'a_2_2']

def uniquify(df_columns):
    seen = set()

    for item in df_columns:
        fudge = 1
        newitem = item

        while newitem in seen:
            fudge += 1
            newitem = "{}_{}".format(item, fudge)

        yield newitem
        seen.add(newitem)

list(uniquify(df_columns))
#>>> ['a', 'b', 'a_2', 'a_2_2', 'a_2_3', 'a_3', 'a_2_4', 'a_2_2_2']

rawDescription: Automatically rename columns to ensure they are unique


code:
conn = MySQLdb.connect(host='localhost')
r = conn.cursor()
r.execute('INSERT INTO users (hash) VALUES (%s)', m.digest())
conn.commit()

rawDescription: How to create SQL queries using an SHA-1 digest of a string using Python

description: Create SQL queries using an SHA-1 digest of a string using Python


code:
import matplotlib.cbook as cbook
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from matplotlib import cm
from numpy.random import randn

# Load sample image
image_file = cbook.get_sample_data('grace_hopper.png')
data = plt.imread(image_file)
data = data[:,:,0]  # Take only one channel for a grey scale image.

#data = np.clip(randn(250, 250), -1, 1)

fig, ax = plt.subplots()

cax = ax.imshow(data, interpolation='nearest', cmap=cm.afmhot)
ax.set_title('colorBar fun')

dataMin = np.amin(data)
dataMax = np.amax(data)
mid = ((dataMax - dataMin) / 2) + dataMin
cbar = fig.colorbar(cax, ticks=[dataMin, mid, dataMax], orientation='horizontal')
cbar.ax.set_xticklabels(['Low', 'Medium', 'High'])# horizontal colorbar

plt.show()

rawDescription: issues with PyPlot color bar tick marks with images

description: Issues with PyPlot color bar tick marks with images


code:
import os
logconf_file = os.path.join(os.path.dirname(__file__), 'logging.conf')
logging.config.fileConfig(logconf_file)

rawDescription: How to distribute logging config with Python package

description: Distribute logging config with Python package


rawDescription: pandas converting numbers to corresponding elements of a list

description: Pandas converting numbers to corresponding elements of a list


code:
data_dict = defaultdict(dict)
for key, value in data:
    data_dict[key][value] = 1

data_dict

rawDescription: Creating a nested dictionary from a list of tuples


code:
# List all children without security checks
context.restrictedTraverse(path).objectValues()
# List all ids without security checks
context.restrictedTraverse(path).objectIds()
# List all ids/values without security checks
context.restrictedTraverse(path).contentItems()
# You can use the catalog, this includes security checks and more.
# This will return a catalog results (brains), not the actual object.
context.restrictedTraverse(path).objectIds().getFolderContents()

rawDescription: Retrieve contents of objects from Plone using Python script


code:
with open('c:\\file.csv', 'rb') as f:
    reader = csv.reader(f)
    result = collections.defaultdict(list)
    unwantedKeys = set()
    for row in reader:
        key = row[1]
        if 'CITY' in row[8]:
            unwantedKeys.add(key)
            if key in result:
                result.pop(key)
        if key not in unwantedKeys:
            result[key].append([row[0], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12]])

rawDescription: Python Dictionary Pop

description: Python Dictionary Pop


code:
def application(env, respond):
    respond('200 OK', [('Content-Type', 'text/plain')])
    return ['\n'.join('%s: %s' % (k, v) for (k, v) in env.iteritems())]

rawDescription: Test page for mod_wsgi

description: Test page for mod_wsgi


code:
from Bio import trie
tr = trie.trie()

rawDescription: How to perform efficient membership search on very large datasets in Python

description: Perform efficient membership search on very large datasets in Python


code:
TEAMS = (
    ("r","red"),
    ("b","black"),
)

class Story(models.Model):
    team = models.CharField(max_length=1, choices=TEAMS)
    title = models.CharField()
    prologue = models.TextField()

rawDescription: I want to write a generic function to pair two database fields


rawDescription: Pass n arguments to a third party function


code:
@app.route('/')
def index():
    return app.send_static_file('index.html')

app.run(host="0.0.0.0", debug=True)

rawDescription: Serve static files with Eve

description: Serve static files with Eve


code:
#!/usr/bin/python
text_file=open('read.txt', 'r')
filename = text_file.readlines()
f = open('out.txt', 'w')
for elem in filename:
    #print f, 'set security idp idp-policy $policy rulebase-ips rule
    f.write('set security idp idp-policy $policy rulebase-ips rule  matchattacks predefined-attacks'+ elem+'\n')
f.close()

rawDescription: Print a sentence multiple times after concatenating a list in every sentence


code:
catalog = self.context.portal_catalog
my_keys = catalog.uniqueValuesFor('Subject')

rawDescription: Python/Plone: Getting all unique keywords (Subject)


code:
import gc

# Remove text variable
del text
# Force gc collection - this not actually necessary, but may be useful.
gc.collect()

rawDescription: Freeing up buffer space after use in Python?


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

z = np.sin(np.arange(100) / 2).reshape(10, 10)
z = np.ma.masked_array(z, z < -.5)

cmap = plt.cm.Reds
plt.pcolormesh(z, vmin=-1, vmax=1, cmap="RdYlBu")
plt.colorbar()

rawDescription: Correct way to set color to transparent with matplotlib.pcolormesh()?


code:
import os
import tempfile

with tempfile.NamedTemoraryFile(suffix='.xls') as file:
    file.write(content)
    file.delete = False

try:
    result = ReadFromExcel(file.name)
finally:
    os.remove(file.name)

rawDescription: XLRD and HTTP Excel Files in Python

description: XLRD and HTTP Excel Files in Python


code:
import numpy as np
from scipy.ndimage import convolve, generate_binary_structure

gen = np.random.RandomState(0)
A = gen.random_integers(0, 3, (6, 6))   # input array
k = generate_binary_structure(2, 1)     # kernel
B = convolve(A, k, mode='wrap')         # use mode='wrap' for periodic boundaries

print(A)
# [[0 3 1 0 3 3]
#  [3 3 1 3 1 2]
#  [0 3 2 0 0 0]
#  [2 1 2 3 3 2]
#  [0 1 1 1 1 0]
#  [1 0 3 0 3 1]]

print(k)
# [[False  True False]
#  [ True  True  True]
#  [False  True False]]

print(B)
# [[10  7  8  7 10  9]
#  [ 8 13 10  5  9  9]
#  [ 8  9  8  8  4  4]
#  [ 5  9  9  9  9  7]
#  [ 4  3  8  6  8  4]
#  [ 2  8  5  7  8  8]]

rawDescription: Vectorizing sum of nearest neighbours in matrix using Numpy


code:
import smtplib
import unittest

def sendmail(from_who, to, msg):
    s = smtplib.SMTP('localhost')
    s.sendmail(from_who, [to], msg)
    s.quit()

class MyTestResult(unittest.TestResult):
    def addError(self, test, err):
        self.super(MyTestResult, self).addError(test, err)
        err_desc = self._exc_info_to_string(err, test)
        sendmail(from_who, to, err_desc)

    def addFailure(self, test, err):
        self.super(MyTestResult, self).addFailure(test, err)
        err_desc = self._exc_info_to_string(err, test)
        sendmail(from_who, to, err_desc)

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromModule()
    results = MyTestResult()
    suite.run(results)

rawDescription: Python, run test, send email if it fails


code:
import os
from collections import defaultdict

def scores_to_dict(file_name):
    """Returns a defaultdict of name / list of scores as key / value"""
    if not os.path.isfile(file_name):
        return defaultdict(list)
    with open(file_name, 'r') as f:
        content = f.readlines()
    content = [line.strip('\n').split(', ') for line in content]
    temp_dict = {line[0]: line[1:] for line in content}
    d = defaultdict(list)
    d.update(temp_dict)
    return d

name = input("Name: ")
score = input("Score: ")

d = scores_to_dict('student_scores.txt')
d[name].append(score)

with open('student_scores.txt', 'w') as f:
    for k, v in d.items():
        f.write(', '.join([k] + v) + '\n')

rawDescription: appending to an existing line in a txt file

description: Appending to an existing line in a txt file


code:
lst = []
[lst.append(i) for i in range(5)]
lst

rawDescription: Is it possible to alter an external variable in a list comprehension?


code:
import pickle

filename = 'container.pkl'

class Container(object):
    def __init__(self, name):
        self.name = name
        self.widgets = []

class Widget(object):
    def __init__(self, name):
        self.name = name

c = Container('My Container')
w = Widget('My Widget')

c.widgets.append(w)

data = open(filename, 'wb')
pickle.dump(c, data)
data.close()

rawDescription: Why can't pickle a list that is an attribute of an object?


code: [rel.model for rel in MyModel._meta.get_all_related_objects()]

rawDescription: Get all models related to this model in django(via ForeignKey, ManyToMay)


code:
file_contents = '...'
p = Popen(['/bin/bash', '-c', "cat <(cat<<'EOF_CFG'\n%s\nEOF_CFG\n)" % file_contents])

rawDescription: Calling a shell script from python that requires a file without writing the file to disk


code:
import matplotlib.pyplot as plt
from fillplots import plot_regions

plotter = plot_regions([
    [(lambda x: 20.0/(1.0+x) - 1.0,),
    ],
])

plt.show()

description: Plot (1+x)(1+y)>=20


code:
class A(object):
    def method(self):
        return "foo"

try:
    import c_ext
    import types
    A.method = types.MethodType(c_ext.optimized_method, None, A)
except ImportError:
    pass

rawDescription: Dynamic use of a class method defined in a Cython extension module


code: is_holiday = now_date in holidays

rawDescription: Assigning a boolean value from an "if ... in" statement in Python


code:
data = {}
data['data'] = [{'Date': metric.date_created.strftime('%Y%m%d'), "Users": "1"}
                for metric in metrics]

rawDescription: How to add to a python dict in a loop, similar to PHP

description: Add to a python dict in a loop, similar to PHP


code:
# repeat the b vector for the amount of rows a has
x = np.repeat(b,a.shape[0])
# now reshape the a matrix to generate a vector
y = np.reshape(a.T,(1,np.product(a.shape) ))

# plot
import matplotlib.pyplot as plt
plt.scatter(x,y)
plt.show()

rawDescription: Matrix elements for scatter plot

description: Matrix elements for scatter plot


code:
import commands
command = "gconftool-2 --set /desktop/gnome/background/picture_filename --type string '/path/to/file.jpg'"
status, output = commands.getstatusoutput(command)  # status=0 if success

rawDescription: change desktop background

description: Change desktop background


rawDescription: How to properly open Port 8888 in Ubuntu under VirtualBox?

description: Properly open Port 8888 in Ubuntu under VirtualBox


caption: SublimeREPL

mnemonic: r

caption: Python

caption: Python

mnemonic: p

type: subprocess

cmd: c:/pythonXX/python.exe -i -u

external_id: python

rawDescription: How to configure python interpretor in sublime text 2 to make it function as IDLE python shell

description: Configure python interpretor in sublime text 2 to make it function as IDLE python shell


code:
#!/usr/bin/env python3
from io import BytesIO
import urllib.request
import tarfile

tarfile_url = "ftp://ftp.ncbi.nlm.nih.gov/pub/pmc/b0/ac/Breast_Cancer_Res_2001_Nov_9_3(1)_61-65.tar.gz"
ftpstream = urllib.request.urlopen(tarfile_url)

# BytesIO creates an in-memory temporary file.
# See the Python manual: http://docs.python.org/3/library/io.html
tmpfile = BytesIO()
while True:
    # Download a piece of the file from the connection
    s = ftpstream.read(16384)

    # Once the entire file has been downloaded, tarfile returns b''
    # (the empty bytes) which is a falsey value
    if not s:
        break

    # Otherwise, write the piece of the file to the temporary file.
    tmpfile.write(s)
ftpstream.close()

# Now that the FTP stream has been downloaded to the temporary file,
# we can ditch the FTP stream and have the tarfile module work with
# the temporary file.  Begin by seeking back to the beginning of the
# temporary file.
tmpfile.seek(0)

# Now tell the tarfile module that you're using a file object
# that supports seeking backward.
# r|gz forbids seeking backward; r:gz allows seeking backward
tfile = tarfile.open(fileobj=tmpfile, mode="r:gz")

# You want to limit it to the .nxml files
tfile_members2 = [filename
                  for filename in tfile.getnames()
                  if filename.endswith('.nxml')]

tfile_extract1 = tfile.extractfile(tfile_members2[0])
tfile_extract1_text = tfile_extract1.read()

# And when you're done extracting members:
tfile.close()
tmpfile.close()

rawDescription: Read Contents Tarfile into Python - "seeking backwards is not allowed"


code:
import pywinauto

app = pywinauto.application.Application().connect(title_re='Form1')
Form1 = app.Window_(title_re='Form1', class_name='WindowsForms10.Window.8.app.0.2bf8098_r13_ad1')
Form1.SetFocus()
Form1.TypeKeys("{PAUSE 2}")
Form1.TypeKeys("{TAB 2}{PAUSE 2}{ENTER}")

rawDescription: How to send SendKeys to Windows form in python script?

description: Send SendKeys to Windows form in python script


code:
if random()>0.5: # 50:50 probability
    ori = 45
    corrAns = 'left'
else:
    ori = -45
    corrAns = 'right'
# store the info we created in the data file
trials.addOtherData('corrAns', corrAns)
trials.addOtherData('ori', ori)

rawDescription: Defining a correct answer for a staircase in PsychoPy


code:
def crop(image):
    return image[200:,:]

rawDescription: Crop out the top of an image numpy (or scipy)


code:
the_class = Draw()

while looping:
    the_class.update()

rawDescription: Using more than one class

description: Using more than one class


code:
from itertools import combinations_with_replacement
dice = 3
faces = 4
list(combinations_with_replacement(range(1, faces+1), dice))

rawDescription: Seeking Elegant Python Dice Iteration

description: Seeking Elegant Python Dice Iteration


code:
YourModel.objects.extra(
    select={'total': 'a * b * c'},
    order_by=['total'],
)

rawDescription: Ordering by multiplication of several values in Django ORM?


code:
class WorldForm(forms.ModelForm):
        class Meta:
                model = World
                fields = ('name',)

        def save(self, commit=True):
            super(WorldForm, self).save(commit=False)
            is_new = not self.instance.pk
            self.instance.save()

            if is_new:
                # It's a new world. Fill it with countries!
                self.instance.country.add(*Country.objects.all())
            else:
                self._save_m2m()

            return self.instance

rawDescription: Django Form - checking every object without showing them


rawDescription: Need help regarding Binary Powering with a matrix


code:
import time
import tkinter
from tkinter import ttk
import threading

#gui
root = tkinter.Tk()
root.title("Threading demo")

status = tkinter.StringVar()
elapsed = tkinter.StringVar()
error = tkinter.StringVar()

#thread
class timer(threading.Thread):
    def __init__(self):
        super().__init__()
        self.stopped = False
        #your code here, don't need init if you have no code

    def run(self):
        status.set('running')

        while not self.isStopped():
            time.sleep(1)

            try:
                oldtime = int(elapsed.get())
            except ValueError:
                oldtime = 0

            elapsed.set(oldtime+1)

        status.set('stopped')
        time.sleep(2)

    def isStopped(self):
        return self.stopped

    def stop(self):
        self.stopped = True

#starts/stops thread (manages it)
class threadedOp(object):
    def __init__(self):
        self.thread = None

    def run(self):
        if self.thread == None:
            self.thread = timer()
            status.set('starting')
            self.thread.start()
        else:
            error.set('Thread already running')

    def stop(self):
        if self.thread != None:
            status.set('stopping')
            self.thread.stop()
            self.thread.join()
            error.set('Join complete')
            self.thread = None
        else:
            error.set('No thread to stop')

op = threadedOp()

#remaining gui
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(tkinter.N, tkinter.W, tkinter.E, tkinter.S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

ttk.Label(mainframe, textvariable=elapsed).grid(column=1, row=1, sticky=(tkinter.W, tkinter.E))
ttk.Label(mainframe, textvariable=status).grid(column=2, row=1, sticky=(tkinter.W, tkinter.E))
ttk.Label(mainframe, textvariable=error).grid(column=1, row=3, sticky=(tkinter.W, tkinter.E))
ttk.Button(mainframe, text="Start", command=op.run).grid(column=1, row=2, sticky=tkinter.W)
ttk.Button(mainframe, text="Stop", command=op.stop).grid(column=2, row=2, sticky=tkinter.W)

root.mainloop()

rawDescription: Python TKinter Threading Help Required

description: Python TKinter Threading Help Required


code:
@app.route("/", subdomain="static")
def static_index():
    """Flask supports static subdomains
    This is available at static.your-domain.tld"""
    return "static.your-domain.tld"

@app.route("/dynamic", subdomain="<username>")
def username_index(username):
    """Dynamic subdomains are also supported
    Try going to user1.your-domain.tld/dynamic"""
    return username + ".your-domain.tld"

rawDescription: Dynamic Subdomain Handling in a Web App (Flask)


code:
from django.db.models import Sum
from django.utils.functional import cached_property

class Order(model.Model):
    ...
    @cached_property       # or @property
    def total(self):
         return self.orderitem_set.aggregate(total_sum=Sum('total'))['total_sum']

    # do the same with tax

rawDescription: Django maximum recursion depth exceeded decimal


code:
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = 'nl'

rawDescription: How to localize reStructuredText and Sphinx messages?

description: Localize reStructuredText and Sphinx messages


code: [lst[1] for lst in data]

rawDescription: Properly slicing a list of lists

description: Properly slicing a list of lists


code:
class Scanner(object):
    ...
    def run(self, targets="" ,options="-Pn"):
        #start a new nmap scan on localhost with some specific options

        syslog.syslog("Scan started")
        parsed = None
        nmproc = NmapProcess(targets,options)

        nmproc.run_background()
        while nmproc.is_running():
            print("Nmap Scan running: ETC: {0} DONE: {1}%".format(nmproc.etc,
                                                                  nmproc.progress))
            sleep(2)

        print("rc: {0} output: {1}".format(nmproc.rc, nmproc.summary))

rawDescription: How to pass the content of list one element at a time to a method?

description: Pass the content of list one element at a time to a method


code:
import weakref
class Node():
    parent = None
    child = None
    @property
    def parent(self):
        parent = self._parent()
        if parent is not None:
            return parent
        raise ValueError("parent has been deleted")
    @parent.setter     # python 2.6+
    def parent(self, parent):
        self._parent = weakref.ref(parent)

rawDescription: How to prune subtree in python

description: Prune subtree in python


code:
class SODIOrder(models.Model):
    sodi_order_num = models.CharField(max_length=50)
    sodi_order_version = models.CharField(max_length=50)
    service_identifier = models.CharField(max_length=50)
    telephone_number = models.CharField(max_length=12)
    insert_timestamp = DateTimeUTCField(auto_now_add=True)

    class Meta:
        unique_together = (("sodi_order_num","sodi_order_version"),)

rawDescription: Django model having two primary keys

description: Django model having two primary keys


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

#set value for testing
actual_nn = np.random.randn(100)
random_nn = np.random.randn(100)
poisson_nn = np.random.randn(100)

f, axarr = plt.subplots(3, sharex=True, sharey=True)
f.suptitle("Nearest Neighbor", fontsize=14)

axarr[0].hist(actual_nn, range = (-3,3)); # range parameter set the start and the end of the bin
axarr[0].set_title('Actual')
axarr[1].hist(random_nn, range = (-3,3));
axarr[1].set_title('Random')
axarr[2].hist(poisson_nn, range = (-3,3));
axarr[2].set_title('Poisson')

rawDescription: Setting Histogram Bar Widths in Subplots as Equal


code:
import wx
import wx.lib.platebtn as platebtn

class GradientFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, -1, title)
        self.panel = wx.Panel(self)
        self.panel.Bind(wx.EVT_PAINT, self.OnPaint)
        self.panel.Bind(wx.EVT_ERASE_BACKGROUND, lambda event: None)
        self.panel.Bind(wx.EVT_SIZE, self.OnSize)

        # add plate buttons
        top_sizer = wx.BoxSizer(wx.VERTICAL)
        btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
        labels = ["Morceaux", "Albums", "Artistes", "Genres"]
        style = platebtn.PB_STYLE_GRADIENT
        for label in labels:
            btn = platebtn.PlateButton(self.panel, label=label, style=style)
            btn.SetPressColor(wx.Colour(208,208,208))
            btn_sizer.Add(btn, 0, wx.RIGHT|wx.LEFT|wx.CENTER, 5)

        top_sizer.Add(btn_sizer, 0, wx.ALL|wx.CENTER, 5)
        top_sizer.Add((1,1), 1, wx.EXPAND)
        self.panel.SetSizer(top_sizer)

        self.Center()
        self.Show()

    def OnSize(self, event):
        event.Skip()
        self.Refresh()

    def OnPaint(self, event):
        dc = wx.BufferedPaintDC(self.panel)
        rect = self.panel.GetClientRect()
        dc.SetBackground(wx.Brush("white"))
        dc.Clear()
        rect.SetHeight(30)
        dc.GradientFillLinear(rect, '#fbfbfb', '#efefef', wx.SOUTH)
        rect.SetTop(30)
        rect.SetHeight(2)
        dc.GradientFillLinear(rect, '#dbdbdb', '#c1c1c1', wx.SOUTH)

app = wx.App(0)
frame = GradientFrame(None, 'Test')
app.MainLoop()

rawDescription: Buttons on a gradient bar to access different panels


code:
from numpy import genfromtxt
my_data = genfromtxt('my_file.csv', delimiter=',')

rawDescription: CSV to image in python

description: CSV to image in python


code:
import maya.cmds as cmds
import maya.utils as utils
import threading

def do_in_main():
    utils.executeDeferred (cmds.sphere)

for i in range(10):
    t  = threading.Thread(target=do_in_main, args=())
    t.start()

rawDescription: How to use python (maya) multithreading

description: Use python (maya) multithreading


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

x = np.arange(100)
y = np.arange(100)
# Colors whether or not x+y is a multiple of 5
c = (x + y)%5 == 0

# Use 'jet' colormap for red/blue.
plt.scatter(x, y, c=c, cmap='jet')

rawDescription: Custom color mapping based on function in matplotlib


code:
rawdata = pickle.dumps(self.data)
cmd = [self.openssl, cipher, "-a", "-salt", "-k", passphrase or "''"]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
encdata, stderr = proc.communicate(input=rawdata)

rawDescription: Trouble working with openssl within Python


code: event.connect(func, lambda i=i: self.do_something(i))

rawDescription: Proper way to define function based on loop index?


code:
from PyQt4 import QtGui, QtCore

class Ventana(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.setLayout(QtGui.QVBoxLayout())
        self.lineEdit = QtGui.QLineEdit(self)
        self.button = QtGui.QPushButton('clickme', self)
        self.layout().addWidget(self.lineEdit)
        self.layout().addWidget(self.button)
        self.button.clicked.connect(self.testSleep)

    def testSleep(self):
        self.lineEdit.setText('Start')
        QtCore.QTimer.singleShot(2000, lambda: self.lineEdit.setText('End'))

    def mainLoop(self, app ):
        sys.exit( app.exec_())

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = Ventana()
    window.show()
    sys.exit(app.exec_())

rawDescription: Sleep is not working on pyqt4

description: Sleep is not working on pyqt4


code: s.split(None, 1)[-1]

rawDescription: best way to do this string conversion in Python

description: Do this string conversion in Python


code: producersPool.submit(lambda i: print(i), (i,))

rawDescription: Why does Python's GIL enforce strict ordering of processing?


code:
def product(xs):
    return reduce(operator.mul, xs, 1)

rawDescription: What is the 'pythonic' equivalent to the 'fold' function from functional programming?


code:
def lcm(numbers):
    return map(__lcm, combinations( numbers, 2 ) )

rawDescription: Lowest common multiple for all pairs in a list


code:
#!/usr/bin/env python3

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

n = 2**3

def drawInitial():
    plt.axes(xlim = (0, n), ylim = (0, n))
    plt.axis('off')

    for line in range(n):
        for col in range(n):
            rect = mpatches.Rectangle(
                (col, line), 1, 1,
                facecolor = "white",
                edgecolor = "black"
            )

            plt.gca().add_patch(rect)

def onclick(event):
    col  = int(event.xdata)
    line = int(event.ydata)

    rect = mpatches.Rectangle(
        (col, line), 1, 1,
        facecolor = "black",
        edgecolor = "black"
    )

    plt.gca().add_patch(rect)
    plt.draw()

def onkey(event):
    if event.key == " ":
        drawInitial()
        plt.draw()

fig = plt.figure()
fig.canvas.mpl_connect('button_press_event', onclick)
fig.canvas.mpl_connect('key_press_event', onkey)

drawInitial()

plt.show()

rawDescription: Interacting with matplotlib

description: Interacting with matplotlib


code:
from pandas.io import data as web
s = web.get_data_yahoo('AAPL', start='2009-01-02',
                            end='2009-12-31')['Adj Close']
monthly = s.resample('BM', how=lambda x: x[-1])
monthly
monthly.pct_change()

rawDescription: How to get DataFrame.pct_change to calculate monthly change on daily price data?

description: Get DataFrame.pct_change to calculate monthly change on daily price data


code:
var = self.model.objects.get(site_id__exact=current_site.id)
context[self.varname] = var.__dict__[self.field]#this will get the field's value dynamically, which is what I was looking for

rawDescription: Django: How to get field value dynamically using custom template tags?


rawDescription: How to move down to a parent directory in Python?

description: Move down to a parent directory in Python


code:
from scrapy.spider import BaseSpider

class DmozSpider(BaseSpider):
    name = "dmoz"
    allowed_domains = ["dmoz.org"]
    start_urls = [
        "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
        "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
    ]

    def parse(self, response):
        filename = response.url.split("/")[-2]
        open(filename, 'wb').write(response.body)

rawDescription: scrapy: preventing crawlspider from crawling linked in/facebook websites

description: Scrapy: preventing crawlspider from crawling linked in/facebook websites


code:
import Queue, threading
def gen_multiplex(genlist):
    item_q = Queue.Queue()
    def run_one(source):
        for item in source: item_q.put(item)

    def run_all():
        thrlist = []
        for source in genlist:
            t = threading.Thread(target=run_one,args=(source,))
            t.start()
            thrlist.append(t)
        for t in thrlist: t.join()
        item_q.put(StopIteration)

    threading.Thread(target=run_all).start()
    while True:
        item = item_q.get()
        if item is StopIteration: return
        yield item

rawDescription: How to multiplex multiple blocking Python generators into one?

description: Multiplex multiple blocking Python generators into one


code: pd.date_range(start, end, freq='90D')

rawDescription: Editing date list

description: Editing date list


code:
import re
test = "Hello -%there%-"
regularExpr = "-%.*%-"
s1 = re.sub(regularExpr, "Mel", test)
# Result: Hello Mel
s2 = re.sub("foo", "Mel", test)
# Result: Hello -%there%-

rawDescription: What is the Python equivalent of (Mel) Substitute, Maya


code:
mappable = plt.cm.ScalarMappable(cmap='gray')
# the mappable usually contains an array of data, here we can
# use that to set the limits
mappable.set_array([0,1])
ax.colorbar(mappable)

rawDescription: Create a grayscale colorbar for each subplot in python


code:
from PIL import Image

im = Image.fromarray(np.uint8(img))
im.save('outfile.png', "PNG")

rawDescription: matplotlib.pyplot: remove white space and keep same size while saving the image

description: Matplotlib.pyplot: remove white space and keep same size while saving the image


code: graph = pydot.Dot(graph_type='digraph')

rawDescription: How to use lines with arrow in pydot

description: Use lines with arrow in pydot


code: r = await aiohttp.post('http://httpbin.org/post', data=b'data')

rawDescription: TypeError('not a valid non-string sequence or mapping object',)


code:
class Baseclass(object):
    @classmethod
    def extend(cls, key):
        if not 'extra_fields' in cls.__dict__:
            cls.extra_fields=[]
        cls.extra_fields.append(key)

class A(Baseclass):
    pass

class B(Baseclass):
    pass

A.extend("foo")

rawDescription: Set attribute of subclass in method of super class


code:
import ScrolledText
self.textfield = ScrolledText.ScrolledText(self, wrap=Tkinter.WORD)

rawDescription: Tkinter Large Entry Box

description: Tkinter Large Entry Box


code:
import wx
import wx.lib.scrolledpanel
from controls import SimpleGrid
from controls import ListCtrlComboPopup

class GraphFrame(wx.Frame):
    title = 'Demo: Data Trending Tool'

    def __init__(self):
        self.selection = []
        self.displaySize = wx.DisplaySize()
        wx.Frame.__init__(self, None, -1, self.title,
                 style = wx.DEFAULT_FRAME_STYLE,
                 size = (self.displaySize[0]/2, self.displaySize[1]/2))
        self.containingpanel = wx.Panel(self, -1)
        self.toppanel = wx.Panel(self, -1)
        self.splittedwin = wx.SplitterWindow(self.containingpanel, wx.ID_ANY, style=wx.SP_3D | wx.SP_BORDER)
        self.splittedwin.SetMinimumPaneSize(20)
        self.gridpanel = wx.lib.scrolledpanel.ScrolledPanel(self.splittedwin,-1, style = wx.SUNKEN_BORDER)
        self.panel = wx.lib.scrolledpanel.ScrolledPanel(self.splittedwin,-1, style = wx.SUNKEN_BORDER)

        #### GRID
        self.grid = SimpleGrid(self.gridpanel)
        self.gridpanelsizer= wx.BoxSizer(wx.HORIZONTAL)
        self.gridpanelsizer.Add(self.grid, wx.GROW)
        self.gridpanel.SetSizer(self.gridpanelsizer)
        self.gridpanelsizer.Fit(self)
        #### COMBOBOX
        self.cc = wx.combo.ComboCtrl(self.toppanel, style=wx.CB_READONLY, size=(200,-1), )
        self.cc.SetPopupMaxHeight(140)
        popup = ListCtrlComboPopup(self)
        self.cc.SetPopupControl(popup)
        self.cc.SetText("--select--")
        # Add some items to the listctrl
        for i in range(10):
            popup.AddItem(str(i))

        #### SIZER FOR COMBOBOX
        self.cbpanelsizer= wx.BoxSizer(wx.HORIZONTAL)
        self.cbpanelsizer.Add(self.cc, border = 5,flag = wx.LEFT)
        self.toppanel.SetSizer(self.cbpanelsizer)

        self.splittedwin.SplitHorizontally(self.gridpanel,self.panel,100)

        ##### SIZER FOR CONTAININGPANEL
        self.cpsizer = wx.BoxSizer(wx.VERTICAL)
        self.cpsizer.Add(self.splittedwin, 1, wx.EXPAND, 0)
        self.containingpanel.SetSizer(self.cpsizer)
        self.cpsizer.Fit(self.containingpanel)

        mainsizer = wx.BoxSizer(wx.VERTICAL)
        mainsizer.Add(self.toppanel, 0, wx.EXPAND)
        mainsizer.Add(self.containingpanel, 1, wx.EXPAND)
        self.SetSizerAndFit(mainsizer)

        self.panel.SetAutoLayout(1)
        self.panel.SetupScrolling()
        self.gridpanel.SetAutoLayout(1)
        self.gridpanel.SetupScrolling()
        self.draw_plot()

    def draw_plot(self):
        for i in range(10):
          if i in self.selection:
             self.grid.ShowRow(i)
          else:
             self.grid.HideRow(i)
        #self.Layout()
        self.gridpanelsizer.Layout()

if __name__ == "__main__":

  app = wx.PySimpleApp()
  app.frame = GraphFrame()
  app.frame.Show()

  app.MainLoop()

rawDescription: wxpython: adding rows to wxgrid dynamically does not fit to panel

description: Wxpython: adding rows to wxgrid dynamically does not fit to panel


code:
def threshold(a, x):
    return sorted(item for item in a if item >= x)

threshold([1,3,2,5,4], 3)

rawDescription: Return array values that are greater than x


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

# byte packing function
def Pack4bytes(c1,c2,c3,c4) :
    result = c1 << 24 | c2 << 16 | c3 << 8 | c4
    return result

#Initialise display and empty array
width = 200
height = 100
pygame.init()
DISP = pygame.display.set_mode((width, height))
Sample = numpy.zeros((width, height), dtype = numpy.uint32)
Output = numpy.zeros_like(Sample)

#Initialise color channels
A = numpy.zeros_like(Sample)
R = numpy.zeros_like(Sample)
G = numpy.zeros_like(Sample)
B = numpy.zeros_like(Sample)

def Render() :
    # for example, fill the channels with some data
    # note the index order - pygame treats array as transposed matrix
    # first index refers to X , second - to Y coordinate
    R[:, 20:30] = 127
    G[:, 40:50] = 127
    B[:, 60:70] = 127

    # Now pack data and blit
    # Note byte order - in pygame it is exactly as follows - ARGB
    Output = Pack4bytes(A,R,G,B)
    # blit Output to display, this one is for output same size as display
    pygame.surfarray.blit_array(DISP, Output)

MyLoop = True
FPS = 8
clock = pygame.time.Clock( )
Render()
# empty loop, just does nothing
while MyLoop:
    clock.tick(FPS)
    for event in pygame.event.get( ):
        if event.type == QUIT: MyLoop = False
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE: MyLoop = False
    pygame.display.update( )
pygame.quit( )

rawDescription: How to display a color map as pygame surface generated from an array in real-time?

description: Display a color map as pygame surface generated from an array in real-time


rawDescription: Python how to join cross platform paths

description: Python how to join cross platform paths


code:
@app.route('/product/<unique_form>',  methods=['GET', 'POST'])
def product(unique_form):
    form = ProductForm(unique_form, **product_data)

class ProductForm(Form):
   def __init__(self, unique_form, *args, **kwargs):
       # well, now you have unique_form here
       Form.__init__(self, *args, **kwargs)

rawDescription: Pass variable from view to form

description: Pass variable from view to form


code:
x = []
with open('my_file.txt', 'r') as f:
    temp_list = []
    for line in f:
        if line.strip(): #line is not blank
            temp_list.append(line)
        else: #line is blank, i.e., it contains only newlines and/or whitespace
            if temp_list: #check if temp_list contains any items
                x.append(temp_list)
            temp_list = []

rawDescription: Python: read text file into array - unequal row distrubution


code:
import subprocess

proc=subprocess.Popen('less', stdin=subprocess.PIPE)
lines=(str(i) for i in range(1000))
proc.stdin.write('\n'.join(lines))
proc.stdin.close()
proc.communicate()

rawDescription: How can I display output in a pager after a git command?

description: Display output in a pager after a git command


code:
for i in range(len(xPts)):
  mad.up()
  mad.goto(xPts[i], yPts[i])
  mad.down()
  mad.dot()

rawDescription: Python Turtle Plot Regression

description: Python Turtle Plot Regression


code: string = ET.tostring(tree.getroot())

rawDescription: Parse an elementTree to return a string in XML form - Python


code:
period = '-P14D'
regex  = re.compile('(?P<sign>-?)P(?:(?P<years>\d+)Y)?(?:(?P<months>\d+)M)?(?:(?P<days>\d+)D)?(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?')

# Fetch the match groups with default value of 0 (not None)
duration = regex.match(period).groupdict(0)

# Create the timedelta object from extracted groups
delta = timedelta(days=int(duration['days']) + (int(duration['months']) * 30) + (int(duration['years']) * 365),
                  hours=int(duration['hours']),
                  minutes=int(duration['minutes']),
                  seconds=int(duration['seconds']))

if duration['sign'] == "-":
    delta *= -1

rawDescription: Parsing an xs:duration datatype into a Python datetime.timedelta object?


code:
#!/usr/bin/python

#scraper

import mechanize
import cookielib
from BeautifulSoup import BeautifulSoup
import html2text

# Browser
br = mechanize.Browser()

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

br.addheaders = [('User-agent', 'Chrome')]

# The site we will navigate into, handling it's session
br.open('url1')

# View available forms
for f in br.forms():
    if f.attrs['id'] == 'fm1':
        br.form = f
        break

# User credentials
br.form['username'] = 'password'
br.form['password'] = 'username'

# Login
br.submit()

#Now we need to confirm again

br.open('https://url2')

# Select the first (index zero) form
br.select_form(nr=0)

# Login
br.submit()

print(br.open('https:url2').read())

rawDescription: How to use mechanize to enter username and password

description: Use mechanize to enter username and password


code:
import X
reload( X )
from X import Y # or * for that matter

rawDescription: How to reload python module imported using "from module import *"

description: Reload python module imported using "from module import *"


code:
df
new = pd.DataFrame({'dt': pd.date_range(df.start_date.min(), df.end_date.max())})
new
new = new.merge(df, how='left', left_on='dt', right_on='start_date').fillna(method='pad')
new
new.ix[(new.dt < new.start_date) | (new.dt > new.end_date), 'value'] = 0
new[['dt', 'value']]

rawDescription: Convert Date Ranges to Time Series in Pandas


code:
interger = input("Please enter an interger: ")
print(int(interger)**2)

rawDescription: Create a program that asks users for input (integer) and outputs the input(integer) squared


code:
def create_multiplier(x):
    def inner_function(y):
        return x*y
    return inner_function

rawDescription: Python Passing values to a return statement function


code:
class MyParser(object):
    def __init__(self, value):
        self.lst = value.split('|')
    def id(self):
        return self.lst[0]
    def level(self):
        return self.lst[2].strip()
    def message(self):
        return self.lst[1].strip(' "')

rawDescription: Better way to do string filtering/manipulation


rawDescription: How do I run doctests with PyCharm?

description: Run doctests with PyCharm


code:
"This is a string with the value of " + str(variable) + " shown."

"This is a string with the value of %s shown." % (str(variable))

"This is a string with the value of {0} shown.".format(variable)

rawDescription: Output variable value in a string

description: Output variable value in a string


code:
import sys
from functools import partial
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Form1(QWidget):
    showForm2Signal = pyqtSignal()

    def __init__(self, parent=None):
        super(Form1, self).__init__(parent)
        self.newGameButton = QPushButton("New Game", self)
        self.quitButton = QPushButton("Quit", self)
        layout = QVBoxLayout(self)
        layout.addWidget(QLabel("My Game
Start Page"))
        layout.addWidget(self.newGameButton)
        layout.addWidget(self.quitButton)
        self.newGameButton.clicked.connect(self.showForm2Signal.emit)
        self.quitButton.clicked.connect(qApp.quit)

class Form2(QWidget):
    showForm1Signal = pyqtSignal()

    def __init__(self, parent=None):
        super(Form2, self).__init__(parent)
        self.backButton = QPushButton("Back", self)
        layout = QVBoxLayout(self)
        layout.addWidget(QLabel("New Game Started!"))
        layout.addWidget(self.backButton)
        self.backButton.clicked.connect(self.showForm1Signal.emit)

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super(MainWidget, self).__init__(parent)
        self.stack = QStackedWidget()
        layout = QVBoxLayout(self)
        layout.addWidget(self.stack)
        self.form1 = Form1(self)
        self.form2 = Form2(self)
        self.stack.addWidget(self.form1)
        self.stack.addWidget(self.form2)
        self.form1.showForm2Signal.connect(partial(self.stack.setCurrentWidget,
                                               self.form2))
        self.form2.showForm1Signal.connect(partial(self.stack.setCurrentWidget,
                                               self.form1))
        self.stack.setCurrentWidget(self.form1)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWidget()
    w.show()
    app.exec_()
    sys.exit()

rawDescription: PyQt widgets in multiple files

description: PyQt widgets in multiple files


code:
if(is_number(n) == True):
    edges_w = str(edges).replace("'","")
else:
    edges_w = str(edges).replace("'",'"')

rawDescription: How to replace a single quote to double quote in Python csv writer?

description: Replace a single quote to double quote in Python csv writer


code:
import Tkinter
import ttk

window = Tkinter.Tk()
notebook = ttk.Notebook(window)
notebook.pack()
subframe = Tkinter.Frame(window)
subframe.pack()
notebook.add(subframe, text="tab", state="normal")
def buttonaction():
    notebook.tab(0, state="disabled")
button = Tkinter.Button(subframe, command=buttonaction, text="click to disable tab")
button.pack()

if __name__ == "__main__":
    window.mainloop()

rawDescription: how to enable & disable tabs in a Tkinter/Tix Python GUI

description: Enable & disable tabs in a Tkinter/Tix Python GUI


code: result.cal = CALORIES[name]

rawDescription: read the dictionary value from array

description: Read the dictionary value from array


code:
@app.route("/hello<path:path>.py")
def hello(path):
    return "Hello World!"

rawDescription: How to get name of a required page in flask?

description: Get name of a required page in flask


code:
from myapp.models import MyModel
my_instance = MyModel.objects.get(id=whatever)
my_instance.first_name = 'foo'
my_instance.last_name = 'bar'
my_instance.save()

rawDescription: set first_name and second_name in python shell - django

description: Set first_name and second_name in python shell - django


code:
d={}
for i,j in zip(students,courses):
  d.setdefault(i,[]).append(j)

d

rawDescription: Python: Merge two lists to dictionary

description: Python: Merge two lists to dictionary


code:
#BPL Stats
UserSearch = raw_input("What player would you like to search for?")

Players = []
Goals = []
counter = 0

def StatProcessing(PlayerFileName,PlayerFileLabel,PlayerTeamAttributeLabel,GoalFileName,GoalFileLabel,GoalTeamAttributeLabel):
    global Players
    global Goals

    PlayerFileLabel = open(PlayerFileName,mode = 'r')
    properListPlayer = PlayerFileLabel.read().split()
    for line in properListPlayer:
        Players.append(line)

    GoalFileLabel = open(GoalFileName,mode = 'r')
    properListGoal = GoalFileLabel.read().split()
    for line in properListGoal:
        Goals.append(line)

StatProcessing('ChelseaPlayers.txt','ChelseaNamesFile','ChelseaName','ChelseaGoals.txt','ChelseaGoalsFile','ChelseaGoals')
StatProcessing('ManCityPlayers.txt','ManCityNamesFile','ManCityName','ManCityGoals.txt','ManCityGoalsFile','ManCityGoals')

while (counter != 10) or (UserSearch != Players[counter]):

    if UserSearch == Players[counter]:
        if counter <= 4:
            print (UserSearch,"who plays for Chelsea has scored:", Goals[counter], " goals this season")
        if (counter > 4) and (counter <= 9):
             print (UserSearch,"who plays for Manchester City has scored:", Goals[counter], " goals this season")
        break
    else:
        counter += 1

        if counter > 9:
            print ('The player you searched for is not in the list. Sorry!')
            break

rawDescription: What is wrong specifically with MY code in Python?


code:
def translate(self):
    new_string=self.string_representation.replace("T","U")
    rna1 = RNA(new_string)
    return rna1

rawDescription: Defining a function with string.replace within a class


code:
df.groupby(level=0).cumcount()
df['subindex'] = df.groupby(level=0).cumcount()  # possibly + 1 here.
df.set_index('subindex', append=True)

rawDescription: Pandas: How to create subindex efficiently?


rawDescription: manipulating two 2D lists - python 2.7

description: Manipulating two 2D lists - python 2.7


code:
def rep(f, n):
    return f if n == 1 else lambda x: f(rep(f, n-1)(x))

rawDescription: Python: A better way to write n compositions of a function?


code:
SomeModel2.objects.annotate(new_field=Count('SomeField2',
    distinct=True)).filter(condition=condition,
    another_condition=condition2).values('new_field', 'Somefield1')

rawDescription: Select within select using Django ORM

description: Select within select using Django ORM


code:
for obj_type,dest in self.what_to_build.items():
    self.typeBuild(obj_type, dest)

rawDescription: How to map a function to each dictionary element?

description: Map a function to each dictionary element


code: connect(checkbox, SIGNAL(stateChanged(int)), button, SLOT(buttonStateChanged(int)));

rawDescription: How to disable button until check box is checked in pyqt?

description: Disable button until check box is checked in pyqt


code:
g = git.Git('my/repo')
g.execute(["git","add","conflicted_file.txt"])
g.execute(["git","commit","-m", "Conflict resolved"])

rawDescription: How do I programmatically simulate resolving a merge conflict with GitPython?

description: Programmatically simulate resolving a merge conflict with GitPython


code:
import re

utf8_detector = re.compile(r"""^(?:
     [\x09\x0A\x0D\x20-\x7E]            # ASCII
   | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
   |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
   | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
   |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
   |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
   | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
   |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
  )*$""", re.X)

rawDescription: Best way to decode unknown unicoding encoding in Python 2.5

description: Decode unknown unicoding encoding in Python 2.5


code:
import StringIO

output = StringIO.StringIO()

rawDescription: PrettyPrint python into a string, and not stdout


code:
seen = set()
res = []
for line in textlines:
    if line not in seen:
        res.append(line)
        if not line.strip():
            seen.add(line)
textlines = res

rawDescription: Remove multiple occurrence except for particular values?


code:
from flask import Flask, render_template_string
from wtforms import Form
from wtforms.fields.html5 import DecimalRangeField

app = Flask(__name__)
app.config['DEBUG'] = True

TPL = '''
<!DOCTYPE html>
<html>
<head>
<script>
function outputUpdate(age) {
    document.querySelector('#selected-age').value = age;
}
</script>
</head>
<body>
<form>
    <p>
       {{ form.age.label }}:
       {{ form.age(min=0, max=100, oninput="outputUpdate(value)") }}
       <output for="age" id="selected-age">{{ form.age.data }}</output>
    </p>
</form>
</body>
</html>
'''

class TestForm(Form):
    age = DecimalRangeField('Age', default=0)

@app.route("/")
def home():
    form = TestForm(csrf_enabled=False)
    return render_template_string(TPL, form=form)

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

rawDescription: Displaying slider value alongside wtforms.fields.html5.DecimalRangeField


code:
class Pizza(object):
    '''Create a pizza'''

    def __init__(self):
        self.farina=0
        self.acqua=0
        self.lievito=0
        self.sale=0
        self.olio=0
        self.semola=0
        self.strutto=0
        self.manitoba=0

        self.set_default_ingredients()
    # end Constructor

    @classmethod
    def default_ingredients(cls):
        '''Return the default ingredients for a pizza.'''
        return {'farina':0, 'acqua':0, 'lievito':0, 'sale':0}

    def set_default_ingredients(self):
        '''Set the default ingredients.'''
        self.farina=0
        self.acqua=0
        self.lievito=0
        self.sale=0
        self.olio=0
        self.semola=0
        self.strutto=0
        self.manitoba=0
    # end set_default_ingredients

    def bake(self):
        '''Bake the pizza.'''
        pass # Do something to bake the pizza.
    # end class Pizza

class Romana(Pizza):
    '''Create a special Romana Pizza.'''

    @classmethod
    def default_ingredients(cls):
        '''Return the default ingredients for a Romana Pizza.'''
        return {'farina':80, 'semola':20, 'acqua':57, 'lievito':0.171, 'sale':2.85, 'olio':2.85}

    def set_default_ingredients(self):
        '''Set the default ingredients for a Romana Pizza.'''
        self.farina=80
        self.semola=20
        self.acqua=57
        self.lievito=0.171
        self.sale=2.85
        self.olio=2.85

class Napoletana(Pizza):
    '''Create a special Napoletana Pizza.'''

    @classmethod
    def default_ingredients(cls):
        '''Return the default ingredients for a Romana Pizza.'''
        return {'farina':72, 'manitoba':48, 'acqua':72, 'lievito':0.216, 'sale':3.6, 'strutto':7.2}

    def set_default_ingredients(self):
        '''Set the default ingredients for a Romana Pizza.'''
        self.farina=72
        self.manitoba=48
        self.acqua=72
        self.lievito=0.216
        self.sale=3.6
        self.strutto=7.2

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super().__init__()

        self.main_widg = QtGui.QWidget()
        self.main_layout = QtGui.QFormLayout()
        self.main_widg.setLayout(self.main_layout)
        self.setCentralWidget(self.main_widg)

        self.current_pizza = Pizza()

        self.pizza_type = QtGui.QComboBox()
        self.pizza_type.addItems(['Pizza', 'Romana', 'Napoletana'])
        self.pizza_type.currentIndexChanged.connect(self.select_pizza)

        # Ingredients
        self.farina = QtGui.QLineEdit('0')
        self.farina.textChanged.connect(self.set_farina)
        self.acqua = QtGui.QLineEdit('0')
        self.acqua.textChanged.connect(self.set_acqua)
        self.lievito = QtGui.QLineEdit('0')
        self.lievito.textChanged.connect(self.set_lievito)
        self.sale = QtGui.QLineEdit('0')
        self.sale.textChanged.connect(self.set_sale)
        self.olio = QtGui.QLineEdit('0')
        self.olio.textChanged.connect(self.set_olio)
        self.semola = QtGui.QLineEdit('0')
        self.semola.textChanged.connect(self.set_semola)
        self.strutto = QtGui.QLineEdit('0')
        self.strutto.textChanged.connect(self.set_strutto)
        self.manitoba = QtGui.QLineEdit('0')
        self.manitoba.textChanged.connect(self.set_manitoba)

        # Actions
        self.bake_btn = QtGui.QPushButton("Bake")
        self.bake_btn.clicked.connect(self.bake)

        # Layout
        self.main_layout.addRow('Pizza Type', self.pizza_type)
        self.main_layout.addRow('farina', self.farina)
        self.main_layout.addRow('acqua', self.acqua)
        self.main_layout.addRow('lievito', self.lievito)
        self.main_layout.addRow('olio', self.olio)
        self.main_layout.addRow('semola', self.semola)
        self.main_layout.addRow('strutto', self.strutto)
        self.main_layout.addRow('manitoba', self.manitoba)
        self.main_layout.addRow(self.bake_btn)
    # end __init__

    def select_pizza(self, idx):
        if self.pizza_type.currentText() == 'Pizza':
            self.current_pizza = Pizza()
        elif self.pizza_type.currentText() == 'Romana':
            self.current_pizza = Romana()
        else:
            self.current_pizza = Napoletana()
        self.set_values()
    # end select_pizza

    def set_values(self):
        '''Set the values from the current pizza.'''
        self.farina.setText(str(self.current_pizza.farina))
        self.acqua.setText(str(self.current_pizza.acqua))
        self.lievito.setText(str(self.current_pizza.lievito))
        self.sale.setText(str(self.current_pizza.sale))
        self.olio.setText(str(self.current_pizza.olio))
        self.semola.setText(str(self.current_pizza.semola))
        self.strutto.setText(str(self.current_pizza.strutto))
        self.manitoba.setText(str(self.current_pizza.manitoba))

    def set_farina(self, val):
        self.current_pizza.farina = val
    def set_acqua(self, val):
        self.current_pizza.acqua = val
    def set_lievito(self, val):
        self.current_pizza.lievito = val
    def set_sale(self, val):
        self.current_pizza.sale = val
    def set_olio(self, val):
        self.current_pizza.olio = val
    def set_semola(self, val):
        self.current_pizza.semola = val
    def set_strutto(self, val):
        self.current_pizza.strutto = val
    def set_manitoba(self, val):
        self.current_pizza.manitoba = val

    def bake(self):
        self.current_pizza.bake()
# end class MainWindow

if __name__ == "__main__":
    import sys
    QtGui.QApplication([])

    window = MainWindow()
    window.show()

    sys.exit(QtGui.qApp.exec_())

rawDescription: Python Qt4 classes & QTGui Windows

description: Python Qt4 classes & QTGui Windows


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

x = np.linspace(0, 20, 500)
y = np.cos(3*x) - 2*np.cos(5*x) + 0.5*np.cos(6*x)

a = 5
b = 15

plt.axvspan(a, b, color='y', alpha=0.5, lw=0)
plt.plot(x, y)
plt.savefig('shade.png', dpi=300)
plt.show()

rawDescription: Shading an area between two points in a matplotlib plot


code:
def add_tags(count):
    new_tags = []
    for t in range(count):
        tag = Tag(tag='tag%s' % t)
        new_tags.append(tag)
    Tag.objects.bulk_create(new_tags)

    tag_ids = list(Tag.objects.values_list('id', flat=True))
    photo_ids = Photo.objects.values_list('id', flat=True)
    tag_count = len(tag_ids)

    tag_to_photo_links = []
    for photo_id in photo_ids:
        shuffle(tag_ids)

        rand_num_tags = randint(0, tag_count)
        photo_tags = tag_ids[:rand_num_tags]

        for tag_id in photo_tags:
            # through is the table generated by django to link m2m between tag and photo
            photo_tag = Tag.Photos.through(tag_id=tag_id, photo_id=photo_id)
            tag_to_photo_links.append(photo_tags)

        Tag.Photos.through.object.bulk_create(tag_to_photo_links, batch_size=7000)

rawDescription: Proper way to bulk_create for ManyToMany field, Django?


rawDescription: Transform method row by row function

description: Transform method row by row function


code:
clientId = ""
Running = -1
Swimming = -1
Aerobics = -1
Football = -1
Tennis = -1

def readFromFile():
    global clientID
    clientID = input("Enter your clientID: ")
    clientFile = open("clientIntensity.txt","r")
    for record in clientFile:
        if record.startswith(clientID):
            print ("Your intensity is", record[6:14])
            intensity = record[6:10]

            if intensity == "High":
                print(" Running \n Swimming \n Aerobics \n Football \n Tennis")
            else:
                print(" Walking \n Hiking \n Cleaning \n Skateboarding \n Basketball")

    clientFile.close()

readFromFile()

def my_input(event):
    num = -1
    while not 0 <= num <= 120:
        num = int(input("Please enter the ammount of minutes you spent " + event + ": "))
    return num

def Time():
    global Running, Swimming, Aerobics, Football, Tennis
    Running = my_input('Running')
    Swimming = my_input("Swimming")
    Aerobics = my_input("Aerobics")
    Football = my_input("Football")
    Tennis = my_input("Tennis")
Time()

print(clientID)
print("The ammount of time spent exercising this week is",Running+Swimming+Aerobics+Football+Tennis)

rawDescription: Can someone look at my code to help and a validation technique to make it only enter between 0 and 120 on my variables?


code:
def deleteList(listo1, listo2):
    for insidelist in listo1:
        if listo2[0] == insidelist[0]:
             listo1.remove(insidelist)
    print(listo1)

def main():
    deleteList([[1000, 1],[2000, 2],[3000, 3]], [1000, 77])

rawDescription: Removing a list item from another list

description: Removing a list item from another list


code:
def do_pie(fic,data):
    import pylab
    # make a square figure and axes
    pylab.figure(1, figsize=(6,6))
    ax = pylab.axes([0.1, 0.1, 0.8, 0.8])
    pylab.pie(data,labels=data)
    pylab.title(fic, bbox={'facecolor':'0.8', 'pad':5})
    pylab.savefig('%s.png' % fic,dpi=100)
    pylab.close()

rawDescription: How to generate several matplotlib charts at a time?

description: Generate several matplotlib charts at a time


code:
from StringIO import StringIO
# ...

with open('foo.cfg') as foo:
    fixed = foo.read().format(**keys)
parser = ConfigParser.ConfigParser()
parser.readfp(StringIO(fixed))

# ...

rawDescription: Combine template and `ConfigParser`

description: Combine template and `ConfigParser`


code:
query = 'select * from test where data in ({})'.format(','.join(['?']*len(my_list)))
curr.execute(query, my_list)

rawDescription: Python sqlite3 - How do I formulate a condition where we check if an attribute in the table is one of the elements in my list


code:
import wx.lib.agw.pyprogress.ProgressGauge as pg

prog = pg.ProgressGauge(self, -1)
prog.SetGaugeBackground(wx.Colour(0, 0, 0))

rawDescription: Want to change progress bar color to Black in wx python


rawDescription: How to specify which optional parameters to use in a method call?

description: Specify which optional parameters to use in a method call


code: buffpkt = pkt[:]

rawDescription: List cannot be copied

description: List cannot be copied


code:
m.groups()
m.span()
m.span(1)
m.span(2)

rawDescription: alternative to `regs` attribute of `match` object in `re` in python3

description: Alternative to `regs` attribute of `match` object in `re` in python3


code:
data = { (1, 0, 0): [0, 0], (1, 1, 0): [1, 0] }
keytoadd = (5, 7, 3)
valuetoadd = [othervalue, othervalue2]

if keytoadd not in data:
    data[keytoadd] = valuetoadd

rawDescription: Most efficient way of searching and adding to a large list that grows with every loop


code:
i = 0
j=0
for root, dirs, files in os.walk('D:/'):
        i += 1
        if i > 150: #this is 150 folders (not files)
           break
        for f in files:
            j+= 1
            if j > 150:  #this is 150 files
               i=151 # force exit the outer loop
               break
            print(f, 'ROOT: ', root, 'DIR: ', dirs)

rawDescription: limit os.walk to a certain number of files

description: Limit os.walk to a certain number of files


code:
class forwardTo(object):
    """
    A descriptor based recipe that makes it possible to write shorthands
    that forward attribute access from one object onto another.

    >>> class C(object):
    ...     def __init__(self):
    ...         class CC(object):
    ...             def xx(self, extra):
    ...                 return 100 + extra
    ...             foo = 42
    ...         self.cc = CC()
    ...
    ...     localcc = forwardTo('cc', 'xx')
    ...     localfoo = forwardTo('cc', 'foo')
    ...
    >>> print C().localcc(10)
    110
    >>> print C().localfoo
    42

    Arguments: objectName - name of the attribute containing the second object.
               attrName - name of the attribute in the second object.
    Returns:   An object that will forward any calls as described above.
    """
    def __init__(self, objectName, attrName):
        self.objectName = objectName
        self.attrName = attrName
    def __get__(self, instance, owner=None):
        return getattr(getattr(instance, self.objectName), self.attrName)
    def __set__(self, instance, value):
        setattr(getattr(instance, self.objectName), self.attrName, value)
    def __delete__(self, instance):
        delattr(getattr(instance, self.objectName), self.attrName)

rawDescription: Attribute mapping with a Python property


code:
from io import BytesIO
a = urllib2.urlopen(url)
myavro = a.read()
reader = DataFileReader(BytesIO(myavro), DatumReader())

rawDescription: Read Avro and parse from web

description: Read Avro and parse from web


code:
import sys
sys.path.insert(0, '/path/to/')

option1 = 'abc'
option2 = 'def'

from MyFile import option3, option4

rawDescription: How to 'add' text to a file using a python function


rawDescription: How to collect values with the same keys in a list from the two dictionaries

description: Collect values with the same keys in a list from the two dictionaries


rawDescription: How to write examples in docstrings that pass Travis CI?

description: Write examples in docstrings that pass Travis CI


code:
vis = {}
def DFS_graph(graph, start, end, stack):
    #Stack to push the node when we are entering the node
    stack.append(start)
    vis[start] = 1
    while len(stack):
        # got to an element
        found_element = stack[-1]
        if found_element == end:
            # you found the end, so break now
            break
        stack.pop()
        for i in graph.edges[start]:
            #check if this is inside the stack, to make sure that it doesn't try to go back
            if i not in vis:
                #Recursive Call
                stack.push(i)

rawDescription: DFS - Implementing a O(|E|) timing complexity solution


code:
import timeit

timeit.default_timer() - 5

rawDescription: platform-independent time calculation

description: Platform-independent time calculation


code:
import logging

class epiLogger():
    _initialised = {}
    _finalised = {}

    def __init__(self, name):
        self.logger = logging.getLogger(name)
        self.name = name
        if not epiLogger._initialised.get(name):
            self.logger.addHandler(logging.StreamHandler())
            self.logger.setLevel(logging.INFO)
            self.logger.info('** My Prologue **')
            epiLogger._initialised[self.name] = True

    def info(self, the_info):
        self.logger.info(the_info)

    def __del__(self):
        if not self.__class__._finalised.get(self.name):
            self.logger.info('** My Epilogue **')
            self.__class__._finalised[self.name] = True

a = epiLogger("foo")

a.info("foo!")
a.info("bar!")
a.info("party!")

rawDescription: Prologue and epilogue in python logger

description: Prologue and epilogue in python logger


rawDescription: Python - Reference Redirected Folder

description: Python - Reference Redirected Folder


code:
import Tkinter as tk

words="""this is a really large file, it has a lot of words"""*25

args=['end']
for i,w in enumerate(words.split()):
   args.extend((w+' ','TAG%d'%i))

root=tk.Tk()
text=tk.Text(root)
text.grid(row=0,column=0)
text.insert(*args)
root.mainloop()

rawDescription: Python: Assigning tags to text in Tkinter


code:
class a(object):
    pass
class b(a):
    pass
class c:
    pass
ai=a()
bi=b()
ci=c()
type(ai) is ai.__class__
type(bi) is bi.__class__
type(ci) is ci.__class__

rawDescription: Difference between type(obj) and obj.__class__


code:
import dis
dis.dis(func)

rawDescription: Why is lookup in dictionary much faster than two if-tests in Python?


code:
life = 200

def example(x):
    return x - 75

life = example(life)

rawDescription: Python - Problem with variables

description: Python - Problem with variables


code:
import os
module_dir = os.path.dirname(__file__)  # get current directory
file_path = os.path.join(module_dir, 'baz.txt')

rawDescription: Open file in Django app

description: Open file in Django app


code:
import sys
from PyQt4 import QtGui, QtCore

class MyDelegate(QtGui.QItemDelegate):

    def __init__(self, parent, table):
        super(MyDelegate, self).__init__(parent)
        self.table = table

    def sizeHint(self, option, index):
        # Get full viewport size
        table_size = self.table.viewport().size()
        gw = 1  # Grid line width
        rows = self.table.rowCount() or 1
        cols = self.table.columnCount() or 1
        width = (table_size.width() - (gw * (cols - 1))) / cols
        height = (table_size.height() -  (gw * (rows - 1))) / rows
        return QtCore.QSize(width, height)

class Window(QtGui.QWidget):
    def __init__(self, rows, columns):
        super(Window, self).__init__()
        self.lay = QtGui.QVBoxLayout()
        self.setLayout(self.lay)
        self.table = QtGui.QTableWidget(rows, columns, self)
        self.table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.lay.addWidget(self.table)
        self.delegate = MyDelegate(self, self.table)
        self.table.setItemDelegate(self.delegate)

    def showEvent(self, event):
        super(Window, self).showEvent(event)
        self.resizeTable()

    def resizeTable(self):
        self.table.resizeRowsToContents()
        self.table.resizeColumnsToContents()

    def resizeEvent(self, event):
        super(Window, self).resizeEvent(event)
        self.resizeTable()

rawDescription: PyQt4 QTableWidget: Set row width and column height to fill parent widget


code:
from pyspark.sql.functions import UserDefinedFunction
from pyspark.sql.types import StringType

name = 'target_column'
udf = UserDefinedFunction(lambda x: 'new_value', Stringtype())
new_df = old_df.select(*[udf(column).alias(name) if column == name else column for column in old_df.columns])

rawDescription: Updating a dataframe column in spark

description: Updating a dataframe column in spark


rawDescription: Is there any `itemgetter` equivalent for `numpy.ndarray`?


code:
from __future__ import division
dict = {u'_id': {u'user': u'ariel', u'day': 1332115200000.0}, u'value': {u'count': 99.0}}
datetime.datetime.utcfromtimestamp(dict['_id']['day'] / 1000.0)

rawDescription: Putting a Date object into MongoDB, getting back a float when querying with pymongo


rawDescription: Python CSV merge fields together

description: Python CSV merge fields together


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

c = np.poly1d([2,-4,-28,62,122,-256,-196,140,392,240,72])

crit = c.deriv().r
r_crit = crit[crit.imag==0].real
test = c.deriv(2)(r_crit)

# compute local minima
# excluding range boundaries
x_min = r_crit[test>0]
y_min = c(x_min)
plot( x_min, y_min, 'o' )

xc = np.arange(-2.5, 2.6, 0.02)
yc = c(xc)
plot( xc, yc)

xlim([-2.5,2.5])
show()

rawDescription: Get minimum point(s) of numpy.poly1d curve


code: numericVariable % 10

rawDescription: How to check last digit of number

description: Check last digit of number


code:
def partition(pred, iterable):
    'Use a predicate to partition entries into false entries and true entries'
    # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
    t1, t2 = tee(iterable)
    return filterfalse(pred, t1), filter(pred, t2)

rawDescription: How to split a sequence according to a predicate?

description: Split a sequence according to a predicate


code:
import signal

import time   # For the demo only

def signal_handler(signal, frame):
    global interrupted
    interrupted = True

signal.signal(signal.SIGINT, signal_handler)

interrupted = False
while True:
    print("Working hard...")
    time.sleep(3)
    print("All done!")

    if interrupted:
        print("Gotta go")
        break

rawDescription: How to stop an infinite loop safely in Python?

description: Stop an infinite loop safely in Python


code:
with open('output outfile.txt', "a+") as f:
    for line in f.readlines():
        parts = line.strip().split("\t")
        f.write('{}\n'.format(parts[0]))

rawDescription: Python: append split list is empty

description: Python: append split list is empty


code:
def tohex(array):
    array = np.asarray(array, dtype='uint32')
    return ((array[:, :, 0]<<16) + (array[:, :, 1]<<8) + array[:, :, 2])

rawDescription: Numpy Image Arrays: How to efficiently switch from RGB to Hex


rawDescription: How to break the tuple brackets within a list?

description: Break the tuple brackets within a list


code:
def triangle(n):
    if n == 0:
        return []
    elif n == 1:
        return [[1]]
    else:
        new_row = [1]
        result = triangle(n-1)
        last_row = result[-1]
        for i in range(len(last_row)-1):
            new_row.append(last_row[i] + last_row[i+1])
        new_row += [1]
        result.append(new_row)
    return result

rawDescription: python recursive pascal triangle

description: Python recursive pascal triangle


code:
from fpdf import FPDF

pdf=FPDF()
pdf.add_page()
pdf.set_font('Courier','B',16)
pdf.cell(40,10,'Hello World!')
pdf.output('tuto1.pdf','F')

rawDescription: Convert a string to a pdf with precise spacing in python


code: filter(None, (r[0].value for r in sheet.range(USERROLELIST)))

rawDescription: Shorter way to check if true in Python list comprehension expression?


code:
from matplotlib.pyplot import scatter, show, xlim, ylim

for index, item in enumerate(speed):
    scatter([times[index]]*len(item), item, marker='.')

xlim(min(times), max(times))
ylim(min(min(speed)), max(max(speed)))
show()

rawDescription: Array element with a sequence

description: Array element with a sequence


code:
import urlparse

def make_links_absolute(soup, url):
    for tag in soup.findAll('a', href=True):
        tag['href'] = urlparse.urljoin(url, tag['href'])

rawDescription: Python BeautifulSoup equivalent to lxml make_links_absolute


code:
import collections

input_dicts = [{1: 0}, {1: 1}, {1: 2}]

output_dict = collections.defaultdict(list)
for d in input_dicts:
    for key in d:
        output_dict[key].append(d[key])

rawDescription: Combining indefinite number of dictionaries for python


code:
class ContactForm(forms.Form):
    full_name = forms.CharField(max_length=120)
    email = forms.EmailField()
    website = forms.URLField()
    message = forms.CharField(max_length=500, widget=forms.Textarea)
    send_notification = forms.BooleanField(required=False)
    # <-- insert 4 spaces here
    fieldsets = ((u'Personal Information',
                {'fields': ('full_name', 'email', 'website'),
                'description': u'Your personal information will not ' \
                                u'be shared with 3rd parties.'}),
                (None,
                {'fields': ('message',),
                'description': u'All HTML will be stripped out.'}),
                (u'Preferences',
                {'fields': ('send_notification',)}))

rawDescription: Why doesn't inspect.getsource return the whole class source?


code:
_routes = {}

@app.route('/<path:url>', marthods=['GET', 'POST'])
def route(url):
    handler = _routes.get(url, None)
    if handler is not None:
        return handler()
    abort(404)

rawDescription: Flask delete routes added with add_url()


code:
#get IP and username for remote access
IP = input("Enter host_server IP: ").split()
username = input("Enter username: ").split()

#create a file on host_server for file
file_a = open(date+"file.txt", "a") #ignore the date variable
file = str(date+"file.txt")
import paramiko
import os
privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
ssh.connect(IP[0], username = user[0], pkey = mykey)

rawDescription: How to connect to remote server with paramiko without a password?

description: Connect to remote server with paramiko without a password


code:
class CheckbuttonPlus(Checkbutton):
    def __init__(self, text, command, padx, justify, ticked=False):
        super().__init__(text, command, padx, justify)
        self.ticked = ticked

rawDescription: To count no. times a function is called?

description: To count no. times a function is called


code:
def getObjectFromLink(url):
    global r
    obj=praw.objects.Submission.get_info(r, url)
    if len(url.split('/'))==6:
        return obj
    else:
        return obj.comments[0]

rawDescription: Using Praw how do you get comment linked by a URL


code:
class YourHandler(webapp2.RequestHandler):
  def get(self):
    params = {'url':self.request.host}
    template = jinja_environment.get_template('your_template.html')
    self.response.write(template.render(params))

rawDescription: How to get base url of website in jinja2?

description: Get base url of website in jinja2


code:
filters = tables.Filters(complevel=4, complib='blosc')
atom = tables.Float32Atom()
array = h5_f.createCArray(group, 'ArrayA', atom, shape, filters=filters)
array[:] = data

rawDescription: How to use LZF or LZO filters to compress HDF5 file in Python?

description: Use LZF or LZO filters to compress HDF5 file in Python


code:
import json
...
parsed_json = json.load(request.POST) # Or GET, depends on what you are using

rawDescription: Python and a JSON Array

description: Python and a JSON Array


code:
import subprocess

with open('filename', 'wb', 0) as file:
    subprocess.check_call(cmd, stdout=file, stderr=subprocess.STDOUT)

rawDescription: How to read stdout and stderr and save it all at once with subprocess Popen?

description: Read stdout and stderr and save it all at once with subprocess Popen


code:
from itertools import chain

with open(xyzfile) as f1, open(input_file) as f2:
    atom_count = len(set('OHCN').intersection(chain.from_iterable(f1)))
    s = f2.read().replace('ntyp = 2', 'nytp = {}'.format(atom_count))

rawDescription: Python Count how many types of characters in a file


code:
data = [[1, 3, "String1"], [3, 2, "String2"]]
class AnyString(str):
    def __eq__(self, other):
        return isinstance(other, str)

check = [1, 3, AnyString()]
check in data

rawDescription: Check if a list element is in a list when one of it's elements is unknown


code:
import socket, select, Queue

from flask import Flask
from celery import Celery

def make_celery(app):
    celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)
    TaskBase = celery.Task
    class ContextTask(TaskBase):
        abstract = True
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)
    celery.Task = ContextTask
    return celery

app = Flask(__name__)
app.config.update(
    CELERY_BROKER_URL='redis://localhost:6379',
    CELERY_RESULT_BACKEND='redis://localhost:6379'
)
celery = make_celery(app)
socket_queue = Queue.Queue()

@celery.task()
def listen_to_udp():
    """
    This code was taken from
    https://stackoverflow.com/questions/9969259/python-raw-socket-listening-for-udp-packets-only-half-of-the-packets-received
    """
    s1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s1.bind(('0.0.0.0', 1337))
    s2 = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
    s2.bind(('0.0.0.0', 1337))
    while True:
        r, w, x = select.select([s1, s2], [], [])
        for i in r:
            socket_queue.put((i, i.recvfrom(131072)))

@app.route("/")
def test_home():
    listen_to_udp.delay()
    print(socket_queue.get())

if __name__ == "__main__":
    #run install.py to install dependencies and create the database
    app.run(host="0.0.0.0", port=5000, debug=True)

rawDescription: Simple Network UDP Listen in Flask or Pyramid


code: df.index = pd.DatetimeIndex(end=pd.datetime.today(), periods=len(df), freq='1D')

rawDescription: Transforming an index to date in PANDAS

description: Transforming an index to date in PANDAS


code:
from urllib2 import Request, urlopen
import json
from pandas.io.json import json_normalize

path1 = '42.974049,-81.205203|42.974298,-81.195755'
request=Request('http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&sensor=false')
response = urlopen(request)
elevations = response.read()
data = json.loads(elevations)
json_normalize(data['results'])

rawDescription: JSON to pandas DataFrame

description: JSON to pandas DataFrame


code:
import numpy as np
import ImageGrab
import cv2

while(True):
    printscreen_pil =  ImageGrab.grab()
    printscreen_numpy =   np.array(printscreen_pil.getdata(),dtype=uint8)\
    .reshape((printscreen_pil.size[1],printscreen_pil.size[0],3))
    cv2.imshow('window',printscreen_numpy)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        cv2.destroyAllWindows()
        break

rawDescription: Screen Capture with OpenCV and Python-2.7


code:
import psutil
for p in psutil.process_iter():
    if p.name == "chrome":
        print (p.pid)
        p.kill()

rawDescription: How to find process ids of running applications using python3

description: Find process ids of running applications using python3


code: boundbox = list(poly.exterior.coords)

rawDescription: PyMongo Shapely GeoJson Conversion

description: PyMongo Shapely GeoJson Conversion


code:
'''VTK'''
plane1 = vtk.vtkPlaneSource()
plane1.SetCenter(1.0, 0.0, 0.0)
plane1.SetNormal(1.0, 0.0, 0.0)
# planes.SetExtent(1,100,1,100,7,7);

'''VTK'''
plane2 = vtk.vtkPlaneSource()
plane2.SetCenter(1.0, 2.0, 0.0)
plane2.SetNormal(0.0, 1.0, 0.0)
# planes.SetExtent(1,100,1,100,7,7);

# mapper
mapper1 = vtk.vtkPolyDataMapper()
mapper1.SetInput(plane1.GetOutput())

# mapper
mapper2 = vtk.vtkPolyDataMapper()
mapper2.SetInput(plane2.GetOutput())

# actor
actor1 = vtk.vtkActor()
actor1.SetMapper(mapper1)

actor2 = vtk.vtkActor()
actor2.SetMapper(mapper2)

'''RENDER'''
renderer = vtk.vtkRenderer()
# Background
renderer.SetBackground(1., 1., 1.)
# Add actor to the scene
renderer.AddActor(actor1)
renderer.AddActor(actor2)

'''Render window'''
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)

'''Interactor'''
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
renderWindowInteractor.SetRenderWindow(renderWindow)

'''Add camera coordinates'''
axes = vtk.vtkAxesActor()
widget = vtk.vtkOrientationMarkerWidget()
widget.SetOutlineColor(0.9300, 0.5700, 0.1300)
widget.SetOrientationMarker(axes)
widget.SetInteractor(renderWindowInteractor)
widget.SetViewport(0.0, 0.0, 0.4, 0.4)
widget.SetEnabled(1)
widget.InteractiveOn()

# Reset camera
renderer.ResetCamera()

'''Begin interaction'''
renderWindow.Render()
renderWindowInteractor.Initialize()
renderWindowInteractor.Start()
renderWindowInteractor.Start()

rawDescription: Draw multiple planes in vtk python api

description: Draw multiple planes in vtk python api


code:
from graphics import *

def redCircles():
    win = GraphWin("Patch2" ,100,100)
    for x in (10, 30, 50, 70, 90):
        for y in (10, 30, 50, 70, 90):
            c = Circle(Point(x,y), 10)
            d = Circle(Point(x,y), 10)
            if x in (30, 70):
                r = Rectangle(Point(x - 10, y), Point(x + 10, y + 10))
            else:
                r = Rectangle(Point(x - 10, y- 10), Point(x, y + 10))
            c.setFill("red")
            d.setOutline("red")
            r.setFill("white")
            r.setOutline('white')
            c.draw(win)
            r.draw(win)
            d.draw(win)

if __name__=='__main__':
    redCircles()

rawDescription: Does anyone know how i can half fill my circles to white?


code:
import numpy as np
from scipy.spatial import ConvexHull
import matplotlib.pyplot as plt

pts1 = [[0.0, 10.0], [0.0, 20.0], [10.0, 0.0], [20.0, 0.0]]
pts = np.array(pts1)

hull = ConvexHull(pts)

plt.fill(pts[hull.vertices,0], pts[hull.vertices,1],'red',alpha=0.5)
plt.show()

rawDescription: How to fill area between multiple points in a graph

description: Fill area between multiple points in a graph


code:
# 1: this should be fine
qry1 = Car.query.join(User, Car.users).filter(User.name=='you')

# 1: this will probably not work for you, as this is not one query, although the result is a Query instance
usr1 = User.query.filter_by(name='you').one()
qry2 = Car.query.with_parent(usr1)

# 3: you might define the relationship to be lazy='dynamic', in which case the query object instance will be returned
from sqlalchemy.orm.query import Query
class Car(Base):
    __tablename__ = 'cars'
    id = Column(Integer, primary_key=True)
    vin = Column(String(50), unique=True, nullable=False)

    users = relationship(User, secondary=user_cars,
            #backref='cars',
            backref=backref('cars', lazy="dynamic"),
            lazy="dynamic",
            )
qry3 = Car.query.filter_by(name="you").one().cars
assert isinstance(qry3, Query)

rawDescription: Convert relationship to query object

description: Convert relationship to query object


code:
urlpatterns = patterns('',
                   (r'^publishers/$', ListView.as_view(
                       queryset=Publisher.objects.all(),
                       template_name='publisher_list_page.html'
                   )))

rawDescription: how to replace list_detail by ListView in my django code

description: Replace list_detail by ListView in my django code


code:
def State_Machine(self):
    groupBox = QtGui.QGroupBox("State Machine")
    main_layout = QtGui.QGridLayout()
    States_list =["INIT","NORMAL","WAKE","SLEEP","STANDBY"]
    self.State =[]
    self.Checkbox =[]
    Regulators_list =["QCO","QVR","QT1","QT2"]
    self.Regulator_checkbox =[]
    self.Applybutton = []

    box2 =QtGui.QHBoxLayout()
    box3 =QtGui.QHBoxLayout()

    label1 = QtGui.QLabel("EMPTY")
    box2.addWidget(label1)

    for i in xrange(5):
        self.State.append(QtGui.QGroupBox(States_list[i]))
        self.Applybutton.append(QtGui.QPushButton("Apply"))

        self.State[i].setFixedSize(200,100)

    for j in xrange(5):
        verticalbox = QtGui.QVBoxLayout()
        firsthbox = QtGui.QHBoxLayout()
        secondhbox = QtGui.QHBoxLayout()
        thirdhbox = QtGui.QHBoxLayout()
        firsthbox.addWidget(self.Applybutton[j])
        for  k in xrange(4):
            self.Checkbox = QtGui.QCheckBox(Regulators_list[k])
            if k < 2:
                secondhbox.addWidget(self.Checkbox)
            if k >= 2:
                thirdhbox.addWidget(self.Checkbox)

        verticalbox.addLayout(firsthbox)
        if j < 4:
            verticalbox.addLayout(secondhbox)
            verticalbox.addLayout(thirdhbox)
        if j == 4:
            verticalbox.addLayout(box2)

        self.State[j].setLayout(verticalbox)
    main_layout.addWidget(self.State[0],4,2)
    main_layout.addWidget(self.State[1],2,2)
    main_layout.addWidget(self.State[2],0,2)
    main_layout.addWidget(self.State[3],2,4)
    main_layout.addWidget(self.State[4],2,0)
    groupBox.setLayout(main_layout)
    return groupBox

rawDescription: How can i place multiple Qwidgets in multiple Qgroupbox using a loop in python?

description: Place multiple Qwidgets in multiple Qgroupbox using a loop in python


code:
import dis

def func(arg):
    x = 5
    arg = 3
    return x + arg

def function_to_code_obj(func):
    return func.func_code

code_obj = function_to_code_obj(func)
dis.disassemble(code_obj)

rawDescription: How do I convert a python function/class/module object to a python code object

description: Convert a python function/class/module object to a python code object


code:
from tkinter import *
import threading
import time

def fibonacci(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fibonacci(n-1) + fibonacci(n-2)

class App:

    def __init__(self, master):
        self.frame = Frame(master)
        self.frame.pack(expand=1, fill=BOTH)
        self.master = master

        self.quitter = Button(self.frame, text="Quit", fg="red", command=self.master.destroy)
        self.quitter.pack(side=LEFT)

        self.starter = Button(self.frame, text="Start", command=self.start)
        self.starter.pack(side=LEFT)

        self.stopper = Button(self.frame, text="Stop", command=self.stop)
        self.stopper.pack(side=LEFT)

        self.counter = 0
        self.running = False

    def start(self):
        self.running = True
        threading.Thread(target=self.start_fibonacci).start()

    def start_fibonacci(self):
        while self.running:
            print(fibonacci(self.counter))
            self.counter += 1
            time.sleep(1)

    def stop(self):
        self.running = False
        print('Stop')

if __name__ == "__main__":
    root = Tk()
    root.title("Fibonacci")
    app = App(root)
    root.mainloop()

rawDescription: How do I make an interuptable program that deals with a heavy computational load?

description: Make an interuptable program that deals with a heavy computational load


code:
#!/usr/bin/python

import gtk

class PyApp(gtk.Window):

    def __init__(self):
        super(PyApp, self).__init__()

        self.set_title("Simple menu")
        self.set_size_request(250, 200)
        self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(6400, 6400, 6440))
        self.set_position(gtk.WIN_POS_CENTER)

        mb = gtk.MenuBar()

        filemenu = gtk.Menu()
        filem = gtk.MenuItem("File")
        filem.set_submenu(filemenu)

        exit = gtk.MenuItem("Exit")
        style = exit.get_style().copy ()
        style.bg[gtk.STATE_NORMAL] = exit.get_colormap().alloc_color (0xffff, 0x0000, 0x0000)
        exit.set_style (style)

        exit.connect("activate", gtk.main_quit)
        filemenu.append(exit)

        mb.append(filem)

        vbox = gtk.VBox(False, 2)
        vbox.pack_start(mb, False, False, 0)

        self.add(vbox)

        self.connect("destroy", gtk.main_quit)
        self.show_all()

PyApp()
gtk.main()

rawDescription: How to change the background color of a gtk.MenuItem()

description: Change the background color of a gtk.MenuItem()


code:
import pysodium
import ctypes
import ctypes.util

sodium = ctypes.cdll.LoadLibrary(ctypes.util.find_library('sodium') or ctypes.util.find_library('libsodium'))
sodium
ctypes.util.find_library('libsodium')
ctypes.util.find_library('sodium')

rawDescription: Traceback: AttributeError: Symbol not Found


code:
import numpy as np

from enable.api import Component, ComponentEditor
from traits.api import HasTraits, Instance
from traitsui.api import UItem, View

from chaco.api import ArrayPlotData, Plot, gray

class Demo(HasTraits):

    plot = Instance(Component)

    traits_view = View(
        UItem('plot', editor=ComponentEditor(size=(600, 600))),
        resizable=True, title="Simple image plot"
    )

    def _plot_default(self):
        image = np.random.random_integers(0, 255, size=(100, 100))
        image = image.astype(np.uint8)
        data = ArrayPlotData(imagedata=image)

        plot = Plot(data, default_origin="top left")
        plot.img_plot("imagedata", colormap=gray)
        return plot

demo = Demo()
demo.configure_traits()

rawDescription: Enthought Canopy Chaco img_plot with grey scale data


rawDescription: Convert List to Pandas Timeseries

description: Convert List to Pandas Timeseries


rawDescription: Weave number rows together with python

description: Weave number rows together with python


code:
import plotly.plotly as py
help(py.Stream)

rawDescription: Dynamically updating Plotly Graph Title

description: Dynamically updating Plotly Graph Title


code:
from textwrap import wrap
labels=['Really really really really really really long label 1',
        'Really really really really really really long label 2',
        'Really really really really really really long label 3']
labels = [ '\n'.join(wrap(l, 20)) for l in labels ]

rawDescription: Wrapping long y labels in matplotlib tight layout using setp


code:
# sfab.py
from fabric.api import run, sudo, task

@task
def myinstall():
    sudo('yum install httpd')

rawDescription: Trying to SSH using Python and fabric

description: Trying to SSH using Python and fabric


rawDescription: In class definition inherited from dict why is there a difference in defining attributes?


code:
import pandas as pd
res = {}
TIME = None

# by default lazy line read
for line in open('file.txt'):
    parts = line.strip().split(':')
    map(str.strip, parts)
    if len(parts) and parts[0] == 'TIME':
        TIME = parts[1].strip(',')
        res[TIME] = {}
        print('New time section start {}'.format(TIME))
        # here you can stop and work with data from previou period
        continue

    if len(parts) <= 1:
        continue
    res[TIME][parts[1].lstrip()] = parts[2].strip(',').split(',')

df = pd.DataFrame.from_dict(res, 'columns')
# for example for TIME 0
dfZero = df['0']
print(dfZero)

df = pd.DataFrame.from_dict(res, 'index')

dfA = df['A']
print(dfA)

rawDescription: Python import text file where each line has different number of columns


code:
try:
    from tkinter import *
    from tkinter import ttk
except ImportError:
    from Tkinter import *
    import ttk

def treeview_sort_column(tv, col, reverse):
    l = [(tv.set(k, col), k) for k in tv.get_children('')]
    l.sort(key=lambda t: int(t[0]), reverse=reverse)
    #      ^^^^^^^^^^^^^^^^^^^^^^^

    for index, (val, k) in enumerate(l):
        tv.move(k, '', index)

    tv.heading(col,
               command=lambda: treeview_sort_column(tv, col, not reverse))

root = Tk()
columns = ('number',)
treeview = ttk.Treeview(root, columns=columns, show='headings')
for t in ('1', '10', '11', '2', '3'):
    treeview.insert('', END, values=(t,))
treeview.pack()
for col in columns:
    treeview.heading(col, text=col,
                     command=lambda: treeview_sort_column(treeview, col, False))

mainloop()

rawDescription: python ttk treeview sort numbers

description: Python ttk treeview sort numbers


code:
from django.forms.models import model_to_dict

def json_view(request):
    phoneinfo = PhoneInfo.objects.filter(user = user_id)
    phones = [model_to_dict(phone) for phone in phoneinfo]

    result = {'phoneinfo': phones}
    return HttpResponse(json.dumps(result), mimetype="application/json")

rawDescription: send report in specific json format

description: Send report in specific json format


code:
import psycopg2

conn = psycopg2.connect("dbname=test user=postgres")

# create a cursor for interaction with the database
cursor = conn.cursor()
# execute your sql statement
cursor.execute("insert into emp select * from emp1")

# retrieve the number of selected rows
number_rows_inserted = cursor.rowcount

# commit the changes
conn.commit()

rawDescription: Python -printing the sql statement record count in the log file


rawDescription: NumPy append to 1-column vector

description: NumPy append to 1-column vector


code:
sorted_input = np.sorted(input_array)
cumsum = np.cumsum(sorted_input)
max_r = (cumsum<desired_sum).sum()
if max_r == len(input_array) and sorted_input[-1] < desired_sum:
    print("sorry I can't do anything for you")
    exit()

for r in range(1,max_r):
    [...]

rawDescription: find all elements in a list of positive numbers that add up to number X

description: Find all elements in a list of positive numbers that add up to number X


code:
row = crsr.fetchone()
rowAsList = [x for x in row]

rawDescription: Convert pyodbc.row to int list

description: Convert pyodbc.row to int list


code: df.groupby('a', as_index=False).apply(lambda x: x.loc[x.b.argmax(),])

rawDescription: Groupby returning full row for max occurs


rawDescription: How to change IP address of wifi interface using python in linux?

description: Change IP address of wifi interface using python in linux


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

point1  = np.array([0,0,0])
normal1 = np.array([1,-2,1])

point2  = np.array([0,-4,0])
normal2 = np.array([0,2,-8])

point3  = np.array([0,0,1])
normal3 = np.array([-4,5,9])

# a plane is a*x+b*y+c*z+d=0
# [a,b,c] is the normal. Thus, we have to calculate
# d and we're set
d1 = -np.sum(point1*normal1)# dot product
d2 = -np.sum(point2*normal2)# dot product
d3 = -np.sum(point3*normal3)# dot product

# create x,y
xx, yy = np.meshgrid(range(30), range(30))

# calculate corresponding z
z1 = (-normal1[0]*xx - normal1[1]*yy - d1)*1./normal1[2]
z2 = (-normal2[0]*xx - normal2[1]*yy - d2)*1./normal2[2]
z3 = (-normal3[0]*xx - normal3[1]*yy - d3)*1./normal3[2]

# plot the surface
plt3d = plt.figure().gca(projection='3d')
plt3d.plot_surface(xx,yy,z1, color='blue')
plt3d.plot_surface(xx,yy,z2, color='yellow')
plt3d.plot_surface(xx,yy,z3, color='cyan')
plt.show()

rawDescription: How to draw planes from a set of linear equations in Python?

description: Draw planes from a set of linear equations in Python


code:
s = StringIO()
pickle.dump([], s)
s.getvalue()

rawDescription: Python memory serialisation

description: Python memory serialisation