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

# Constants
isqrt = 2**(-0.5)
omega = np.sqrt(2-np.sqrt(2))   #Angular velocity
L=4                             #Length of the system

n = 1                         #Normal mode number
if n==1:
    z = [isqrt,1,isqrt]             #mode 1
elif n==2:
    z = [1,0,-1]                   #mode 2
elif n==3:
    z = [isqrt,-1,isqrt]           #mode 3

ex = [1,2,3]                    #x-coordinates of scatter points

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, L), ylim=(-1.1, 1.1))

line, = ax.plot([], [], lw=2, color='b')
scat, = ax.plot([],[], linestyle='', marker='o', color='b')
# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    scat.set_data([], [])
    return [scat,line,]

# animation function.  This is called sequentially
def animate(t):
    xinterval = np.arange(0,10,0.05)
    wave = np.cos(0.1*omega*t)*np.sin(n*xinterval*np.pi/L)
    line.set_data(xinterval, wave)
    dots = z*real(np.exp(0+(omega*0.1*t)*1j))

    scat.set_data(ex, dots)
    return [scat,line,]

# call the animator.
anim = animation.FuncAnimation(fig, animate,init_func=init, frames=range(200), interval=20,     blit=True)
plt.grid(True)
plt.show()

rawDescription: First set of (scatter) plot data remains on the graph during animation with Python's matplotlib


code:
class Thing(object):
    def __init__(self, name, content=None):
        if content is None:
            content = []
        self.name = name
        self.content = content

rawDescription: Python: Instance attribute unexpectedly loaded


code:
atapi.StringField('Url',
                   mode="rw",
                   widget=atapi.ComputedWidget(label="Url",
                                            description="Url set after upload",
                                            visible = { 'edit' :'visible',
                                                        'view' : 'visible' },
                                            ),
                  ),

rawDescription: Plone Archetypes - how display read-only field in base_edit view


code:
@list_route(methods=['get'])
def some_method(self, request, **kwargs):
    queryset = Model.objects.all()
    page = self.paginate_queryset(queryset)
    if page is not None:
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)
    serializer = self.get_serializer(queryset, many=True)
    return Response(serializer.data)

rawDescription: How can I leverage builtin pagination for a list_route in the Django Rest Framework?

description: Leverage builtin pagination for a list_route in the Django Rest Framework


code: G = nx.DiGraph(((source, target, attr) for source, target, attr in my_network.edges_iter(data=True) if attr['weight'] > threshold))

rawDescription: Efficient extraction of a subgraph according to some edge attribute in NetworkX


code:
from flask import Flask
import lxml.html
import json
from lxml.etree import XPath

app = Flask(__name__)

@app.route("/")
def hello():
    url = "http://gbgfotboll.se/information/?scr=table&ftid=51168"
    date = '2014-09-27'
    # use this in real mode: currentDate = (time.strftime("%Y-%m-%d"))
    list = []
    rows_xpath = XPath("//*[@id='content-primary']/table[3]/tbody/tr[td[1]/span/span//text()='%s']" % (date))
    time_xpath = XPath("td[1]/span/span//text()[2]")
    team_xpath = XPath("td[2]/a/text()")

    html = lxml.html.parse(url)

    for row in rows_xpath(html):
        time = time_xpath(row)[0].strip()
        team = team_xpath(row)[0]
        list.append(time + " " + team)

    return json.dump(list)

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

rawDescription: Sending JSON with python

description: Sending JSON with python


code:
from collections import defaultdict
hist = defaultdict(int)
for entry in data:
    hist[entry["location"]] += 1

rawDescription: Is it possible, in python, to update or initialize a dictionary key with a single command?


code:
start_of_day = datetime.datetime.combine(datetime.date.today(), datetime.time())
dt = start_of_day + datetime.timedelta(seconds=58800)

rawDescription: Create Unix timestamp given the time only


code: df['col'] = ['new string' if '@' in x else x for x in df['col']]

rawDescription: replace string in pandas dataframe

description: Replace string in pandas dataframe


rawDescription: Python list manipulation: combine predecessor and successor to tuples


code:
def save(self, **kwargs):
    slug_str = "%s %s %s %s" % (self.user, self.year, self.model, self.series)
    unique_slugify(self, slug_str)
    super(Phone, self).save()

rawDescription: Generating unique slug in Django

description: Generating unique slug in Django


rawDescription: Functional statement in Python to return the sum of certain lists in a list of lists


code:
import re
re.findall(r'[\\]', r'\ the backslash will match')
re.findall(r'[\C]', r'\C is not a valid escape sequence, only Cs will match')
re.findall(r'[\s]', r'No s will match, whitespace is matched instead')

rawDescription: metacharacters with slash inside brackets

description: Metacharacters with slash inside brackets


code:
class MainWindow(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.vbox = QVBoxLayout()
        self.buttons = []

        for i in range(3):
            button = QPushButton(str(i), self)
            self.vbox.addWidget(button)
            self.buttons += [button]

        self.setLayout(self.vbox)

rawDescription: PyQt - how can element exist without pointer?


code:
import re
substrings = ['microsoft.com', 'ibm.com', 'cnn', '.ru']
pattern = "(?:%s)" % "|".join(map(re.escape, substrings))
print(pattern)
pattern = re.compile(pattern)
[x for x in ["www.microsoft.com", "example.com", "foo.ru"]
   if not pattern.search(x)]

rawDescription: filter list in python by another list of stop-words (substrings)

description: Filter list in python by another list of stop-words (substrings)


rawDescription: What is the pythonic way to merge a 2d list by one of its columns


code: [int(i) for i in str(12345)]

rawDescription: splitting integer in python?

description: Splitting integer in python


code:
f_in = open('my_file')
f_out = open('new_file', 'w')
for line in f:
    new_str = ''.join(line.split(',')[1:])
    f_out.write(new_str)

rawDescription: Remove all characters before comma of every line in a file in python


code:
# touch chroot/dev/random
# mount --bind /dev/random chroot/dev/random

rawDescription: openssl inside a chroot

description: Openssl inside a chroot


rawDescription: python3: How to get logical complement (negation) of a binary number, eg. '010' => '101'?

description: Python3: How to get logical complement (negation) of a binary number, eg. '010' => '101'


code:
import re
re.findall(r"\d+|[,;]", s)

rawDescription: Joining characters not seperated by a particular character in lists


code: ", ".join(x.strftime("%d/%m/%Y") for x in daterange)

rawDescription: Format comma seperated list of dates in python


code: sorted(list5, key=lambda vertex: (degree(vertex), vertex))

rawDescription: How do I perform secondary sorting in python?

description: Perform secondary sorting in python


code:
data2008 = {x[-1]:x[1] for x in data}
# {u'US-AL': 290060.0, u'US-AK', 46400.0, ...}
# data2008["US-AL"] == 290060.0
## NOTE THAT DICTIONARIES ARE UNORDERED -- IF YOU NEED TO KEEP THE
## ORDER FOR ANY REASON OTHER THAN DISPLAYING IT TO THE USER (FOR
## WHICH for line in sorted(data2008) WILL WORK PERFECTLY, DO NOT
## DO THIS

rawDescription: How to split a Python list

description: Split a Python list


code:
class Start(TemplateView):

    def get_template_names(self):
        if self.request.user.is_authenticated():
            return ['dashboard/dashboard.html']
        return ['dashboard/start.html']

rawDescription: Adding start separate page in django app


code:
def init_a(obj):
    obj.x = 10

def init_b(obj):
    init_a(obj)
    obj.y = 20

o = {}
init_b(o)

rawDescription: Initializing parent class instance attributes


code:
import itertools
protos = re.findall(r'PROTO\s*\{(.*?)\}', data, flags=re.DOTALL)
lines = [re.findall(r'(\w+),', x) for x in protos]
products = list(itertools.chain.from_iterable(lines))

rawDescription: How to implement the mentioned regex in the Python Code

description: Implement the mentioned regex in the Python Code


code:
all(x in 'tomato' for x in ['t','o','m','a'])
all(x in 'potato' for x in ['t','o','m','a'])

rawDescription: String contains all the elements of a list


code:
df.set_index('Date', inplace=True)
index = ['2016-01', '2016-02', '2016-03']

df.groupby('Group').apply(lambda df1: df1.reindex(index).interpolate())

rawDescription: Pandas resample by groups with duplicate datetimes


code:
to_decorate = []

def decorate_later(func):
    to_decorate.append(func)
    return func

@decorate_later
def do_stuff(*args, **kw):
    print('I am doing stuff')
@decorate_later
def do_more_stuff(*args, **kw):
    print('Even more stuff')

def apply_decorator(decorator):
    for func in to_decorate:
        globals()[func.func_name] = decorator(func)

rawDescription: How to make Python Decorator NOT run when imported

description: Make Python Decorator NOT run when imported


code:
import time
answer = time.mktime(time.strptime(string, '%Y-%m-%d %H:%M:%S'))

rawDescription: Can you please tell me how can I convert this date string to total seconds in python?

description: Please tell me how can I convert this date string to total seconds in python


code:
a = 'foo'
b = 'foo'
a is b
b = 'f' + ('oo',)[0]
a is b
a = intern('foo')
b = intern('f' + ('oo',)[0])
a is b

rawDescription: Database Compression in Python

description: Database Compression in Python


rawDescription: Convert numpy int array to boolean array


code:
class IAVForm(forms.ModelForm):
  z_score = forms.DecimalField(widget=forms.NumberInput(attrs={'class':'form-control','value':'0.0',}))
  screens = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control','value':'0',}))
  flu_proteins = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control','value':'0',}))
  key_word = forms.CharField(required=False, widget=forms.Textarea(attrs={'class':'form-control','rows':1,'cols':10,'placeholder':'keword values'}))

rawDescription: Django TextField always is required, despite blank=True,Null=True


code: self.assertEqual('foo'.upper(), 'FOO', 'custom message')

rawDescription: Print custom string upon unittest failure


code:
class CustomList(list):
    def __init__(self, *args):
        super(CustomList, self).__init__(*args)
        # call your own methods here

rawDescription: Call a method in initialization without overriding base class's __init__


code: n.to_bytes(2, 'little')  # b'\x01\x01'

rawDescription: How to display values larger than 255 in Bytes in Python 3

description: Display values larger than 255 in Bytes in Python 3


rawDescription: Python 3 doesn't have the file function

description: Python 3 doesn't have the file function


code: thisArray = numpy.rollaxis(numpy.indices(shape), 0, len(shape)+1)

rawDescription: Pythonic way to create a numpy array of coordinates


rawDescription: Creating a directory based on function parameters, Python


code:
from django.contrib.auth.models import User, Group
from django.db.models.signals import post_save

def default_group(sender, instance, created, **kwargs):
    if created:
        instance.groups.add(Group.objects.get(name='your default group name'))
post_save.connect(default_group, sender=User)

rawDescription: How do I set a default group with django-authopenid?

description: Set a default group with django-authopenid


rawDescription: Combine the dataframe in Pandas

description: Combine the dataframe in Pandas


code:
import sys

print(sys.executable)

rawDescription: Find full path of python interpreter?

description: Find full path of python interpreter


rawDescription: grouping csv data under same timestamp

description: Grouping csv data under same timestamp


code:
rows = archesDB.read_all("""SELECT %s
                       FROM arches
                       WHERE lower(arch) like %%s""" % (",".join(columns),),
                       ("%%%s%%" % (arch.lower(),),))

rawDescription: Python, SQL: Set the columns read as parameter


code:
import argparse
parser = argparse.ArgumentParser()
g = parser.add_mutually_exclusive_group()
g.add_argument("--a",help="Argument a")
g.add_argument("--b",help="Argument b")
g.add_argument("--c",help="Argument c")
args= parser.parse_args()

rawDescription: How do I constrain my python script to only accepting one argument? (argparse)

description: Constrain my python script to only accepting one argument? (argparse)


code: from __future__ import braces

rawDescription: Does Jython have the GIL?

description: Does Jython have the GIL


code:
import scipy
import pylab
import scipy.cluster.hierarchy as sch

# Generate random features and distance matrix.
x = scipy.rand(40)
D = scipy.zeros([40,40])
for i in range(40):
    for j in range(40):
        D[i,j] = abs(x[i] - x[j])

# Compute and plot first dendrogram.
fig = pylab.figure(figsize=(8,8))
ax1 = fig.add_axes([0.09,0.1,0.2,0.6])
Y = sch.linkage(D, method='centroid')
Z1 = sch.dendrogram(Y, orientation='right')
ax1.set_xticks([])
ax1.set_yticks([])

# Compute and plot second dendrogram.
ax2 = fig.add_axes([0.3,0.71,0.6,0.2])
Y = sch.linkage(D, method='single')
Z2 = sch.dendrogram(Y)
ax2.set_xticks([])
ax2.set_yticks([])

# Plot distance matrix.
axmatrix = fig.add_axes([0.3,0.1,0.6,0.6])
idx1 = Z1['leaves']
idx2 = Z2['leaves']
D = D[idx1,:]
D = D[:,idx2]
im = axmatrix.matshow(D, aspect='auto', origin='lower', cmap=pylab.cm.YlGnBu)
axmatrix.set_xticks([])
axmatrix.set_yticks([])

# Plot colorbar.
axcolor = fig.add_axes([0.91,0.1,0.02,0.6])
pylab.colorbar(im, cax=axcolor)
fig.show()
fig.savefig('dendrogram.png')

rawDescription: plotting results of hierarchical clustering ontop of a matrix of data in python

description: Plotting results of hierarchical clustering ontop of a matrix of data in python


code:
plt.axis("off") # turn off axis
# output to a temporary file name and display it in matplotlib
filename = "/tmp/image.png"
plt.savefig(filename, dpi=400, bbox_inches='tight')
img = imread(filename)
self.axes.imshow(img)

rawDescription: Embedding a networkx graph into wxPython with matplotlib


code:
import tkinter as tk
import os

def callback():
    filename = 'test.py'
    os.system(filename) #Open file [Same as Right-click Open]
    os.system('notepad '+filename) #Open in notepad

root = tk.Tk()
tk.Button(root, text="Python File", command=callback).pack()
root.mainloop()

rawDescription: Link different python files with button click using tkinter python 3.4


code:
def scraper(request):
    try:
        url = request.GET.get('url')
        su_obj = ScrappedURL(url=url)
        su_obj.save()
        html = urllib2.urlopen(url)
        parsed_html = BeautifulSoup(html)
        p_tags = parsed_html.findAll('p')
        f = tempfile.NamedTemporaryFile()
        for tag in p_tags:
            f.write("\n")
            f.write(tag.getText())
            f.write("\n")
        f.seek(0)
        response = HttpResponse(content_type ='application/force-download')
        response['Content-Disposition'] = 'attachment; filename=file.txt'
        response.write(f.read())
    except Exception as e:
        res_dict = {"status":0,"Exception":e}
        return HttpResponse(json.dumps(res_dict))
    return response

rawDescription: Download a zip file using Django?

description: Download a zip file using Django


code:
import random

x = 2 # Amount of Random choices
dict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
dict2 = {}

for _ in range(x):
    key = random.choice(list(dict.keys()))  # Chose a random key
    dict2[key] = dict[key] # Add it to new dict
    dict.pop(key, None) # Remove from old dict, so it doesn't get picked again

print(dict2)

rawDescription: how to pick key and value from a dictionary and build a new dictrionary

description: Pick key and value from a dictionary and build a new dictrionary


code:
for j in range( 1, len(P)-2 ):  # skip the ends
    for t in range( 10 ):  # t: 0 .1 .2 .. .9
        p = spline_4p( t/10, P[j-1], P[j], P[j+1], P[j+2] )
        # draw p

def spline_4p( t, p_1, p0, p1, p2 ):
    """ Catmull-Rom
        (Ps can be numpy vectors or arrays too: colors, curves ...)
    """
        # wikipedia Catmull-Rom -> Cubic_Hermite_spline
        # 0 -> p0,  1 -> p1,  1/2 -> (- p_1 + 9 p0 + 9 p1 - p2) / 16
    # assert 0 <= t <= 1
    return (
          t*((2-t)*t - 1)   * p_1
        + (t*t*(3*t - 5) + 2) * p0
        + t*((4 - 3*t)*t + 1) * p1
        + (t-1)*t*t         * p2 ) / 2

rawDescription: Catmull-Rom splines in python

description: Catmull-Rom splines in python


code:
headers = [header.text.strip() for header in table.find_all('th',{'scope' :'col'})]
rows = []

for row in table.find_all('tr'):
    rows.append([val.text.encode('utf8').rstrip() for val in row.find_all(['td', 'th'])])

with open('filename.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerow(headers)
    writer.writerows(row for row in rows if row)

rawDescription: How to parse HTML table with rows contaning both <th> and <td> tags under the <tr> tag?

description: Parse HTML table with rows contaning both <th> and <td> tags under the <tr> tag


code:
locals().get('some_var', "some_var doesn't exist.")
some_var = 0
locals().get('some_var', "some_var doesn't exist.")

rawDescription: Cleanest way of choosing between two values in Python


rawDescription: How can I convert ranked table with pandas?

description: Convert ranked table with pandas


code:
ts = pd.Series(1, index=pd.date_range('2000-1-1', periods=10, freq='30T'))
ts
ts.loc[ts.index.minute == 0]

rawDescription: How to resample a dataframe by dropping every second row ( dropping every 30min measurements)

description: Resample a dataframe by dropping every second row ( dropping every 30min measurements)


rawDescription: Django query across many-to-many relationship


code:
import collections
source = [{'x': 1, 'cat': 1},
          {'x': 1, 'cat': 1},
          {'x': 1, 'cat': 2},
          {'x': 1, 'cat': 1},
          {'x': 1, 'cat': 2},
          {'x': 1, 'cat': 1},
          {'x': 1, 'cat': 2},
          {'x': 1, 'cat': 3}]
minimum_count = 2

category_counts = collections.Counter(item['cat'] for item in source)
# category_counts == {1: 4, 2: 3, 3: 1}

frequent_categories = {
    category for category, count in category_counts.items()
    if count > minimum_count
}
# frequent_categories == {1, 2}

result = [item for item in source if item['cat'] in frequent_categories]

rawDescription: In python: filter out elements in a list of dicts where some property is underrepresented


code:
MT = client.factory.create('MoneyTransfer')
MT.transferDate = '01/01/01'
MT.debitAccount = '01234567'
MT.creditAccount = '87654321'
MT.transferAmount = 1000000.00

TB = client.factory.create('TransferBalance')
TB.transDetails = MT

rawDescription: How can I create complex types in suds python

description: Create complex types in suds python


code:
from itertools import zip_longest

files = [open(filename) for filename in file_list]

for lines in zip_longest(*files, fillvalue=''):
    print(" ".join(lines))

rawDescription: Read lines from multiple files python

description: Read lines from multiple files python


code:
def copyStruct(inputStruct, outputValues):
    return [copyStruct(subList, outputValues)
            if isinstance(subList, list)
            else next(outputValues)
            for subList in inputStruct]

copyStruct(inputList, iter(flattenedResults))

rawDescription: What is the best way to separate a single list into multiple lists based on a pattern in Python?


code:
words = re.split('[\[\]]+', key_value)
words = filter(None, words)          # remove empty words
key = words[0]
value = words[1] if len(words) > 1 else None

rawDescription: Regex to extract key surrounded by brackets


code:
import unidecode # to install: `pip install unidecode`
line = u"Flyttbara hyllplan anpassar förvaringen så"
unidecode.unidecode(line)

rawDescription: scan through a list with dictionary in python

description: Scan through a list with dictionary in python


code:
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client import tools

# the stored credentials file to use for these tests
TEST_CREDENTIALS_FILE = 'testjoe.storage'

def get_credentials():
    """Utility routine to returns credentials for testing use"""

    # Location of the credentials storage file
    storage = Storage(TEST_CREDENTIALS_FILE)

    # Start the OAuth flow to retrieve credentials
    flow = flow_from_clientsecrets('client_secret_native.json', scope='https://www.googleapis.com/auth/gmail.modify')

    # Try to retrieve credentials from storage or run the flow to generate them
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        flags = tools.argparser.parse_args(args=[])
        credentials = tools.run_flow(flow, storage, flags)
    return credentials

rawDescription: Google Calendar API when access_token is invalid


code:
from nltk import word_tokenize, pos_tag
from nltk.corpus import wordnet as wn
text = 'this is a pos tagset in some foo bar paradigm'
pos_tag(word_tokenize(text))
for tok, pos in pos_tag(word_tokenize(text)):
    pos = pos[0].lower()
    if pos in ['a', 'n', 'v']:
            wn.synsets(tok, pos)

rawDescription: Converting POS tags from TextBlob into Wordnet compatible inputs


code:
def on_this_day(day, month):
    return Event.objects.filter(date__day=day, date__month=month)

rawDescription: Django day and month event date query

description: Django day and month event date query


code:
for name in namelist:
    firstname = library.find('.//firstname[@name="{}"]'.format(name))

rawDescription: How can I find a element that has a particular name attribute using ElementTree in Python

description: Find a element that has a particular name attribute using ElementTree in Python


code:
def register_New_Date():
    # Cast PostgreSQL Date as Python string
    # Reference:
    # 1. http://initd.org/psycopg/docs/extensions.html#psycopg2.extensions.new_type
    # 2. http://initd.org/psycopg/docs/advanced.html#type-casting-from-sql-to-python
    # 1082 is OID for DATE type.
    NewDate = psycopg2.extensions.new_type((1082,), 'DATE', psycopg2.STRING)
    psycopg2.extensions.register_type(NewDate)

rawDescription: How to cast date to string in psycopg2?

description: Cast date to string in psycopg2


code:
import test

def test_call_save_file_if_necessary(self):
    """test function to test add in list."""
    ip_dic = ["seven1", "seven2", "seven3"]
    test.save_file_if_necessary = Mock()

    test.test_function()
    self.assertTrue(test.save_file_if_necessary.called)

rawDescription: Python Mock function return always False


code:
def testfunc():
    ok = False
    while not ok:
        testvar = input('Select Option\n\n[1] Option 1\n[2] Option 2\n\n    >')
        if testvar in ('1', 'Option 1', 'option 1'):
            print("\nYou selected Option 1")
            ok = True
        elif testvar in ('2', 'Option 2', 'option 2'):
            print("\nYou Selected Option 2")
            ok = True
        else:
            print("\n\nThat is not an option, please select another option")

    print(testvar)

testfunc()

rawDescription: How to replace value of variable within function in python 3

description: Replace value of variable within function in python 3


code:
callable(open)
print(callable.__doc__)

rawDescription: Find out if an Python object is callable


code:
import ipaddress
ip1 = ipaddress.IPv4Address('192.168.0.1')
ip2 = ipaddress.IPv4Address('192.168.0.2')
ip3 = ipaddress.IPv4Address('192.168.1.1')
net = ipaddress.IPv4Network('192.168.0.0/24')
ip1 in net
ip2 in net
ip3 in net

rawDescription: determine if two IP addresses can communicate

description: Determine if two IP addresses can communicate


code:
def second_parse(self, response):
   webDriver = webdriver.Firefox()
   webDriver.get(url)

   # scrape

   webDriver.close()

rawDescription: yield multiple request to a same parse function. what is the order of function running? Scrapy

description: Yield multiple request to a same parse function. what is the order of function running? Scrapy


code: np.repeat(s.index.values, s.values)

rawDescription: Converting document-term count in Pandas series into a python list


code:
def convert(argument):
    return map(int, argument.split(','))  # 3.x: consider wrapping in list()

parser.add_argument('--ids', type=convert)

rawDescription: Pass an optional list to argparse

description: Pass an optional list to argparse


code:
try:
    f = bz2.BZ2File(corpus, mode='r')
except IOError:
    f = codecs.open(corpus, encoding='utf-8')
for data in parse_lines(f):
    yield data
f.close()

rawDescription: Try opening a file as an archive, otherwise read as a regular file


code:
import xlwt, csv, os

csv_folder = "Output/"

book = xlwt.Workbook()
for fil in os.listdir(csv_folder):
    sheet = book.add_sheet(fil[:-4])
    with open(csv_folder + fil) as filname:
        reader = csv.reader(filname)
        i = 0
        for row in reader:
            for j, each in enumerate(row):
                sheet.write(i, j, each)
            i += 1

book.save("Output.xls")

rawDescription: How can I convert all .csv files in a folder into a single .xlsx file with multiple worksheet tabs (1 for each .csv)?

description: Convert all .csv files in a folder into a single .xlsx file with multiple worksheet tabs (1 for each .csv)


code: cb.ax.set_yticklabels([str(x) + 'dB' for x in np.arange(0, 9)])

rawDescription: list comprehension producing result plus gibberish

description: List comprehension producing result plus gibberish


rawDescription: Sorting lists by multiple criteria and appending


rawDescription: How to create a list of date string in 'yyyymmdd' format with Python Pandas?

description: Create a list of date string in 'yyyymmdd' format with Python Pandas


code:
import matplotlib.pyplot as plt

x = [2, 4, 3]
y = [1, 3, 5]
errors = [0.5, 0.25, 0.75]

plt.figure()
plt.errorbar(x, y, xerr=errors, fmt = 'o', color = 'k')
plt.yticks((0, 1, 3, 5, 6), ('', 'x3', 'x2', 'x1',''))

rawDescription: Python boxplot showing means and confidence intervals


code:
import os
import subprocess

subprocess.call (["7z", "x", "test.7z", "-ppasswd"])

rawDescription: how to test for passwords entries of a 7zip file using a python script?

description: Test for passwords entries of a 7zip file using a python script


code: print(item.name, ":", textwrap.fill(item.description), "\n\nValue :", item.value)

rawDescription: Wrapping text during print Python

description: Wrapping text during print Python


code:
from openpyxl import Workbook
nfc_east = ('DAL', 'WAS', 'PHI', 'NYG')
wb = Workbook()
ws = wb.active
for row, i in enumerate(nfc_east):
    column_cell = 'A'
    ws[column_cell+str(row+2)] = str(i)

wb.save("row_creation_loop.xlsx")

rawDescription: Python - How to use a for loop to write data to a cell, then move to the next row


code:
import os
import shutil

srcpath = "E:\\Learning Python\\Testing out\\thunderstorm stuff"
srcfiles = os.listdir(srcpath)

destpath = "E:\\Learning Python\\Testing out\\test folder"

# extract the three letters from filenames and filter out duplicates
destdirs = list(set([filename[12:15] for filename in srcfiles]))

def create(dirname, destpath):
    full_path = os.path.join(destpath, dirname)
    os.mkdir(full_path)
    return full_path

def move(filename, dirpath):
    shutil.move(os.path.join(srcpath, filename)
                ,dirpath)

# create destination directories and store their names along with full paths
targets = [
    (folder, create(folder, destpath)) for folder in destdirs
]

for dirname, full_path in targets:
    for filename in srcfile:
        if dirname == filename[12:15]:
            move(filename, full_path)

rawDescription: How to match and move files into corresponding folders using Python

description: Match and move files into corresponding folders using Python


code: only = set(args.onlyTheseServers or availableServers)

rawDescription: Convert one list to set, but if empty use a default one


rawDescription: Python "private" classmethod and DRY

description: Python "private" classmethod and DRY


code:
import pandas as pd

numberoffiles = 100

# FIRST IMPORT (CREATE RESULT DATA FRAME)
result = pd.read_csv("1isoforms.fpkm_tracking.txt", sep="\t",
                      index_col=[0,1,2,3], usecols=[0,1,2,3,7])

# ALL OTHER IMPORTS (MERGE TO RESULT DATA FRAME, 8TH COLUMN SUFFIXED ITERATIVELY)
for i in range(2,numberoffiles+1):
    df = pd.read_csv("{}isoforms.fpkm_tracking.txt".format(i), sep="\t",
                     index_col=[0,1,2,3], usecols=[0,1,2,3,7])

    result = pd.merge(result, df, right_index=True, left_index=True, suffixes=[i-1, i])

result.to_excel("Output.xlsx")
result.to_csv("Output.csv")

rawDescription: concatenate pandas dataframe in a loop of files

description: Concatenate pandas dataframe in a loop of files


code:
new_x = []
new_y = []
new_y = []
new_i = []

for index in range(len(i_list)):
    if i_list[index] != 0:
        new_x.append(x_list[index])
        new_y.append(y_list[index])
        # Etc.

rawDescription: Most efficient way to remove entries in a list


code:
from django.db.models import Avg

def get_queryset(self):
    return Fruit.objects.filter(user=self.request.user).annotate(
                                vote_avg=Avg('items__vote'))

rawDescription: Average of M2M element in ListView

description: Average of M2M element in ListView


rawDescription: Ordering columns in dataframe

description: Ordering columns in dataframe


code:
with transaction.commit_on_success():
    query = Log.objects.raw("SELECT * FROM ...log WHERE time BETWEEN %s and %s", [lastUpdate, now])

rawDescription: Simpliest python long polling

description: Simpliest python long polling


code:
if x=='':
    pass
elif x in s:
    pass
elif x not in s:
    pass

rawDescription: Create a new string out of the old string with python (1)


code:
import sys

def my_print(text):
    sys.stdout.write(str(text))
    sys.stdout.flush()

rawDescription: python `print` does not work in loop

description: Python `print` does not work in loop


code:
def cond_freq_dist(data):
    """ Takes a list of tuples and returns a conditional frequency distribution as a pandas dataframe. """

    cfd = {}
    for cond, freq in data:
        try:
            cfd[cond][freq] += 1
        except KeyError:
            try:
                cfd[cond][freq] = 1
            except KeyError:
                cfd[cond] = {freq: 1}

    return pd.DataFrame(cfd).fillna(0)

rawDescription: NLTK ConditionalFreqDist to Pandas dataframe


code: openerp.report.rml_parse = my_parser

rawDescription: OpenERP engine modification

description: OpenERP engine modification


code:
import mutagen
from flask import make_response
import os

music_dir = 'c:/www/music'

@app.route('/cover')
def cover_art():
    fname = 'music.mp3'
    mp3 = mutagen.File(os.path.join(music_dir, fname))
    art = mp3.tags['APIC:'].data
    def wsgi_app(environ, start_response):
        start_response('200 OK', [('Content-type', 'image/jpeg')])
        return art
    return make_response(wsgi_app)

rawDescription: python 3 mp3 artwork

description: Python 3 mp3 artwork


code:
import MySQLdb

db = MySQLdb.connect(host="", user="", passwd="", db="")
cursor = db.cursor()
sql = """SELECT DISTINCT keywords FROM keywords"""
tweets = open("keywords.txt", "w")
cursor.execute(sql)
for row in cursor:
   print>>tweets, row[0]
tweets.close()
db.close()

rawDescription: Saving data from MySQL table to a text file with Python


code:
def steps(start,end,n):
    if n<2:
        raise Exception("behaviour not defined for n<2")
    step = (end-start)/float(n-1)
    return [int(round(start+x*step)) for x in range(n)]

rawDescription: Generating evenly distributed multiples/samples within a range


rawDescription: Python - 'module' object is not callable returned when calling function


code:
axs = pd.tools.plotting.scatter_matrix(df, diagonal='kde')

def wrap(txt, width=8):
    '''helper function to wrap text for long labels'''
    import textwrap
    return '\n'.join(textwrap.wrap(txt, width))

for ax in axs[:,0]: # the left boundary
    ax.grid('off', axis='both')
    ax.set_ylabel(wrap(ax.get_ylabel()), rotation=0, va='center', labelpad=20)
    ax.set_yticks([])

for ax in axs[-1,:]: # the lower boundary
    ax.grid('off', axis='both')
    ax.set_xlabel(wrap(ax.get_xlabel()), rotation=90)
    ax.set_xticks([])

rawDescription: How to modify pandas plotting integration?

description: Modify pandas plotting integration


rawDescription: App logo for python tkinter window

description: App logo for python tkinter window


code:
df1.columns = pd.MultiIndex.from_tuples([(c, '', '') for c in df1])
pd.concat([df2, df1], axis=1)

rawDescription: How to combine single and multiindex Pandas DataFrames

description: Combine single and multiindex Pandas DataFrames


code:
#!/usr/bin/env python3

import requests
from bs4 import BeautifulSoup

url = "http://www.fveconstruction.ch/anDetails.asp?RT=2&M=06&R=4&ID=10003401"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# First, put the data in a clean list
contact_name = soup.find("span", class_="titreentreprise").string
contact_info_raw = str(soup.find_all("span",
                       class_="entrepriseDef")[0].next_sibling()[0])
contact_info = contact_info_raw.split('<br>')
contact_info = filter(None, contact_info)
del contact_info[-1]

# Now, parse the list to get the actual data
address = ""
contact_data = {}
for line in contact_info:
    split_line = line.split('\xc2\xa0:\xc2\xa0')
    if len(split_line) == 1:
        address += ' ' + line
    else:
        contact_data[split_line[0]] = split_line[1]

contact_data["address"] = address
email = BeautifulSoup(contact_data['e-Mail'])
contact_data['e-Mail'] = email.find('a').string

print(contact_name, contact_data)

rawDescription: BeautifulSoup without Class or tags

description: BeautifulSoup without Class or tags


code:
from matplotlib.ticker import FuncFormatter

formatter = FuncFormatter(lambda y, pos: "%d%%" % (y))
ax.yaxis.set_major_formatter(formatter)

rawDescription: How To Change Bar Chart Values to Percentages (Matplotlib)


code:
import random
import bisect
data = []
input_data = random.sample(range(1000),100)
#Substitute this with your serial input data
for i in input_data:
    bisect.insort(data, i)
min = data[0]
max = data[-1]

rawDescription: efficient updating of variables

description: Efficient updating of variables


code:
import matplotlib.pyplot as plt
import matplotlib.font_manager
from numpy import *

# cmunso.otf is a randomly selected font in my tex installation
path = '/usr/local/texlive/2012/texmf-dist/fonts/opentype/public/cm-unicode/cmunso.otf'
f0 = matplotlib.font_manager.FontProperties()
f0.set_file(path)

plt.figure()
plt.xlim(0,1.)
plt.ylim(0,1.)

d = arange(0, 1, .1)
plt.plot(d, d, "ob", label='example')

plt.text(.5, .1, 'text.. abcdef', fontproperties=f0, size=30)
plt.xlabel("x label", fontproperties=f0)
plt.legend(prop=f0, loc=2)

rawDescription: python latex font xcode

description: Python latex font xcode


code:
message = email.message_from_string(raw_body)

plain_text_body = ''
if message.is_multipart():
    for part in message.walk():
        if part.get_content_type() == "text/plain":
            plain_text_body = part.get_payload(decode=True)
            break

if plain_text_body == '':
    plain_text_body = BeautifulSoup(message.as_string()).get_text()

rawDescription: Trying to convert html to text in python?


code:
worker = app.Worker(
    hostname=hostname,
    queues=[hostname],
    optimization='fair'
)
worker.start()

rawDescription: Celery run worker with -Ofair from python


code: import pdb; pdb.set_trace()

rawDescription: Python debugging by invoking the keyboardinput in a script


rawDescription: Display only the top n results from classifier.predict_proba(X)


code: items = sorted(dct.iteritems(), key=lambda x: x[1].total, reverse=True)

rawDescription: sort dictionary of objects

description: Sort dictionary of objects


code:
from pymc3 import *
import theano.tensor as T
basic_model = Model()

def logistic(l):
    return 1 / (1 + T.exp(-l))

with basic_model:
    # Priors for unknown model parameters
    alpha = Normal('alpha', mu=0, sd=10)
    beta = Normal('beta', mu=0, sd=10, shape=18)

    # Expected value of outcome
    mu = alpha + beta[0]*X1 + beta[1]*X2 + beta[2]*X3

    # Likelihood (sampling distribution) of observations
    Y_obs = Bernoulli('Y_obs', p=logistic(mu), observed=Y)

rawDescription: How to set Bernoulli distribution parameters in pymc3

description: Set Bernoulli distribution parameters in pymc3


code: soup = BeautifulSoup(source, 'xml')

rawDescription: BS4: Case sensitive searching

description: BS4: Case sensitive searching


rawDescription: Integer to byte conversion

description: Integer to byte conversion


code:
lines = open(filename).readlines()
regex = re.compile("(.*):.*@gmail\.com")
aliases = [m.group(1) for m in map(lambda x: regex.match(x), lines) if m]

rawDescription: Python - Regular Expression Assistance

description: Python - Regular Expression Assistance


code:
filter = ['a', 'b', 'c']
" ".join(["item -%s" % val for val in filter])

rawDescription: String formatting

description: String formatting


code:
string = u'#exampleTextInput{ background-color:#ff0000;}\n'
return HttpResponse(string, content_type='text/css')

rawDescription: dynamically generate css content not taking effect

description: Dynamically generate css content not taking effect


code:
# -*- coding: utf-8 -*-
import pyodbc
connStr = (
    r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
    r"DBQ=C:\Users\Gord\Desktop\Test.accdb;"
    )
conn = pyodbc.connect(connStr)
crsr = conn.cursor()
table_list = [x[2] for x in crsr.tables() if x[3]=='TABLE']
for table_name in table_list:
    column_list = [x[3] for x in crsr.columns(table_name)]
    for column_name in column_list:
        print('[{0}].[{1}]'.format(table_name, column_name))
crsr.close()
conn.close()

rawDescription: Can I extract schema information from empty Access tables with Python?

description: Extract schema information from empty Access tables with Python


code:
from graphics import *

def main():
    win = GraphWin('Floor', 500, 500)

    win.setCoords(0.0, 0.0, 10.0, 10.0)
    win.setBackground("yellow")

    # draw grid
    for x in range(10):
        for y in range(10):
            win.plotPixel(x*50, y*50, "blue")

    square = Rectangle(Point(5,5), Point(6,6))
    square.draw(win)
    square.setFill("black")

    win.getMouse()
    win.close()

main()

rawDescription: How to draw grid on window using graphics library in python

description: Draw grid on window using graphics library in python


code:
seqs = ['xyzxyz', 'yzyzyz']
chars = ['x','y','z','xx','xy','xz','yx','yy','yz','zx','zy','zz']

N = len(chars)
out = []
for i, seq in enumerate(seqs):
    M = len(seq)  # if different seqs have different lenghts, this will break!
    tmp = np.array([], dtype=int)
    for c in chars:
        o = np.array([0]*M)
        index = -1
        try:
            while True:
                index = seq.index(c, index+1)
                o[index:(index+len(c))] = 1
        except ValueError:
            pass
        finally:
            tmp = np.r_[tmp, o]
    out.append(tmp)
out = np.array(out)

rawDescription: Python: How to read one element first and followed by two elements?


code:
import glob
glob.glob('./[0-9].*')
glob.glob('*.gif')
glob.glob('?.gif')

rawDescription: Search for a file using a wildcard

description: Search for a file using a wildcard


code:
a = [1, 2]
b = a
del a
a
b

rawDescription: In Python, is use of `del` statement a code smell?


code:
from win32com.shell import shell

def launch_file_explorer(path, files):
    '''
    Given a absolute base path and names of its children (no path), open
    up one File Explorer window with all the child files selected
    '''
    folder_pidl = shell.SHILCreateFromPath(path,0)[0]
    desktop = shell.SHGetDesktopFolder()
    shell_folder = desktop.BindToObject(folder_pidl, None,shell.IID_IShellFolder)
    name_to_item_mapping = dict([(desktop.GetDisplayNameOf(item, 0), item) for item in shell_folder])
    to_show = []
    for file in files:
        if name_to_item_mapping.has_key(file):
            to_show.append(name_to_item_mapping[file])
        # else:
            # raise Exception('File: "%s" not found in "%s"' % (file, path))

    shell.SHOpenFolderAndSelectItems(folder_pidl, to_show, 0)
launch_file_explorer(r'G:\testing', ['189.mp3'])

rawDescription: Launch a GUI process without spawning a black shell window


code:
def addChannelWithName(name):
    channel = Channel(name = name)
    channel.put()
    return channel

class TestChannel(unittest.TestCase):
    @patch("notification.models.Channel")
    def testAddChannelWithNamePutsChannel(self, *args):
        channel = addChannelWithName("channel1")
        self.assertTrue(channel.put.called)

rawDescription: Patch - How to check that a patched class's instance called a class function?


code: train_idx, test_idx = next(iter(skf))

rawDescription: python - sklearn 0.17 and 0.18 - how to retrieve only the first value of an StratifiedKFold object?

description: Python - sklearn 0.17 and 0.18 - how to retrieve only the first value of an StratifiedKFold object


code:
import dis
dis.dis(testAccumEqualPlus)
dis.dis(testAccumPlusEqual)

rawDescription: python plus equals slower

description: Python plus equals slower


code:
import sys

ver = sys.getwindowsversion()
if ver.major == 6 and ver.minor == 1:
    print('Windows 7')
elif ver.major == 6 and ver.minor == 0:
    print('Windows Vista')
elif ver.major == 5 and ver.minor == 0:
    print('Windows XP')

rawDescription: How can I disable use of Python programs on certain operating systems?

description: Disable use of Python programs on certain operating systems


code:
class CustomCache(Cache):
    def _memoize_kwargs_to_args(self, f, *args, **kwargs):
        keyargs, keykwargs = super(CardCache, self) \
            ._memoize_kwargs_to_args(f, *args, **kwargs)

        new_args = []
        for arg in keyargs:
            if isinstance(arg, numbers.Integral):
                arg = long(arg)
            new_args.append(arg)

        return tuple(new_args), keykwargs

rawDescription: Flask-cache generate different keys for int and long parameters


code:
self.cursor.execute("INSERT INTO items (title, url) VALUES (%s, %s)",
                    (item['title'][0], item['link']))

rawDescription: Scrapy Getting Start_Urls

description: Scrapy Getting Start_Urls


code:
# assume selected_job is the job instance
try:
    host = Host.objects.get(name=hostname)
except ObjectDoesNotExist:
    # do something here to handle an unmatched hostname
    pass
host.job = selected_job
host.save()

rawDescription: how to add a instance of a foreign key to an instance of a model that it points to

description: Add a instance of a foreign key to an instance of a model that it points to


code:
import re

s = "reverse 45"
output = re.sub(r'reverse (\d+)', r'reverse(\1)', s)

rawDescription: how do I convert a string into a different format in python?

description: Convert a string into a different format in python


code:
import easygui as eg
infile = eg.fileopenbox(msg='Please locate the csv file',
                    title='Specify File', default='c:\data\det\*.csv',
                    filetypes='*.csv')
refdata = pd.read_csv(infile)

rawDescription: How to get easygui to filter file list

description: Get easygui to filter file list


rawDescription: Python: Get value with xmltodict

description: Python: Get value with xmltodict


code:
#!/usr/bin/env python

from setuptools import setup

setup(
    # GETTING-STARTED: set your app name:
    name='YourAppName',
    # GETTING-STARTED: set your app version:
    version='1.0',
    # GETTING-STARTED: set your app description:
    description='OpenShift App',
    # GETTING-STARTED: set author name (your name):
    author='Your Name',
    # GETTING-STARTED: set author email (your email):
    author_email='example@example.com',
    # GETTING-STARTED: set author url (your url):
    url='http://www.python.org/sigs/distutils-sig/',
    # GETTING-STARTED: define required django version:
    install_requires=[
        'Django==1.8.4',
        'djangorestframework==3.3.2',
    ],
    dependency_links=[
        'https://pypi.python.org/simple/django/',
        'https://pypi.python.org/simple/djangorestframework/',
    ],
 )

rawDescription: Django rest_framework does not work on rhcloud.com


code:
@classmethod
def load(cls, filename):
    with open(filename, 'rb') as bin_object:
        ...
    foo = cls()
    foo.lst1 = lst1
    foo.lst2 = lst2
    ...
    return foo

rawDescription: Instanstiate serialized object from a static method


code:
class VForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(VForm, self).__init__(*args, **kwargs)

        if self.instance.field == 'Y':
            self.fields['field2'] = forms.ChoiceField(
                choices=[(self.instance.field,
                          self.instance.field),], required=True)

rawDescription: How to make a record read-only in a Django form?

description: Make a record read-only in a Django form


code: bar = [x for x in foo if x % 2 == 1]

rawDescription: Does python have a shorthand for this simple task?


code:
from ilogue.fexpect import expect, expecting, run

prompts = []
prompts += expect('What is your name?','John')
prompts += expect('Where do you live?','New York')

with expecting(prompts):
    run('command')

rawDescription: How to get Fabric to automatically (instead of user-interactively) interact with shell commands? Combine with pexpect?

description: Get Fabric to automatically (instead of user-interactively) interact with shell commands? Combine with pexpect


code:
a = []
counter = 0
while counter < 10:
    c = int(raw_input('Enter an integer: '))
    if c % 2 != 0:
        a.append(c)
    counter += 1
print(a)

rawDescription: remove even numbers from a list

description: Remove even numbers from a list


code:
lines = {}

for files in filesInDir:
    sourceFile = open("scanfiles/" + files, "r")
    lines[files] = sourceFile.read().splitlines()

rawDescription: Using a string, to give a name to a new string


code:
from selenium import webdriver
from random import randint
driver = webdriver.Firefox()
driver.get('http://www.python.org')
links = driver.find_elements_by_partial_link_text('')
l = links[randint(0, len(links)-1)]
l.click()

rawDescription: Click on random link in webpage using selenium API for python


rawDescription: Compare 2 dictionary's and subtract the keys


code:
import dateutil.parser
import pytz

tz_str = '''-12 Y
-11 X NUT SST
-10 W CKT HAST HST TAHT TKT
-9 V AKST GAMT GIT HADT HNY
-8 U AKDT CIST HAY HNP PST PT
-7 T HAP HNR MST PDT
-6 S CST EAST GALT HAR HNC MDT
-5 R CDT COT EASST ECT EST ET HAC HNE PET
-4 Q AST BOT CLT COST EDT FKT GYT HAE HNA PYT
-3 P ADT ART BRT CLST FKST GFT HAA PMST PYST SRT UYT WGT
-2 O BRST FNT PMDT UYST WGST
-1 N AZOT CVT EGT
0 Z EGST GMT UTC WET WT
1 A CET DFT WAT WEDT WEST
2 B CAT CEDT CEST EET SAST WAST
3 C EAT EEDT EEST IDT MSK
4 D AMT AZT GET GST KUYT MSD MUT RET SAMT SCT
5 E AMST AQTT AZST HMT MAWT MVT PKT TFT TJT TMT UZT YEKT
6 F ALMT BIOT BTT IOT KGT NOVT OMST YEKST
7 G CXT DAVT HOVT ICT KRAT NOVST OMSST THA WIB
8 H ACT AWST BDT BNT CAST HKT IRKT KRAST MYT PHT SGT ULAT WITA WST
9 I AWDT IRKST JST KST PWT TLT WDT WIT YAKT
10 K AEST ChST PGT VLAT YAKST YAPT
11 L AEDT LHDT MAGT NCT PONT SBT VLAST VUT
12 M ANAST ANAT FJT GILT MAGST MHT NZST PETST PETT TVT WFT
13 FJST NZDT
11.5 NFT
10.5 ACDT LHST
9.5 ACST
6.5 CCT MMT
5.75 NPT
5.5 SLT
4.5 AFT IRDT
3.5 IRST
-2.5 HAT NDT
-3.5 HNT NST NT
-4.5 HLV VET
-9.5 MART MIT'''

tzd = {}
for tz_descr in map(str.split, tz_str.split('\n')):
    tz_offset = int(float(tz_descr[0]) * 3600)
    for tz_code in tz_descr[1:]:
        tzd[tz_code] = tz_offset

date = 'Sun Sep 15, 2013 12:10pm EDT'
dateutil.parser.parse(date, tzinfos=tzd) # => datetime.datetime(2013, 9, 15, 12, 10, tzinfo=tzoffset(u'EDT', -14400))

rawDescription: Python time zone parsing

description: Python time zone parsing


code:
class MyClass(object):
  pass

type(MyClass)
hasattr(MyClass, '__call__')

rawDescription: Difference in type() and hasattr() between Python 3 and Python 2


code:
def __init__(self, parent, id, title, pos, size):
    #...
    self.pages = [PageOne(self.nb)]
    #...

def OnClick(self, event):
    page = self.nb.GetPageCount() + 1
    # Or: page = len(self.pages) + 1

    self.pages.append(PageTwo(self.nb))
    self.nb.AddPage(self.pages[page], "PAGE %d" % page)
    self.pages[page].OnLoad("PAGE %d" % page)

rawDescription: wxpython notebook - creating new pages

description: Wxpython notebook - creating new pages


code:
import numpy as np
a = np.arange(10)
a
a.fill(0)
a

rawDescription: Empty an existing NumPy array

description: Empty an existing NumPy array


code:
from matplotlib.ticker import MaxNLocator

fig = plt.figure()
axes = fig.add_subplot(111)
axes.xaxis.set_major_locator(MaxNLocator(symmetric=True))

upsrt = pd.DataFrame({'DAC3' : pd.Series([-2.1, -1., 0., 1., 2.]),
                      'norm' : pd.Series([5., 3., 6., 8., 2.])})

downsrt = pd.DataFrame({'DAC3' : pd.Series([-2., -1., 0., 1., 2.]),
                        'norm' : pd.Series([3., 7., 3., 6., 7.])})

upsrt.plot(x='DAC3', y='norm', color='red', label='Up',ax=axes)

downsrt.plot(x='DAC3', y='norm', color='blue', label='Down', ax=axes)

plt.show()

rawDescription: Tick labels on x-axis aren't symmetric (Matplotlib)


code: df['result'] = df['actual_credit'].ge(df['min_required_credit']) | np.isclose(df['actual_credit'], df['min_required_credit'])

rawDescription: Comparing floats in a pandas column

description: Comparing floats in a pandas column


code: p = p.encode('utf-8') if isinstance(p,unicode)  else p

rawDescription: Special characters problems using Python unicode


code:
test_json = {
    "a": {
        "b": {
            "c": {
                "d": "foo"
            }
        }
    },
    "1": {
        "2": {
            "3": "bar"
        }
    },
    "a1" : "foo"
}

def searchDict(d, path):
    for k,v in d.iteritems():
        if isinstance(v, dict):
            searchDict(v, path + [k])
        else:
            if v == "foo":
                print(path + [k] + [v])

searchDict(test_json, [])

rawDescription: Python - Return path of all JSON elements that match string


code: plt.hexbin(x, y, cmap=cm.jet, gridsize = 20, extent=[x_min, x_max, y_min, y_max])

rawDescription: making hexbin in matplotlib python fill in empty space on a square axis?

description: Making hexbin in matplotlib python fill in empty space on a square axis


code:
def foo(x, y):
    return x+y

def bar(x, y):
    return foo(x, y)

rawDescription: Understanding the role of closure in decorators and function wrapper arguments


code:
for k, v in myDict2.iteritems():
    myDict1[k] = myDict1.get(k, ()) + v

rawDescription: Updating a python dictionary while adding to existing keys?


rawDescription: How to get a http page using mechanize cookies?

description: Get a http page using mechanize cookies


code:
import threading

command = 'ls -l' #some_command
t = threading.Thread(target=some_function,args=(command,))
t.start()

def some_function(command):
    some_process = pexpect.spawn(command)
    some_process.expect('[pP]assword*')
    some_process.sendline(some_password)
    some_process.expect(pexpect.EOF,timeout=1000)

rawDescription: running a django app on apache with SSL: pexpect spawn/expect doesn't work

description: Running a django app on apache with SSL: pexpect spawn/expect doesn't work


code:
def takes(*args):
    def _takes(fcn):
        fcn.params = args
        return fcn
    return _takes

@takes("time", "temp", "time")
def do_stuff(start_time, average_temp, stop_time):
    pass

rawDescription: What's a good way to provide additional decoration/metadata for Python function parameters?


code:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib

df = pd.DataFrame(data = BabyDataSet, columns=['Names', 'Births'])

matplotlib.style.use('ggplot')

ax = df['Births'].plot(kind = 'bar')
ax.set_xticklabels(df.Names)

ax.annotate('Most Popular Name: {}: {} births'.format(df.max().Names, df.max().Births),
        xy=(1, 1),
        xytext=(1, 800))

ax.set_title("Number of Births by Name")
ax.set_ylabel("No. Births")

plt.show()

rawDescription: How to plot using matplotlib and pandas?

description: Plot using matplotlib and pandas


code:
headers = {'content-type': 'text/xml'}
r1 = requests.post("http://localhost:8080/geoserver/rest/workspaces",
    auth=('admin', 'geoserver'),
    data='<workspace><name>acme</name></workspace>',
    headers=headers)

rawDescription: Converting geoserver cURL to python requests


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

x = np.linspace(0, 100, 101)
y = x

plt.plot(x, y, "r", linestyle = "dashed", dashes=(10,5)) # short gap
plt.plot(x, y+5, "r", linestyle = "dashed", dashes=(10,20)) # long gap
plt.plot(x, y+10, "r", linestyle = "dashed", dashes=(5,5,5,5,5,15,15,5,15,5,15,15,5,5,5,5,5,35)) # SOS
plt.show()

rawDescription: Set the space size of matplotlibs linestyle "dashed"


code:
x = [5,7,11,15,16,17,18]
y = [8, 5, 8, 9, 17, 18, 25]
cov = np.cov(x, y)
lambda_, v = np.linalg.eig(cov)
lambda_ = np.sqrt(lambda_)
from matplotlib.patches import Ellipse
import matplotlib.pyplot as plt
ax = plt.subplot(111, aspect='equal')
for j in xrange(1, 4):
    ell = Ellipse(xy=(np.mean(x), np.mean(y)),
                  width=lambda_[0]*j*2, height=lambda_[1]*j*2,
                  angle=np.rad2deg(np.arccos(v[0, 0])))
    ell.set_facecolor('none')
    ax.add_artist(ell)
plt.scatter(x, y)
plt.show()

rawDescription: Creating a Confidence Ellipses in a sccatterplot using matplotlib


code:
def connect_sql(instance, database = None):
    from google.storage.speckle.python.tool import google_sql
    database = google_sql.DatabaseConfig(instance, database)

    sql_cmd_config = google_sql.config.SQLCmdConfig(None)
    sql_cmd_config.add('__googlesql__', instance, None, None, database,
                    google_sql.GoogleSqlDriver.NAME, None, None)
    sql_cmd = google_sql.GoogleSqlCmd(sql_cmd_config)
    sql_cmd.set_database(instance)

    sql_cmd.preloop()
    return sql_cmd._SQLCmd__db

rawDescription: Access Google Cloud SQL from python in local machine?


code:
def flash():
  GPIO.output(channel, not GPIO.input(channel))
  sleep(1)

while True:
  flash()

rawDescription: Raspberry PI for loop to flash LED not working


code:
def loopInLabel(self, newsfeedData):
    lines = []
    for item in newsfeedData:
        try:
            a = ("Name: " + item['name'] + '\n' + "Message: " + item['message'] + '\n' + "Description: " + item['description'] + '\n')
            lines.append(a)
        except KeyError:
            pass
    return " | ".join(lines)

rawDescription: For statement in label Python Tkinter

description: For statement in label Python Tkinter


code:
from django.contrib.auth.models import User

User.objects.create_user(username='somename', password='somepass')

rawDescription: Django User Creation without Form

description: Django User Creation without Form


code:
friend_likes = graph.get('me?fields=friends.fields(likes)')
friend_likes['friends']

rawDescription: facepy: How do I get a list, by friend, of pages liked by my friends using facepy?

description: Facepy: How do I get a list, by friend, of pages liked by my friends using facepy


code:
class Fooset(set):
    def __init__(self, s=(), foo=None):
        super(Fooset,self).__init__(s)
        if foo is None and hasattr(s, 'foo'):
            foo = s.foo
        self.foo = foo

    @classmethod
    def _wrap_methods(cls, names):
        def wrap_method_closure(name):
            def inner(self, *args):
                result = getattr(super(cls, self), name)(*args)
                if isinstance(result, set) and not hasattr(result, 'foo'):
                    result = cls(result, foo=self.foo)
                return result
            inner.fn_name = name
            setattr(cls, name, inner)
        for name in names:
            wrap_method_closure(name)

Fooset._wrap_methods(['__ror__', 'difference_update', '__isub__',
    'symmetric_difference', '__rsub__', '__and__', '__rand__', 'intersection',
    'difference', '__iand__', 'union', '__ixor__',
    'symmetric_difference_update', '__or__', 'copy', '__rxor__',
    'intersection_update', '__xor__', '__ior__', '__sub__',
])

rawDescription: What is the correct (or best) way to subclass the Python set class, adding a new instance variable?


code:
class Album(models.Model):
    name = models.CharField(max_length=100)
    order = models.IntegerField(default=1000)

    class Meta:
        ordering = ('order', 'name')

rawDescription: Django: create custom order in model

description: Django: create custom order in model


code:
df['Name'].isin(['Alice', 'Bob'])
df[df.Name.isin(['Alice', 'Bob'])]

rawDescription: Efficiently select rows that match one of several values in Pandas DataFrame


rawDescription: pandas groupby numeric functions coerce numeric to object when DataFrame contains object

description: Pandas groupby numeric functions coerce numeric to object when DataFrame contains object


rawDescription: Python Basics – slicing a long string and combine the sliced in wanted pieces


code: #include "qrencode.h"

rawDescription: Adding a library to C

description: Adding a library to C


code:
class OldNonObjectClass:
    a, b = 2, 3

    @property
    def c(self):
        return self.b + self.a

class SubClass(OldNonObjectClass, object):
    x, y = 4, 5

    @property
    def z(self):
        return self.x + self.y

a = OldNonObjectClass()
print(a.c)
#5
a.c = 2
print(a.c)
#2

b = SubClass()
print(b.z)
#5
b.z = 2
# AttributeError: can't set attribute

rawDescription: How to use property for a class that are not derived from object

description: Use property for a class that are not derived from object


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#spyder
from Tkinter import *
import tkFileDialog

def curdir():
    cdir = tkFileDialog.askdirectory(parent=finestra, initialdir="/home")
    v.set(cdir)

#MAIN
finestra = Tk()
finestra.title("Creacio de fitxer comprimit")
f=Frame(finestra)
f.pack(side=TOP)

b=Button(f,text='Escollir directori treball',command=curdir)
b.pack(side=LEFT,anchor=W)

v=StringVar()
v.set("/home")
e1=Entry(f,width=35,textvariable=v)

e1.pack(side=LEFT)

l1=Label(f,text="Fitxers a incorporar al fitxer tar:")
l1.pack(side=TOP,anchor=N,padx=90)

f1=Frame(finestra)
f1.pack(side=TOP,anchor=NW)

l2=Label(f1,text="Llista:")
l2.pack(side=LEFT)

br=Button(f1,text='Reomplir')
br.pack(side=LEFT)
bo=Button(f1,text='Ocultar no seleccionats')
bo.pack(side=LEFT)
bos=Button(f1,text='Ocultar seleccionats')
bos.pack(side=LEFT)

Label(f1,text="\t\tCompresió").pack(side=LEFT)
rb1=Radiobutton(f1,text="cap").pack(side=LEFT)
rb2=Radiobutton(f1,text="gzip",value="gzip").pack(side=LEFT)
rb3=Radiobutton(f1,text="bzip2",value="bzip2").pack(side=LEFT)
rb4=Radiobutton(f1,text="xz",value="xz").pack(side=LEFT)

f2=Frame(finestra)
f2.pack(side=LEFT,anchor=W)
f3=Frame(finestra)
f3.pack(side=LEFT)

Label(f3,text="Tots:").pack(side=TOP)
tots=Button(f3,text=">>>").pack(side=TOP)
Label(f3,text="Als seleccionats:").pack(side=TOP)
af=Button(f3,text="-->").pack(side=TOP)
qt=Button(f3,text="<--").pack(side=TOP)
Label(f3,text="Tots:").pack(side=TOP)
cap=Button(f3,text="<<<").pack(side=TOP)

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

listbox = Listbox(f2, bd=0, yscrollcommand=scrollbar.set,width=55)
listbox.pack(side=LEFT)

scrollbar.config(command=listbox.yview)

mainloop( )

rawDescription: Python tkinter GUI not showing properly

description: Python tkinter GUI not showing properly


code:
from PIL import Image
im = Image.open('ball.png')
from io import BytesIO
buffer = BytesIO()
im.save(buffer, format='png')
buffer.getvalue()

rawDescription: Python variables and files

description: Python variables and files


code: displayname = firstname + lastname or username

rawDescription: Python - Idiom to check if string is empty, print default


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

months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')

# Some random data for nyears from minyear
nyears = 8
nmonths = len(months)
minyear = 2005
monthly_counts = np.random.randint(low=2, high=15, size=(nyears,nmonths))

fig, ax = plt.subplots()
ind = np.arange(nyears)
width = 0.45
# Random colors for the months
c = np.random.rand(nmonths,3,1)

p = []
for imonth in range(nmonths):
    p.append(ax.bar(ind, monthly_counts[:,imonth], width,
                    bottom=np.sum(monthly_counts[:,:imonth], axis=1),
                    color=c[imonth], alpha=0.8)
            )

# Set x axis ticks and labels
ax.set_xticks(ind + width/2)
ax.set_xticklabels([str(minyear+i) for i in ind])

# Locate legend outside axes plot area
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax.legend([pl[0] for pl in p], months, loc='center left', bbox_to_anchor=(1, 0.5))

plt.show()

rawDescription: How to generate a bar chart of occurrences per year in matplotlib python?

description: Generate a bar chart of occurrences per year in matplotlib python


code: c.linkURL('http://google.com', (inch, inch, 1*inch, 1*inch), relative=1)

rawDescription: What is the simplest way to add a hyperlink to a canvas element in ReportLab?


code:
seq_name = seq_record.id.split(":")[0]  # Get the "chr1"
for i in range(len(seq_record.seq) - 4):
    seq_coords = "{}-{}".format(i + 1, i + 5)  # Make the coordinates

    f.write(">" + seq_name + ":" + seq_coords + "\n")  # Print them both

rawDescription: Python: How to output the FASTA header or chromosome index figure according to the location?


rawDescription: Python json.dumps(<val>) to output minified json?


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

    def __eq__(self, other):
        if isinstance(other, Foo):
            return other.name == self.name
        return self.name == other

rawDescription: How to search objects in Python List using __contains__ / "in" keyword?

description: Search objects in Python List using __contains__ / "in" keyword


code:
if(classes[max_index] == y[q]):
    corr += 1

rawDescription: Naive Bayes Classifier: Only get 30-40% accuracy on iris data set


code:
from tkinter import *
from tkinter import ttk

root = Tk()

l = ttk.Label(text="Not blue anymore")

lf = ttk.Labelframe(root, labelwidget=l)
lf.pack()

label = ttk.Label(lf, text="label")
label.pack()

root.mainloop()

rawDescription: How do I change ttk.LabelFrame's blue header label to black in python's tkinter 8.5

description: Change ttk.LabelFrame's blue header label to black in python's tkinter 8.5


code:
import matplotlib.pyplot as plt
from matplotlib import cm
from math import sin

x=range(10)
y=[sin(i) for i in x]
#colors=np.linspace(0,1,10)
B=[1.29,1.27,1.46,0.91,0.56,0.99,1.00,0.37,1.24,1.23]

cs = plt.scatter(x,y,c=B,cmap=cm.jet,vmin=0.,vmax=2.)
plt.colorbar(cs)
plt.show()

rawDescription: Scatter plot colors corresponding to a value


code:
def findAllCapsUrls2(page_contents):
    """ returns a list of URLs that have ALL CAPS text, given
    the HTML from a page. Uses a combo of RE and BeautifulSoup
    to handle malformed pages.
    """
    # get all anchors on page using regex
    p = r']*>(.*?(?=))'
    re_urls = re.compile(p, re.DOTALL)
    all_a = re_urls.findall(page_contents)

    # if the text for the anchor is ALL CAPS then add the link to good_urls
    good_urls = []
    for a in all_a:
        href = a[0]
        a_content = a[1]
        a_soup = BeautifulSoup.BeautifulSoup(a_content)
        text = ''.join([s.strip() for s in a_soup.findAll(text=True) if s])
        if text and text.upper() == text:
            good_urls.append(href)

    return good_urls

rawDescription: How to find links with all uppercase text using Python (without a 3rd party parser)?

description: Find links with all uppercase text using Python (without a 3rd party parser)


code:
lats_fine = np.arange(lats[0], lats[-1], 0.25) # 0.25 degree fine grid
lons_fine = np.arange(lons[0], lons[-1], 0.25)
lons_sub, lats_sub = np.meshgrid(lons_fine, lats_fine)

rawDescription: regrid netcdf data to finer resolution in python

description: Regrid netcdf data to finer resolution in python


code: (lambda s: {"len" : len(s), "slice" : s[2:4]})(u'hello')

rawDescription: Build dict applying expressions to an object


code: X_closed = np.append(X,X[[0]],axis = 0)

rawDescription: Python add last row and column of 2darray to last positions - Polar Contour plot


code:
import ast

with open(sourcefilename, 'r') as source:
    tree = ast.parse(source.read(), sourcefilename)

rawDescription: Looking for a way to intrepret python code structure


code:
# define the range of x,y,z
x_range = numpy.linspace(x_min,x_max,x_num)
y_range = numpy.linspace(y_min,y_max,y_num)
z_range = numpy.linspace(z_min,z_max,z_num)

# create arrays x,y,z in the correct dimensions
# so that they create the grid
x,y,z = numpy.ix_(x_range,y_range,z_range)

# calculate the function of x, y and z
sinxyz = numpy.sin(x+y+z)

rawDescription: How can I create a numpy array holding values of a multi-variable function?

description: Create a numpy array holding values of a multi-variable function


code:
filename = 'base.db'

path = os.path.join('z:/', filename) if os.name == 'nt' else filename

con = lite.connect(path)

rawDescription: SQLite over LAN

description: SQLite over LAN


code:
import os
for filename in os.listdir('dirname'):
     callthecommandhere(blablahbla, filename, foo)

rawDescription: Using Python to execute a command on every file in a folder


code:
def traverse(path):
    for root, dirs, files in os.walk(path):
        print(root)

        # if you want files too:
        for f in files:
            print(os.path.join(root, f))

rawDescription: Print the pathnames of folders and their subfolder recursively


code:
import dj_database_url
DATABASES['default'] =  dj_database_url.config(default='postgres://foo:bar@somehost.amazonaws.com:5432/somedb')

rawDescription: How to configure Django to use Heroku Dev Postgre while local?

description: Configure Django to use Heroku Dev Postgre while local


code: contents = request.POST.keys()[0] + "=" + request.POST.values()[0]

rawDescription: Using curl with --data-urlencode and fetching the content in django


code:
bypatient_date = pd.DataFrame(byencounter.groupby('patient_id').\
                              agg({'timestamp' : [np.min, np.max]})).reset_index(drop=True)

bypatient_date.columns = bypatient_date.columns.droplevel(0)
bypatient_date['datediff'] = bypatient_date['amax'] - bypatient_date['amin']

rawDescription: How to access the values of aggregate functions in Python

description: Access the values of aggregate functions in Python


code: str = re.sub(r'(options) (\S+)', r'\2\n    \1', re.sub(r'([ \t =,])/', replace_text, text))

rawDescription: Python text processing with regular expression


rawDescription: Iterate through multiple sorted lists in order


code:
class SaleOrder(orm.Model):
    _inherit = 'sale.order'

    def _amount_all_wrapper(self, cr, uid, ids, field_name, arg, context=None):
        """ Wrapper because of direct method passing as parameter for function fields """
        return self._amount_all(cr, uid, ids, field_name, arg, context=context)

    def _amount_all(self, cr, uid, ids, field_name, arg, context=None):
        res = super(SaleOrder, self)._amount_all(cr, uid, ids, field_name, arg, context=context)
        currency_pool = self.pool.get('res.currency')
        for order in self.browse(cr, uid, ids, context=context):
            line_amount = sum([line.price_subtotal for line in order.order_line if line.is_delivery])
            currency = order.pricelist_id.currency_id
            res[order.id]['amount_delivery'] = currency_pool.round(cr, uid, currency, line_amount)
        return res

rawDescription: How to get the value of amount_total of sale.order from another model?

description: Get the value of amount_total of sale.order from another model


code: pBits = im.convert("RGBA").tostring("raw", "RGBA")

rawDescription: Python PIL Image.tostring()

description: Python PIL Image.tostring()


code:
indexes = sorted(range(len(File_2Column)), key=lambda i: File_1Col4[i])
sortedFile_2Col = [File_2Column[i] for i in indexes]
# you can repeat this line for all the columns you want to be sorted by that order

rawDescription: How to sort a file according to a column in another file?

description: Sort a file according to a column in another file


code:
import _thread

a_lock = _thread.allocate_lock()

def certainFunction():
    with a_lock:
        print("Here's the code that you don't want to execute at the same time as onSpecificKeyCall()")

def onSpecificKeyCall():
    with a_lock:
        print("Here's the code that you don't want to execute at the same time as certainFunction()")

rawDescription: How to, in Python, ignore certain/all keypresses while function executing in program on Macintosh


code:
def user():
    if request.args(0) == 'register':
        for field in ['first_name', 'last_name', 'email']:
            db.auth_user[field].readable = db.auth_user[field].writable = False
    return dict(form=auth())

rawDescription: Skip entering email for registration in web2py


code:
for f in next_file(file_path):
    yield f

rawDescription: generate file in a path, but sometimes got a generator returning

description: Generate file in a path, but sometimes got a generator returning


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

x = np.linspace(0, 1.6, 100)
y = np.exp(-x*3)*x
fig, axs = plt.subplots(nrows=2, sharex=True)
axs[0].plot(x, y)
axs[1].plot(x[::-1], y)
plt.xlim(x.min(), x.max())
plt.show()

rawDescription: Invert relationship between units and plotted data Matplotlib


code:
def view(request, var_from_one_url="some_default", var_from_another="some_default"):
    pass

rawDescription: DJANGO: Can I write "def view(request, x or y)"?


code:
import os
from subprocess import Popen, PIPE

p = Popen("some_program.exe", stdin=PIPE)
p.communicate(os.linesep.join(["name", "age"]))

rawDescription: Communicating with a windows executables commandline gui via python


code:
import os
import subprocess

LOGFILE = 'somefile.log'

if not os.path.exists(LOGFILE):
    os.mkfifo(LOGFILE)
proc = subprocess.Popen([YOUR_PROGRAM])
with open(LOGFILE) as log:
    data = log.read()  # process your data

proc.wait()

rawDescription: Intercept C function call from Python

description: Intercept C function call from Python


code:
try:
    # Python 2.x
    import BaseHTTPServer as server
    from StringIO import StringIO as IO
except ImportError:
    # Python 3.x
    from http import server
    from io import BytesIO as IO

class MyHandler(server.BaseHTTPRequestHandler):
    """Custom handler to be tested"""
    def do_GET(self):
        # print just to confirm that this method is being called
        print("executing do_GET") # just to confirm...

        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

        # Here's where all the complicated logic is done to generate HTML.
        # For clarity here, replace with a simple stand-in:
        html = "
hello world
"

        self.wfile.write(html.encode())

def test_handler():
    """Test the custom HTTP request handler by mocking a server"""
    class MockRequest(object):
        def makefile(self, *args, **kwargs):
            return IO(b"GET /")

    class MockServer(object):
        def __init__(self, ip_port, Handler):
            handler = Handler(MockRequest(), ip_port, self)

    # The GET request will be sent here
    # and any exceptions will be propagated through.
    server = MockServer(('0.0.0.0', 8888), MyHandler)

test_handler()

rawDescription: Python: How to unit test a custom HTTP request Handler?


rawDescription: How to create datetime object from "16SEP2012" in python

description: Create datetime object from "16SEP2012" in python


code:
sql_command ='''SELECT Grade From GRADES where Student_Number='''+str(id)
sql_command+=''' AND Course_ID IN ('''+ ','.join(list) + ''')'''

rawDescription: Select column in values , in python

description: Select column in values , in python


code:
import re, copy

myMassage = [(re.compile('<!-([^-])'), lambda match: '<!--' + match.group(1))]
myNewMassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE)
myNewMassage.extend(myMassage)

BeautifulSoup(badString, markupMassage=myNewMassage)
# Foo<!--This comment is malformed.-->Bar<br />Baz

rawDescription: How can I strip comment tags from HTML using BeautifulSoup?

description: Strip comment tags from HTML using BeautifulSoup


rawDescription: : for displaying all elements in a multidimensional array in python 3.1


code: c = re.compile("(?P<%s>%s)" % (fname,f.__doc__), re.VERBOSE | self.reflags)

rawDescription: Why does PLY treat regular expressions differently from Python/re?


code:
def foo(a):
    if a:
        globals()['g'] = 10
    else:
        g = 20

rawDescription: What's the logic behind this python global scoping magic?


code:
import datetime
d = datetime.datetime.now()
d.isoweekday() in range(1, 6)
d.hour in range(10, 15)
d.minute==30

rawDescription: How do I check if it's Monday to Friday and the time is between 10 AM to 3 PM?

description: Check if it's Monday to Friday and the time is between 10 AM to 3 PM


code: u = u.where(...)

rawDescription: How to write a generative update in SQLAlchemy

description: Write a generative update in SQLAlchemy


code:
def dict_clean(items):
    result = {}
    for key, value in items:
        if value is None:
            value = 'default'
        result[key] = value
    return result

dict_str = json.dumps(my_dict)
my_dict = json.loads(dict_str, object_pairs_hook=dict_clean)

rawDescription: Replace None in a python dictionary

description: Replace None in a python dictionary


code:
# weapon.py
class Weapon:
    def __init__(self, name, dmg):
        self.name = name
        self.dmg  = dmg

    def attack(self, target):
        target.health -= self.dmg

# fighter.py
class Fighter:
    def __init__(self, name, weapon=None):
        self.name   = name
        self.weapon = weapon

    def attack(self, target):
        if self.weapon is None:
            # punch him
            target.health -= 2
        else:
            self.weapon.attack(target)

rawDescription: Calling a method from another class in Python


code:
d = [{'email': u'123@gmail.com', 'name': u'xxx'}, {'email': u'abc@gmail.com', 'name': u'xxx1'}, {'email': u'xyz@gmail.com', 'name': u'xxx2'}]
new_d = [{k: v.encode("utf-8") for k, v in elem.items()} for elem in d]
new_d

rawDescription: How to remove ('u')unicode from list of dictionaries?

description: Remove ('u')unicode from list of dictionaries


code:
obj1 = input(...)

while obj1 not in ('a', 'b'):
    obj1 = input("Invalid. Enter again: ")

if obj1 == 'a':
    ...
elif obj1 == 'b':
    ...

rawDescription: Python Text Adventure Loop

description: Python Text Adventure Loop


code:
@lru_cache(maxsize=20)
def my_expensive_function(x, y):
    # my expensive logic here
    return result

rawDescription: Homemade tiny memcache

description: Homemade tiny memcache


code:
print("True" if 1 else "False")
print("True" if 0 else "False")
print("True" if 0.0 else "False")
print("True" if 123.456 else "False")
print("True" if "hello" else "False")
print("True" if "" else "False")
print("True" if [1,2,3] else "False")
print("True" if [] else "False")
print("True" if [[]] else "False")

rawDescription: Python Boolean Values

description: Python Boolean Values


code:
from collections import Counter
for letter, count in Counter("aaassd").items():
    print("letter", letter, "count", count)

rawDescription: Python - Count letters in random strings


code:
character= get_object_or_404(Character, pk=character_id)
InventoryInlineFormSet = inlineformset_factory(Character, Inventory, max_num=1)
classificationformset = ClassificationInlineFormSet(instance=character)

rawDescription: Handling an "Inventory" (complex associations) with django + appengine


code: {id:x for x,y in myDict.iteritems() for id in y}

rawDescription: Assign single value to a single key from dictionary key with multiple values


code:
from pyspark.sql.functions import *
from pyspark.sql.types import *

def getter(column, index):
    return column[index]

getterUDF = udf(getter, StringType())

df.select(getterUDF(split(df.http_request, '/').alias('http'), lit(1)))

rawDescription: Select array element from Spark Dataframes split method in same call?


code:
p = subprocess.Popen(..., stderr=subprocess.PIPE)
fd = p.stderr.fileno()
my_stderr = os.fdopen(os.dup(fd), 'rU', new_bufsize)
os.close(fd)
# use my_stderr from here on

rawDescription: subprocess.Popen: Different buffering for stdin, stdout, stderr?

description: Subprocess.Popen: Different buffering for stdin, stdout, stderr


code: points = [(i // sy, i % sy) for i in random.sample(xrange(sx*sy), n)]

rawDescription: How to efficiently draw exactly N points on screen?

description: Efficiently draw exactly N points on screen


code:
import os
import glob

searchTerm = "China"

#create output file in which we'll store all of the data that contains the word of interest
out = open("foundHits.txt", "w")

hitCount = 0

for csv in glob.glob("C:\\Users\\Douglas\\Desktop\\potato\\*.csv"):
    openCsv = open(csv, "r")
    readCsv = openCsv.read()

    #split each row into a string within the list "splitCsv"
    splitCsv = readCsv.split("\n")

    #for each row in the current csv
    for row in splitCsv:

        #split each row on the phrase "PM ET", which separates your metadata from the text data you want to scan
        splitRow = row.split("PM ET")

        #determine whether the string of interest appears in what I take to be the data of interest

        #use this if condition in order to prevent the script from breaking if it encounters a row that doesn't contain "PM ET"
        if len(splitRow) > 1:

            #split each time you encounter that word
            splitOnTerm = splitRow[1].split(searchTerm)

            searchTermInstances = len(splitOnTerm) - 1

            #print row for review
            out.write(str(searchTermInstances) + "\t" + str(row) + "\n")

rawDescription: Using python to read cells and score rows in a folder of csv files with multiple rows


code:
import urllib2
import urllib
import os
import subprocess
import json

from websocket import create_connection

def refresh_page(url):
    data = json.load(urllib2.urlopen('http://localhost:9222/json'))

    found_page = False
    for page in data:
        if page['url'].lower() == url.lower():
            found_page = True
            websocketURL = page['webSocketDebuggerUrl']
            ws = create_connection(websocketURL)

            obj = {  "id": 0,
                     "method": "Page.reload",
                     "params":
                     {
                       "ignoreCache": True,
                       "scriptToEvaluateOnLoad": ""
                     }
                  }

            dev_request = json.dumps(obj)
            ws.send(dev_request)
            result =  ws.recv()
            ws.close()
    if not found_page:
        raise Exception("No pageFound")

def open_or_refresh(file_name):
    file_name = "".join ( [f if f in r'\/:*?"<>|' else  urllib.quote(f) for f in file_name] )
    file_name = 'file:///' + file_name.replace('\\', '/')
    file_name = file_name.encode('ascii', 'ignore')
    try:
        refresh_page(file_name)
    except:
        cmd = (r'"%(LOCALAPPDATA)s\Google\Chrome\Application\chrome.exe"'%os.environ
               + r' --remote-debugging-port=9222  "%s"' % file_name)
        subprocess.Popen(cmd)

open_or_refresh(r"C:\test.html")
open_or_refresh(r"C:\test.html")

rawDescription: windows chrome refresh tab 0(or current tab) via command line

description: Windows chrome refresh tab 0(or current tab) via command line


code:
import os

# Open file with a bunch of keywords
with open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'r') as inputkeywordsfile:

    # Read all lines into a list and retain the first one
    keywords = inputkeywordsfile.readlines()
    keyword = keywords[0].strip()

with open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'w') as outputkeywordsfile:
    for w in keywords[1:]:
        outputkeywordsfile.write(w)

rawDescription: Reading lines from text file and deleting them each time the script is run


code:
import sys
from multiprocessing.managers import SyncManager
from functools import partial
import multiprocessing
from Queue import Queue as _Queue

class Queue(_Queue):
    """ A picklable queue. """
    def __getstate__(self):
        # Only pickle the state we care about
        return (self.maxsize, self.queue, self.unfinished_tasks)

    def __setstate__(self, state):
        # Re-initialize the object, then overwrite the default state with
        # our pickled state.
        Queue.__init__(self)
        self.maxsize = state[0]
        self.queue = state[1]
        self.unfinished_tasks = state[2]

def get_q(q):
    return q

class JobQueueManager(SyncManager):
    pass

def make_server_manager(port, authkey):
    job_q = Queue()
    result_q = Queue()

    job_q.put("hey")
    JobQueueManager.register('get_job_q', callable=partial(get_q, job_q))
    JobQueueManager.register('get_result_q', callable=partial(get_q, result_q))

    manager = JobQueueManager(address=('', port), authkey=authkey)
    #manager.start()
    print('Server started at port %s' % port)
    return manager

def make_client_manager(port, authkey):
    JobQueueManager.register('get_job_q')
    JobQueueManager.register('get_result_q')
    manager = JobQueueManager(address=('localhost', port), authkey=authkey)
    manager.connect()
    queue = manager.get_job_q()
    print("got queue {}".format(queue))
    print(queue.get_nowait())

if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "--client":
        make_client_manager(50000, 'abcdefg')
    else:
        manager = make_server_manager(50000, "abcdefg")
        server = manager.get_server()
        server.serve_forever()

rawDescription: Can't pickle <class '__main__.JobQueueManager'>


code:
def cut(ls, n):
    if not ls:  # base
        return []
    return (ls[:1] if ls[0] < n else []) + cut(ls[1:], n)  # peeling + rest

rawDescription: Recursive functions and lists

description: Recursive functions and lists


code: sorted_keys = sorted(concurrencydict.keys(), key=itemgetter(*sort_columns))

rawDescription: Sorting based on a variable number of sort keys input after execution


code: gtk.ListStore(*[str] * len(menu))

rawDescription: How to call a function with n parameters, with n set dynamically?

description: Call a function with n parameters, with n set dynamically


code:
def process_single_line(a_canvas, line_of_pattern, left, top, size):
    x = left
    y = top

    for char in line_of_pattern:
        if char.isdigit():
            type_of_tile = int(char)
            draw_tile (a_canvas, type_of_tile, x, y, size)

        x += size

rawDescription: Python nested loop to identify characters in string of text


code:
import numpy as np

def some_function(x):
    return 3*x

input = np.ones([10,26])
input = np.hstack([input,np.empty([input.shape[0],1])])
for row in input:
    row[-1] = some_function(row[0])

output = input

rawDescription: How to get figure for web traffic + how to append column to numpy array?

description: Get figure for web traffic + how to append column to numpy array


code:
num = 3.444
int(num)

rawDescription: Truncate all numbers after decimal

description: Truncate all numbers after decimal


rawDescription: Python regexp replace 'a_1_1' to 'p.get("a_1_1", 0)'


code:
import sqlite3
from Bio import SeqIO

db = sqlite3.connect("./db")

c = db.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS map (k text unique, v text)''')
db.commit()

def keys(db):
    cursor = db.cursor()
    return cursor.execute("""SELECT k FROM map""").fetchall()

def get(key, db, default=None):
    cursor = db.cursor()
    result = cursor.execute("""SELECT v FROM map WHERE k = ?""", (key,)).fetchone()
    if result is None:
        return default
    return result[0]

def save(key, value, db):
    cursor = db.cursor()
    cursor.execute("""INSERT INTO map VALUES (?,?)""", (key, value))
    db.commit()

with open('uniref90.fasta') as fasta_file:
    for seq_record in SeqIO.parse(fasta_file, 'fasta'):
       header = seq_record.id
       uniID = header.split('_')[1]
       seqs = str(seq_record.seq)
       save(uniID, seqs, db)

rawDescription: Fastest way to read large file(>8GB) and dump data into dictionary and load it again


code:
from collections import Counter

data = ['foo', 'bar', 'foobar']

counts = Counter()
for line in data:
    counts.update(list(enumerate(line, start=1)))

# count of letter 'o' in the 3rd column:
print(counts[(3, 'o')])
print(counts)

# 2
# Counter({
#   (1, 'f'): 2, (2, 'o'): 2, (3, 'o'): 2, (5, 'a'): 1,
#   (6, 'r'): 1, (3, 'r'): 1, (1, 'b'): 1, (2, 'a'): 1,
#   (4, 'b'): 1
# })

rawDescription: How to count the no. of occurrence of characters in a column input of CSV?

description: Count the no. of occurrence of characters in a column input of CSV


code:
from ctypes import Structure, c_int, POINTER, CDLL
from ctypes.util import find_library

__all__ = ["get_taken_values", "Result"]

libc = CDLL(find_library("c"))
libmy_library = CDLL("./my_library.so")

class Result(Structure):
    _fields_ = [
        ("position", c_int),
        ("taken", POINTER(c_int)),
        ("size", c_int)
    ]

    def __str__(self):
        return "result(position={}, taken={})".format(
            self.position, self.taken[:self.size])

    def __del__(self):
        libc.free(self.taken)

get_taken_values = libmy_library.get_taken_values
get_taken_values.argtypes = ()
get_taken_values.restype = Result

if __name__ == "__main__":
    result = get_taken_values()
    print("position is {} and value at position is {}".format(
        result.position, result.taken[result.position]))
    print(result)

rawDescription: Free calloc in shared library using ctypes


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)

    def changeEvent(self, event):
        if event.type() == QtCore.QEvent.WindowStateChange:
            if self.windowState() & QtCore.Qt.WindowMinimized:
                print('changeEvent: Minimised')
            elif event.oldState() & QtCore.Qt.WindowMinimized:
                print('changeEvent: Normal/Maximised/FullScreen')
        QtGui.QWidget.changeEvent(self, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.resize(300, 300)
    window.show()
    sys.exit(app.exec_())

rawDescription: pyqt event trigger on click of minimze button

description: Pyqt event trigger on click of minimze button


code:
with open('C://file.txt') as filein, open('C://fout.txt','w') as fileout:
    for line in filein:
        line=line.replace("'","")
        fileout.write(line)

rawDescription: remove single quote from text with python

description: Remove single quote from text with python


code:
def ndarray_to_opentsdb_series(frame, table, **tags):
    tags_str = ' '.join('{k}={v}'.format(k=k, v=v) for k, v in tags.items())
    indices = frame.index.tolist()
    columns = frame.columns.tolist()
    df = frame.apply(lambda s: ['%d %d %s' % (indices[i], e, tags_str) for i, e in enumerate(s)], axis=0, raw=True)
    df = df.apply(lambda s: ['%s.%d %s' % (table, columns[i], e) for i, e in enumerate(s)], axis=1, raw=True)
    flat = [e for l in df.values.tolist() for e in l]
    return '\n'.join(flat)

rawDescription: Convert big pandas DataFrame efficiently


code:
branches = [ref for ref in repo.refs.keys("refs/heads/") if
            any((True for commit in repo.get_walker(include=[repo.refs[ref]])
                 if commit.id == YOURSHA))]

rawDescription: Check which branches contain a specific git commit sha using Python dulwich?


code: result = tuple([str(col_value) for col_value in result])

rawDescription: SqlAlchemy get all strings (don't cast to boolean or datetime)


code:
config.include('pyramid_jinja2')

@view_config(..., renderer='myapp:templates/home.jinja2')
def view(request):
    return {}

rawDescription: Pyramid Chameleon base template orientation


code:
img = cv2.imread(path1)
template = cv2.imread(path2)
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR','cv2.TM_CCORR_NORMED',     'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
for i in range(len(methods)):
    result[i] = cv2.matchTemplate(img,template,methods[i])
    print ("Method {}  : Result{}") .format(method[i],result[i])

rawDescription: Built in functions available in opencv2 python to find distance between to images


code:
ax = plt.subplot(111)

lo = ax.scatter(random(10), random(10), marker='x', color=colors[0])
ll = ax.scatter(random(10), random(10), marker='o', color=colors[0])
...

plt.legend((lo, ll, l, a, h, hh, ho),
       ('Low Outlier', 'LoLo', 'Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'),
       scatterpoints=1,
       loc='center left',
       bbox_to_anchor=(1, 0.5),
       ncol=3,
       fontsize=8)

rawDescription: How to create out side legend in scatter plot(Matplotlib)

description: Create out side legend in scatter plot(Matplotlib)


rawDescription: Split Python list of strings into seperate lists based on character


code:
#!/usr/bin/env python

import time

from twisted.web import http
from twisted.internet import protocol
from twisted.internet import reactor
from twisted.internet import defer

def wait(seconds, result=None):
    """Returns a deferred that will be fired later"""
    d = defer.Deferred()
    reactor.callLater(seconds, d.callback, result)
    return d

class StreamHandler(http.Request):
    BOUNDARY = 'BOUNDARY'

    def writeBoundary(self):
        self.write("--%s\n" % (self.BOUNDARY))

    def writeStop(self):
        self.write("--%s--\n" % (self.BOUNDARY))

    @defer.inlineCallbacks
    def process(self):
        self.setHeader('Connection', 'Keep-Alive')
        self.setHeader('Content-Type', "multipart/x-mixed-replace;boundary=%s" % (self.BOUNDARY))

        self.writeBoundary()

        self.write("Content-Type: text/html\n")
        s = "foo\n"
        self.write("Content-Length: %s\n\n" % (len(s)))
        self.write(s)
        self.writeBoundary()

        yield wait(2)

        self.write("Content-Type: text/html\n")
        s = "bar\n"
        self.write("Content-Length: %s\n\n" % (len(s)))
        self.write(s)
        self.writeBoundary()

        yield wait(2)

        self.write("Content-Type: text/html\n")
        s = "baz\n"
        self.write("Content-Length: %s\n\n" % (len(s)))
        self.write(s)

        self.writeStop()

        self.finish()

class StreamProtocol(http.HTTPChannel):
    requestFactory = StreamHandler

class StreamFactory(http.HTTPFactory):
    protocol = StreamProtocol

if __name__ == '__main__':
    reactor.listenTCP(8800, StreamFactory())
    reactor.run()

rawDescription: Using Twisted's twisted.web classes, how do I flush my outgoing buffers?


rawDescription: Django 'distinct' returning multiple values


code:
from django.contrib import messages
messages.info(request, message)

rawDescription: How do I display a confirmation message after a custom admin action with an intermediate page (in Django)?

description: Display a confirmation message after a custom admin action with an intermediate page (in Django)


code:
item_request_headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36",
    "Accept": "*/*",
    "Accept-Encoding": "gzip,deflate,sdch",
    "Accept-Language": "en-US,en;q=0.8"
}
payload = {"vr": int(item_number[0])}

session = requests.Session(headers=item_request_headers)

# Get form page
form_response = session.get(validation_url, params=payload)

# parse form page; BeautifulSoup could do this for example
soup = BeautifulSoup(form_response.content)
callbackid = soup.select('input[name=__CALLBACKID]')[0]['value']

item_request_body = {
    "__SPSCEditMenu": "true",
    "MSOWebPartPage_PostbackSource": "",
    "MSOTlPn_SelectedWpId": "",
    "MSOTlPn_View": 0,
    "MSOTlPn_ShowSettings": "False",
    "MSOGallery_SelectedLibrary": "",
    "MSOGallery_FilterString": "",
    "MSOTlPn_Button": "none",
    "__EVENTTARGET": "",
    "__EVENTARGUMENT": "",
    "MSOAuthoringConsole_FormContext": "",
    "MSOAC_EditDuringWorkflow": "",
    "MSOSPWebPartManager_DisplayModeName": "Browse",
    "MSOWebPartPage_Shared": "",
    "MSOLayout_LayoutChanges": "",
    "MSOLayout_InDesignMode": "",
    "MSOSPWebPartManager_OldDisplayModeName": "Browse",
    "MSOSPWebPartManager_StartWebPartEditingName": "false",
    "__VIEWSTATE": viewstate,
    "keywords": "Search our site",
    "__CALLBACKID": callbackid,
    "__CALLBACKPARAM": "startvr"
}

item_url = 'http://www.example.com/EN/items/Pages/yourrates.aspx'

response = session.post(url=item_url, params=payload, data=item_request_body,
                        headers={'Referer': form_response.url})

rawDescription: Sending an ASP.net POST with Python's Requests


code:
def repeat_stuff():
    while True: # keep looping until told otherwise

        # do the actual stuff you want to do here, e.g. converting currencies
        do_stuff_once()

        while True: # ask about doing it again until we understand the answer
            userDoAgain = input("Would you like to use again? (Yes/No)\n")
            if userDoAgain.lower() == "yes":
                break               # go back to the outer loop
            elif userDoAgain.lower() == "no":
                print("Thank you for using this program")
                return              # exit the function
            else:
                print("Error: You entered invalid information.")

rawDescription: Why isn't this code repeating? Python 3.3


code:
x = (2,)
y1 = (1,2)
y2 = 2
def concat_tups(x,y):
    return x + (y if isinstance(y,tuple) else (y,))

concat_tups(x,y2)
concat_tups(x,y1)

rawDescription: Concatenate tuple with variable

description: Concatenate tuple with variable


code:
class ClassType(models.Model):
    name = models.CharField(u"Class name", max_length = 120)
    schedule_day = models.IntegerField(u"Day of week")
    schedule_time = models.TimeField(u"Time")
    max_attend = models.IntegerField(u"Maximum attendants")

class ClassRecord(models.Model):
    type = models.ForeignKey(ClassType, verbose_name = "Class type")
    date = models.DateTime("Scheduled date")
    attendants = models.ManyToManyField(User) #don't forget to import it

rawDescription: Django and designing application with gym classes


code:
with open('datafile.txt') as file:
  datalist = []
  for line in file:
    if line.startswith('>'):
      datalist.append([line.strip()[1:], ''])
    else:
      datalist[-1][1] += line.strip()
  for data in datalist:
    print(data[0], '   ', data[1].count('C'))

rawDescription: Counting occurrence of specific character per gene in fasta file using python


code:
def get_user_input():
    in1 = input("Please enter height")
    in2 = input("Please enter weight")
    return in1, in2

def validate_user_input(x, y):
    try:
        # validation code for x
        _ = int(x)
    except:
        return False
    try:
        # validation code for y
        _ = int(y)
    except:
        return False

    # if we get here than all inputs are good
    return True

def ask_user():
    # Loop and a half pattern

    max_tries = 3

    val1, val2 = get_user_input()
    tries = 1
    while validate_user_input(val1, val2) is False:
        if tries >= max_tries:
            quit("Max tries exceeded")
        print("Invalid input. Please try again. You have {} attempts remaining".format(max_tries - tries))
        tries += 1
        val1, val2 = get_user_input()

    # if we get here, input is validated and program can continue
    print('Thank You')

if __name__ == '__main__':
    ask_user()

rawDescription: Ending A Loop in Python 3.x

description: Ending A Loop in Python 3.x


code:
import pygame
import random

pygame.init()
black=(0,0,0)
screen = pygame.display.set_mode((800,600))
screen.fill((255,255,255))

#Dice random number generation
diceRoll = random.randrange(0, 5)

#Text through GUI
myFont = pygame.font.SysFont("Times New Roman", 18)

randNumLabel = myFont.render("You have rolled:", 1, black)
### pass a string to myFont.render
diceDisplay = myFont.render(str(diceRoll), 1, black)

screen.blit(randNumLabel, (520, 20))
screen.blit(diceDisplay, (520, 30))

### main loop
run = True
while run:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            run = False
    pygame.display.flip()

rawDescription: Pygame - Display variable on display window


rawDescription: Kivy add widget at the end of layout

description: Kivy add widget at the end of layout


code:
total = {}

if customers:
    sql_params.update({'customer_%s' % index: customer for index, customer in enumerate(customers)})
    customers_filter = 'and t.customer_id in (%s)' % ', '.join(
        '%%(customer_%s)s' % index for index, customer in enumerate(customers))

rawDescription: Binding list parameter with Django 1.3 ORM raw query


code:
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.pyplot as plt

line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')

blue_line = mlines.Line2D([], [], color='blue', marker='*',
                  markersize=15, label='Blue stars')
red_patch = mpatches.Patch(color='red', label='The red data')

lines = [blue_line, red_patch]
labels = [line.get_label() for line in lines]
plt.legend(lines, labels)

plt.show()

rawDescription: Matplotlib Legend Guide basic examples

description: Matplotlib Legend Guide basic examples


rawDescription: Wrapping around a python list as a slice operation