code:
import re

new_words = []

rep_file = open('in2.txt','r')

for line in rep_file:
    line = line.strip()
    new_words.append(line + '.ec3')

infile = open('in.txt','r')

i = 0
out = open('out.txt','w')

for inline in infile:
    inline = re.sub('opdut_decoded\.wav',new_words[i],inline)
    out.write(inline)
    i += 1

out.close()

rawDescription: Rename specific lines in a text file using python


code:
def get_years_paying(symbol):
    num_years = 0
    for year in Dividend.objects.filter(stock__symbol=symbol).dates("date", "year", order='DESC'):
        if year.year == datetime.now().year: #ignore current year
            continue
        if year.year == datetime.now().year - (num_years + 1):
           num_years = num_years + 1
        else:
            return num_years
    return num_years

rawDescription: django number of consecutive years

description: Django number of consecutive years


code:
x = {'a':1, 'b':2}
y = {'b':1, 'c':2}
for k in y:
 x.setdefault(k, 0)

for k in x:
 y.setdefault(k, 0)

x
y

rawDescription: How do I add two python dictionaries such that the not equal thinks become zero?

description: Add two python dictionaries such that the not equal thinks become zero


code:
from flask import Flask, Blueprint
app = Flask(__name__)
@app.route('/')
def index():
    return '''cheese-bread'''
app.register_blueprint(api, url_prefix='/api')
if __name__ == '__main__':

    app.run(host='0.0.0.0')

rawDescription: Gunicorn and Flask blueprints

description: Gunicorn and Flask blueprints


code:
df = pd.DataFrame(data)
df.groupby(0)[1].agg(["count", "sum", "mean"])

rawDescription: Python List - group by first item, count and sum second item


code:
def ons():
    cs=listbox.curselection()
    listbox.delete(0,cs[0] -1)
    listbox.delete(1,END)

rawDescription: tkinter delete all but not selected item

description: Tkinter delete all but not selected item


code:
import uuid
hdr="\xff"*6
mac=uuid.getnode()
txt="%012X"%mac
as_b=[int("".join(x),16) for x in map(None,*(txt[::2],txt[1::2]))]
as_s="".join(chr(b) for b in as_b)
out=hdr+as_s

rawDescription: Get MAC address in python and append to string


code:
from functools import partial
force_decimal = partial(int, base=10)
force_decimal("01")
force_decimal("0102301")

rawDescription: Why does Python change the value of an integer when there is a 0 in front of it?


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

class MyUser(AbstractUser):
    black_coffee = models.IntegerField(default=0)
    coffee_with_milk = models.IntegerField(default=0)
    coffee_cut = models.IntegerField(default=0)

rawDescription: Extending django.contrib.auth.models.User model with custom fields in Django


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

class TestThatNeedsLogin(TestCase):
    def setUp(self):
        User.objects.create_superuser(
            'user1',
            'user1@example.com',
            'pswd',
        )
        self.client.login(username="user1", password="pswd")

    def tearDown(self):
        self.client.logout()

    def test_something(self):
        response = self.client.get("/")
        self.assertEqual(200, response.status_code)

rawDescription: Can I avoid permission_required decorator on Django testing?

description: Avoid permission_required decorator on Django testing


code: manager = forms.CharField(required=False, widget=Select(choices=(('', '----------'),) + LIST), label='Their Position?')

rawDescription: DJANGO: blank select option missing in form


code:
from django.forms.models import model_to_dict

class Currency(models.Mode):
    code = models.CharField(max_length=3)
    name = models.CharField(max_length=10)

    def __init__(self):
        super(Currency, self).__init__()
        self.__state = model_to_dict(self)

    def updated(self):
        new_state = model_to_dict(self)
        return dict(set(self.__state.iteritems()) - set(new_state.iteritems()))

rawDescription: How to check for a specific field change in a model?

description: Check for a specific field change in a model


code:
#!/usr/bin/env python

import re

# uncomment/comment for test with a real file ...
# header = open('mycfile.c', 'r').read()
header = """

#if 0
    whatever(necessary)
    and maybe more

#endif

/*
 * This is an original style comment
 *
 */

int main (int argc, char const *argv[])
{
    /* code */
    return 0;
}

"""

p_macro = re.compile("#if.*?#endif", re.DOTALL)
p_comment = re.compile("/\*.*?\*/", re.DOTALL)

# Example ...
# print re.sub(p_macro, '', header)
# print re.sub(p_comment, '', header)

rawDescription: How to automatically remove certain preprocessors directives and comments from a C header-file?

description: Automatically remove certain preprocessors directives and comments from a C header-file


code:
msg="""To: user1@company1.com, John Doe <user2@example.com>, "Public, John Q." <user3@example.com>
From: anotheruser@user.com
Subject: This is a subject

This is the message.
"""

import email

msg822 = email.message_from_string(msg)
for to in email.utils.getaddresses(msg822.get_all("To", [])):
    print("To:",to)

rawDescription: How do you extract multiple email addresses from an RFC 2822 mail header in python?

description: Extract multiple email addresses from an RFC 2822 mail header in python


code:
f = lambda r: ','.join(df.columns[r])
df.eq(df.max(axis=1), axis=0).apply(f, axis=1)
df['best'] = _
df

rawDescription: New column with column name from max column by index pandas


code:
import cPickle
class MyModel(models.Model):
    cpickled_values = models.TextField()

    def get_values(self):
        return cPickle.loads(str(self.cpickled_values))

    def set_values(self, value):
        self.cpickled_value = cPickle.dumps(values)

    values = property(get_values, set_values)

rawDescription: Model set fields in Django

description: Model set fields in Django


code:
from __future__ import division

import numpy as np
from scipy.signal import lombscargle
import matplotlib.pyplot as plt

np.random.seed(12345)

n = 100
x = np.sort(10*np.random.rand(n))
# Dominant periodic signal
y = np.sin(2.5*x)
# Add some smaller periodic components
y += 0.15*np.cos(0.75*x) + 0.2*np.sin(4*x+.1)
# Add some noise
y += 0.2*np.random.randn(x.size)

plt.figure(1)
plt.plot(x, y, 'b')
plt.xlabel('x')
plt.ylabel('y')
plt.grid()

dxmin = np.diff(x).min()
duration = x.ptp()
freqs = np.linspace(1/duration, n/duration, 5*n)
periodogram = lombscargle(x, y, freqs)

kmax = periodogram.argmax()
print("%8.3f" % (freqs[kmax],))

plt.figure(2)
plt.plot(freqs, np.sqrt(4*periodogram/(5*n)))
plt.xlabel('Frequency (rad/s)')
plt.grid()
plt.axvline(freqs[kmax], color='r', alpha=0.25)
plt.show()

rawDescription: Discrete fourier transfromation from a list of x-y points


code:
import random

from string import ascii_uppercase, ascii_lowercase, ascii_letters, digits

pool = ascii_letters + digits
wordLen=random.randint(7,14)
answer = random.sample(pool, wordLen)

while True:
    if not any(char.isupper() for char in answer):
        answer[random.randrange(len(answer))] = random.choice(ascii_uppercase)
        continue

    if not any(char.islower() for char in answer):
        answer[random.randrange(len(answer))] = random.choice(ascii_lowercase)
        continue

    if not any(char.isdigit() for char in answer):
        answer[random.randrange(len(answer))] = random.choice(digits)
        continue

    break

answer = ''.join(answer)

rawDescription: Modifying random word generator to ensure specific character types


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

test1 = pd.DataFrame({'A':[False, False, False, True], 'B':[False, False, True, False], 'C':[True, False, True, False]})
test2 = pd.DataFrame({'A':[False, False, False, False], 'B':[True, False, True, False], 'C':[False, False, False, False]})

# Make a matrix whose elements are 0 if both are True, 1 if neither True, else 2.
mat = np.vectorize( lambda a,b: 0 if a and b else 1 if a or b else 2)(test1,test2)

y,x = np.where(mat==0)
plt.plot(x, y, 'ro')
y,x = np.where(mat==1)
plt.plot(x, y, 'yo')

xlabels = test1.columns

plt.ylim(-1,len(test1.index))
plt.xlim(-1,len(xlabels))

plt.xticks(range(len(xlabels)), xlabels)

plt.show()

rawDescription: Plotting boolean dataframes with a condition


code:
@pytest.fixture
def thing(request, db):
    class ThingFactory(object):
        def get(self):
            thing = MyModel.objects.create()
            request.addfinalizer(thing.delete)
            return thing
    return ThingFactory()

def test_thing(thing):
    thing1 = thing.get()
    thing2 = thing.get()

rawDescription: Multiple copies of a py.test fixture

description: Multiple copies of a py.test fixture


code:
import scipy.io
mat = scipy.io.loadmat('file.mat')

rawDescription: Read .mat files in Python

description: Read .mat files in Python


code:
# populate a Dictionary to find dimension_ids for category labels
parent_dimension_age = Dimension.objects.get(name='Age')
parent_dimension_income = Dimension.objects.get(name='Income')
dims_age = dict([ (d.name, d.id) for d in Dimension.objects.filter(parent_id=parent_dimension_age.id) ])
dims_income = dict([ (d.name, d.id) for d in Dimension.objects.filter(parent_id=parent_dimension_income.id) ])

# Retrieves a row at a time into a comma delimited string
for line in pandas_pivottable.to_csv(header=False, index=True, sep='\t').split('\n'):
    if line:
        # row[0] = income category, row[1] = age category, row[2] = age, row[3] = income
        row = line.split('\t')
        entity = Entity(name='data pivot row', dataset_id=dataset.id)
        entity.save()
        # dims_age.get(row[1]) gets the ID for the category whose name matches the contents of row[1]
        age_val = FloatValue(value=row[2], entity_id=entity.id, attribute_id=attrib_age.id, dimension_id=dims_age.get(row[1]))
        age_val.save()
        income_val = FloatValue(value=row[3], entity_id=entity.id, attribute_id=attrib_income.id, dimension_id=dims_income.get(row[0]))
        income_val.save()

rawDescription: Insert and categorize a Numpy array into a Django modelled database EAV schema


code:
s = 'FFFFoFob*&%ar**^'
s.strip('!@#$%^&*(FGHJKmn')

rawDescription: How do I strip a string given a list of unwanted characters? Python

description: Strip a string given a list of unwanted characters? Python


code: lst = [{'foo': [0] * n_of_elems, 'bar': [0] * n_of_elems} for _ in range(n_of_dicts)]

rawDescription: Python - Strange behavior with dicts in list


code:
from numpy import *

x,y,z = mgrid[-100:101:25., -100:101:25., -100:101:25.]

V = 2*x**2 + 3*y**2 - 4*z # just a random function for the potential

Ex,Ey,Ez = gradient(V)

rawDescription: Calculating gradient with NumPy

description: Calculating gradient with NumPy


code:
[tox]
skipsdist=BOOL    # defaults to false

rawDescription: How do I run tox in a project that has no setup.py?

description: Run tox in a project that has no setup.py


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

fig = plt.figure()
ax = fig.add_subplot(111)

# some X and Y data
x = [0]
y = [0]

li, = ax.plot(x, y,'o')

# draw and show it
fig.canvas.draw()
plt.show(block=False)

# loop to update the data
for i in range(100):
    try:
        x.append(i)
        y.append(i)

        # set the new data
        li.set_xdata(x)
        li.set_ydata(y)

        ax.relim()
        ax.autoscale_view(True,True,True)

        fig.canvas.draw()

        time.sleep(0.01)
    except KeyboardInterrupt:
        plt.close('all')
        break

rawDescription: MatPlotLib's ion() and draw() not working


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

ax = plt.subplot(111, polar=True)
equals = np.linspace(0, 360, 24, endpoint=False) #np.arange(24)
ones = np.ones(24)
ax.scatter(np.deg2rad(equals), ones)

# Set the circumference labels
ax.set_xticks(np.linspace(0, 2*np.pi, 24, endpoint=False))
ax.set_xticklabels(range(24))

# Make the labels go clockwise
ax.set_theta_direction(-1)

# Place 0 at the top
ax.set_theta_offset(np.pi/2.0)

plt.show()

rawDescription: Python polar clock-like plot with matplotlib


code:
iter = x.__iter__()         # get iterator
try:
    while 1:
        y = iter.next()         # get each item
        ...                     # process y
except StopIteration: pass  # iterator exhausted

rawDescription: Why the following python code works?

description: Why the following python code works


code: [ i for [_, i] in lst ]

rawDescription: Python Selecting Data in a List within a List


code:
import numpy as np

a = np.array(range(5, 10))
b = np.array(range(2, 6))

res = a[np.newaxis, :] - b[:, np.newaxis]
print(res)
# [[3 4 5 6 7]
#  [2 3 4 5 6]
#  [1 2 3 4 5]
#  [0 1 2 3 4]]

rawDescription: Subtract all pairs of values from two arrays


code:
class Intervals(dict):
    def __init__(self, *_):
        self.update({'P5': 7})

Intervals = Intervals()

rawDescription: Is __init__ called every time for a subscriptable object that creates a dictionary dynamically?


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

xlim = (-60.,60.)
ylim = (-110.,110.)
axes_pad = 0.02
cbar_height = 0.025
h_pad = 0.1
v_pad = 0.1

fig_w = 7.
fig_h = 6.

height = 1-axes_pad-cbar_height-2*v_pad
width = np.abs((xlim[1]-xlim[0])/(ylim[1]-ylim[0]))*height*fig_h/fig_w # ensure equal aspect

bottom_h = v_pad+height+axes_pad
left_h = h_pad+width+axes_pad

rect_c = [h_pad, v_pad, width, height]
rect_cbar = [h_pad, bottom_h, width, cbar_height]
rect_r = [left_h, v_pad, 1-axes_pad-width-2*h_pad, height]

fig = plt.figure(1, figsize=(fig_w,fig_h))
ax_c = plt.axes(rect_c)
ax_cbar = plt.axes(rect_cbar)
ax_r = plt.axes(rect_r)

ax_c.set_xlim(xlim)
ax_c.set_ylim(ylim)
ax_r.set_ylim(ylim)

ax_rty = ax_r.twiny()
ax_rty.set_xlim((-100,0)) # determined dynamically later
ax_r.set_xlim((0,0.5)) # determined dynamically later

plt.savefig('skeleton.pdf',bbox_inches='tight')

rawDescription: three subplots in a grid, one equal aspect subplot with shared x and y axes

description: Three subplots in a grid, one equal aspect subplot with shared x and y axes


code:
from IPython.display import Image
Image(filename='test.png')

rawDescription: Display an image from a file in an IPython Notebook


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

#read in data from csv organised in columns labelled 'lat','lon','elevation'
data = np.recfromcsv('elevation-sample.csv', delimiter=',')

# create a 3d axis on a figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Find unique (i.e. constant) latitude points
id_list = np.unique(data['lat'])

# stride is how many lines to miss.  set to 1 to get every line
# higher to miss more
stride = 5

# Extract each line from the dataset and plot it on the axes
for id in id_list[::stride]:
    this_line_data = data[np.where(data['lat'] == id)]
    lat,lon,ele = zip(*this_line_data)
    ax.plot(lon,lat,ele, color='black')

# set the viewpoint so we're looking straight at the longitude (x) axis
ax.view_init(elev=45., azim=90)

ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
ax.set_zlabel('Elevation')
ax.set_zlim([0,1500])

plt.show()

rawDescription: Geographical data plot/map with lines in python and matplotlib


code:
def verify(self, param, val):
    self.assertEqual(getattr(self.tm.get, param), val)

rawDescription: call different functions based on parameter

description: Call different functions based on parameter


code:
def make_grid(neighbor_dict):
    # step 1, find the first corner
    for node, neighbors in neighbor_dict:
        if len(neighbors) == 2:
            break  # node and neighbors will hold our start corner and its neighbors

    # step 2, build the first edge
    row = [node, neighbor[0]]  # start with the corner, and an arbitrary neighbor
    while len(neighbors_dict[row[-1]]) == 3:
        for neighbor in neighbor_dict[row[-1]]:
            if neighbor != row[-2] and len(neighbor_dict[neighbor]) <= 3:
                row.append(neighbor)
                break

    # setup for steps 3 and 4
    seen = set(row)  # a set of all nodes we've added to the grid so far
    rows = []
    done = False

    while not done:  # this loop is step 4, building all rows
        rows.append(row)
        new_row = []
        for node in row:  # this is step 3, building a new row from the previous row
            for neighbor in neighbor_dict[node]:
                if neighbor not in seen:
                    new_row.append(neighbor)
                    seen.add(neighbor)
                    break
            else:  # no break hit in for loop, only happens if `row` is the far edge
                done = True
                break
        row = new_row

    # step 5, transpose to get columns from rows
    columns = list(zip(*rows))

    return rows, columns

rawDescription: Pythonic way of figuring out straight paths on a square lattice grid?


rawDescription: Round, align and print list of floats with format()


code:
def create_or_get(tree, nodes):
    for node in nodes:
        if not tree.hasElement(node):
            tree.appendChild(tree.createElement(node))
        tree = tree.getElement(node)
    return tree

create_or_get(doc, ["Global", "Config", "Hey"]).text = "lorem ipsum dolor sit amet"

rawDescription: Shorter way to write in a specific path of the XML tree


code:
full_person = ia.get_person(actor[0].getID(), info=["filmography"])
full_person.keys()
full_person["actor"]

rawDescription: How to Find list of movies acted by an actor?

description: Find list of movies acted by an actor


rawDescription: Python pandas Reading specific values from HDF5 files using read_hdf and HDFStore.select


code:
import numpy as np
def polynomial_features(x, order):
    x = np.asarray(x).T[np.newaxis]
    n = x.shape[1]
    power_matrix = np.tile(np.arange(order + 1), (n, 1)).T[..., np.newaxis]
    X = np.power(x, power_matrix)
    I = np.indices((order + 1, ) * n).reshape((n, (order + 1) ** n)).T
    F = np.product(np.diagonal(X[I], 0, 1, 2), axis=2)
    return F.T

rawDescription: 2d numpy.power for polynomial expansion

description: 2d numpy.power for polynomial expansion


rawDescription: matplotlib custom x-axes with custom number of ticks

description: Matplotlib custom x-axes with custom number of ticks


code:
for i, item in enumerate(some_seq):
    bar(item, i)

rawDescription: What is the runtime complexity of python list functions?


code:
import urllib2
from bs4 import BeautifulSoup
page = urllib2.urlopen('some_site').read()
soup = BeautifulSoup(page)
body = soup.find('body')
the_contents_of_body_without_body_tags = body.findChildren()

rawDescription: BeautifulSoup - how should I obtain the body contents


code:
import collections
d = collections.deque(maxlen=10)
d
for i in xrange(20):
    d.append(i)

d

rawDescription: efficient circular buffer?

description: Efficient circular buffer


code:
"Hi, there".startswith(('Ha', 'Ho', 'Hi'))
"Hoy, there".startswith(('Ha', 'Ho', 'Hi'))
"Hello, there".startswith(('Ha', 'Ho', 'Hi'))

rawDescription: Startswith(): more arguments

description: Startswith(): more arguments


code:
def getbasetemp(self):
    """ return base temporary directory. """
    try:
        return self._basetemp
    except AttributeError:
        basetemp = self.config.option.basetemp
        if basetemp:
            basetemp = py.path.local(basetemp)
            if basetemp.check():
                basetemp.remove()
            basetemp.mkdir()
        else:
            basetemp = py.path.local.make_numbered_dir(prefix='pytest-')
        self._basetemp = t = basetemp.realpath()
        self.trace("new basetemp", t)
        return t

rawDescription: Specify --basetemp while keeping the per-session folder behavior


code:
import bottle
import pickle
import time
import threading

class WebServer(object):
    def __init__(self):
        bottle.route("/", 'GET', self.root)
        bottle.run(host='0.0.0.0', debug=True)

    def root(self):
        with open("watchdog.txt", "wb") as f:
            pickle.dump(time.time(), f)

def check():
    try:
        with open("watchdog.txt", "rb") as f:
            t1 = pickle.load(f)
    except IOError:
        pass
    else:
        t2 = time.time()
        if t2 - t1 > 10:
            print("stale watchdog")
        else:
            print("fresh watchdog")
    finally:
        threading.Timer(10, check).start()

if __name__ == "__main__":
    check()
    WebServer()

rawDescription: How to run bottle and a concurrent function?

description: Run bottle and a concurrent function


code: models = [name.split('_')[2] for name in files]

rawDescription: Python: Extract all characters between a two groups of characters in a string


code:
def levenshtein(s1, s2):
    insertionCost=1
    deletionCost=1
    substitutionCost=1

    if len(s1) < len(s2):
        return levenshtein(s2, s1)

    # len(s1) >= len(s2)
    if len(s2) == 0:
        return min(deletionCost,insertionCost)*len(s1)

    previous_row = range(len(s2) + 1)
    for i, c1 in enumerate(s1):
        current_row = [i + 1]
        for j, c2 in enumerate(s2):
            insertions = previous_row[j + 1] + insertionCost # j+1 instead of j since previous_row and current_row are one character longer
            deletions = current_row[j] + deletionCost       # than s2
            substitutions = previous_row[j] + substitutionCost*(c1 != c2)
            current_row.append(min(insertions, deletions, substitutions))
        previous_row = current_row

    return previous_row[-1]

#returns 2
print(levenshtein(['abc','def','ghi'],['abc','ghi','e']))

rawDescription: Simple recursive plagiarism detector for arrays


code:
from flask import Flask, render_template
from jinja2 import BaseLoader, TemplateNotFound
from urllib import urlopen
from urlparse import urljoin

class UrlLoader(BaseLoader):
    def __init__(self, url_prefix):
        self.url_prefix = url_prefix

    def get_source(self, environment, template):
        url = urljoin(self.url_prefix, template)
        try:
            t = urlopen(url)
            if t.getcode() is None or t.getcode() == 200:
                return t.read().decode('utf-8'), None, None
        except IOError:
            pass
        raise TemplateNotFound(template)

app = Flask(__name__)
app.jinja_loader = UrlLoader('http://localhost:8000/')

@app.route('/')
def root():
    return render_template('hello.html')

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

rawDescription: Render a Jinja template stored on an FTP server


code:
class ImpersonateMiddleware(object):
    def process_request(self, request):
        if request.user.is_superuser and "__impersonate" in request.GET:
            request.user = models.User.objects.get(id=int(request.GET["__impersonate"]))

    def process_response(self, request, response):
        if request.user.is_superuser and "__impersonate" in request.GET:
            if isinstance(response, http.HttpResponseRedirect):
                location = response["Location"]
                if "?" in location:
                    location += "&"
                else:
                    location += "?"
                location += "__impersonate=%s" % request.GET["__impersonate"]
                response["Location"] = location
        return response

rawDescription: Django user impersonation by admin

description: Django user impersonation by admin


code:
object2 = copy.deepcopy(object1)
object3 = copy.deepcopy(object1)

rawDescription: Copying an object in Python

description: Copying an object in Python


rawDescription: how to use mask to remove the background in python

description: Use mask to remove the background in python


code:
import tornado.httpserver
import tornado.ioloop
import tornado.web

class getToken(tornado.web.RequestHandler):
    def get(self):
        self.write("hello")

application = tornado.web.Application([
    (r'/', getToken),
])

if __name__ == '__main__':
    http_server = tornado.httpserver.HTTPServer(application, ssl_options={
        "certfile": "/var/pyTest/keys/ca.csr",
        "keyfile": "/var/pyTest/keys/ca.key",
    })
    http_server.listen(443)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: How to create HTTPS tornado server

description: Create HTTPS tornado server


code:
from bs4 import BeautifulSoup as bs
data = '
BAR hello
'
soup = bs(data)
bar = soup.find(id="bar")
bar
bar.next_sibling.strip()

rawDescription: Get text next to the selected element using BeautifulSoup


code:
from HTMLParser import HTMLParser

s = r"""<form method="post" enctype="multipart/form-data" class="wp-upload-form" action="http://localhost/wp-admin/update.php?action=upload-plugin">
        <input type="hidden" id="_wpnonce" name="_wpnonce" value="a7a9167537"><input type="hidden" name="_wp_http_referer" value="/wp-admin/plugin-install.php?tab=upload">     <label class="screen-reader-text" for="pluginzip">Plugin zip file</label>
        <input type="file" id="pluginzip" name="pluginzip">
        <input type="submit" name="install-plugin-submit" id="install-plugin-submit" class="button" value="Install Now" disabled="">    </form>"""

class CodeFinder(HTMLParser):
    def handle_starttag(self, tag, attrs):
        if tag == "input":
            attrs = dict(attrs)
            if 'id' in attrs and attrs['id'] == '_wpnonce':
                print("The  value is: {}".format(attrs['value']))

parser = CodeFinder()
parser.feed(s)

rawDescription: python regex token capture

description: Python regex token capture


code:
from kivy.uix.popup import Popup
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label

box = BoxLayout()
box.add_widget(Label(text='Hello world'))
box.add_widget(TextInput(text='Hi'))

popup = Popup(title='Test popup', content=box, size_hint=(None, None), size=(400, 400))

rawDescription: Kivy: Multiple items in a popup wont work


code:
import numpy as np
import scipy.ndimage as ndimage
import scipy.spatial as spatial
import scipy.misc as misc
import matplotlib.pyplot as plt
import matplotlib.patches as patches

class BBox(object):
    def __init__(self, x1, y1, x2, y2):
        '''
        (x1, y1) is the upper left corner,
        (x2, y2) is the lower right corner,
        with (0, 0) being in the upper left corner.
        '''
        if x1 > x2: x1, x2 = x2, x1
        if y1 > y2: y1, y2 = y2, y1
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
    def taxicab_diagonal(self):
        '''
        Return the taxicab distance from (x1,y1) to (x2,y2)
        '''
        return self.x2 - self.x1 + self.y2 - self.y1
    def overlaps(self, other):
        '''
        Return True iff self and other overlap.
        '''
        return not ((self.x1 > other.x2)
                    or (self.x2 < other.x1)
                    or (self.y1 > other.y2)
                    or (self.y2 < other.y1))
    def __eq__(self, other):
        return (self.x1 == other.x1
                and self.y1 == other.y1
                and self.x2 == other.x2
                and self.y2 == other.y2)

def find_paws(data, smooth_radius = 5, threshold = 0.0001):
    # http://stackoverflow.com/questions/4087919/how-can-i-improve-my-paw-detection
    """Detects and isolates contiguous regions in the input array"""
    # Blur the input data a bit so the paws have a continous footprint
    data = ndimage.uniform_filter(data, smooth_radius)
    # Threshold the blurred data (this needs to be a bit > 0 due to the blur)
    thresh = data > threshold
    # Fill any interior holes in the paws to get cleaner regions...
    filled = ndimage.morphology.binary_fill_holes(thresh)
    # Label each contiguous paw
    coded_paws, num_paws = ndimage.label(filled)
    # Isolate the extent of each paw
    # find_objects returns a list of 2-tuples: (slice(...), slice(...))
    # which represents a rectangular box around the object
    data_slices = ndimage.find_objects(coded_paws)
    return data_slices

def slice_to_bbox(slices):
    for s in slices:
        dy, dx = s[:2]
        yield BBox(dx.start, dy.start, dx.stop+1, dy.stop+1)

def remove_overlaps(bboxes):
    '''
    Return a set of BBoxes which contain the given BBoxes.
    When two BBoxes overlap, replace both with the minimal BBox that contains both.
    '''
    # list upper left and lower right corners of the Bboxes
    corners = []

    # list upper left corners of the Bboxes
    ulcorners = []

    # dict mapping corners to Bboxes.
    bbox_map = {}

    for bbox in bboxes:
        ul = (bbox.x1, bbox.y1)
        lr = (bbox.x2, bbox.y2)
        bbox_map[ul] = bbox
        bbox_map[lr] = bbox
        ulcorners.append(ul)
        corners.append(ul)
        corners.append(lr)

    # Use a KDTree so we can find corners that are nearby efficiently.
    tree = spatial.KDTree(corners)
    new_corners = []
    for corner in ulcorners:
        bbox = bbox_map[corner]
        # Find all points which are within a taxicab distance of corner
        indices = tree.query_ball_point(
            corner, bbox_map[corner].taxicab_diagonal(), p = 1)
        for near_corner in tree.data[indices]:
            near_bbox = bbox_map[tuple(near_corner)]
            if bbox != near_bbox and bbox.overlaps(near_bbox):
                # Expand both bboxes.
                # Since we mutate the bbox, all references to this bbox in
                # bbox_map are updated simultaneously.
                bbox.x1 = near_bbox.x1 = min(bbox.x1, near_bbox.x1)
                bbox.y1 = near_bbox.y1 = min(bbox.y1, near_bbox.y1)
                bbox.x2 = near_bbox.x2 = max(bbox.x2, near_bbox.x2)
                bbox.y2 = near_bbox.y2 = max(bbox.y2, near_bbox.y2)
    return set(bbox_map.values())

if __name__ == '__main__':
    fig = plt.figure()
    ax = fig.add_subplot(111)

    data = misc.imread('image.png')
    im = ax.imshow(data)
    data_slices = find_paws(255-data, smooth_radius = 20, threshold = 22)

    bboxes = remove_overlaps(slice_to_bbox(data_slices))
    for bbox in bboxes:
        xwidth = bbox.x2 - bbox.x1
        ywidth = bbox.y2 - bbox.y1
        p = patches.Rectangle((bbox.x1, bbox.y1), xwidth, ywidth,
                              fc = 'none', ec = 'red')
        ax.add_patch(p)

    plt.show()

rawDescription: Rectangular bounding box around blobs in a monochrome image using python


code:
from path import path
s = path(filename).bytes()

rawDescription: Easiest way to read/write a file's content in Python


code:
a = [['hello ', 'world '],['foo ',' bar']]
b = [[s.strip() for s in l] for l in a]
print(b)
# [['hello', 'world'], ['foo', 'bar']]

rawDescription: Double for loop list comprehension

description: Double for loop list comprehension


code:
for i in currentList:
    if not i[0:length] == parameters:
        self.searchResults.delete(int)
        continue # <--  Use continue so `int` does not increment.
    int += 1

rawDescription: Tkinter Listbox not deleting items correctly


code:
from operator import add

def pascal_line(n):
    if n < 2:
        return [1]*(n+1)
    l = pascal_line(n-1)
    return [1] + map(add, l[1:], l[:-1]) + [1]

rawDescription: Return a specific line of pascals triangle recursivly with python


code:
from logging import Handler, getLogger

class ListboxHandler(Handler):
    def __init__(self, box):
        self._box = box
        Handler.__init__(self)

    def emit(self, record):
        r = self.format(record)
        self._box.insert(0, r)

# quick test:
target = [] # supports insert like Listbox :)
rootLogger = getLogger()
# add handler to the root logger here
# should be done in the config...
rootLogger.addHandler(ListboxHandler(target))
rootLogger.warn('test')
print(target)

rawDescription: how to direct python logger to Tkinker's Listbox?

description: Direct python logger to Tkinker's Listbox


code:
MINIMAL_MATCH = 3

def find_some_sort_of_weird_consecutiveness(data):
    """
    >>> find_some_sort_of_weird_consecutiveness([1,3,4,5])
    [[1], [3, 4, 5]]
    >>> find_some_sort_of_weird_consecutiveness([1,3,5,6,7])
    [[1, 3, 5], [6], [7]]
    >>> find_some_sort_of_weird_consecutiveness([1,2,3,7,9,11])
    [[1, 2, 3], [7, 9, 11]]
    >>> find_some_sort_of_weird_consecutiveness([1,2,3,7,10,12,14,25])
    [[1, 2, 3], [7], [10, 12, 14], [25]]
    >>> find_some_sort_of_weird_consecutiveness([1,2,3,4,6,8,10])
    [[1, 2, 3, 4], [6, 8, 10]]
    >>> find_some_sort_of_weird_consecutiveness([1,5,10,11,12,13,14,15,17,20,22,24,26,28,30])
    [[1], [5], [10, 11, 12, 13, 14, 15], [17], [20, 22, 24, 26, 28, 30]]
    """
    def pair_iter(series):
        from itertools import tee
        _first, _next = tee(series)
        next(_next, None)
        for i, (f, n) in enumerate(zip(_first, _next), start=MINIMAL_MATCH - 1):
            yield i, f, n

    result = []
    while len(data) >= MINIMAL_MATCH:
        test = data[1] - data[0]
        if (data[2] - data[1]) == test:
            for i, f, n in pair_iter(data):
                if (n - f) != test:
                    i -= 1
                    break
        else:
            i = 1
        data, match = data[i:], data[:i]
        result.append(match)
    for d in data:
        result.append([d])
    return result

if __name__ == '__main__':
    from doctest import testmod
    testmod()

rawDescription: Identify varying consecutive multiples in a sorted list


code:
text = 'code'
first, body, last = text[0], text[1:-1], text[-1]
result = last + body + first
# 'eodc'

rawDescription: Why doesn't my front_back programme in Python work?


code:
@cherrypy.expose
def echo(self, *args, **kwargs):
    return kwargs['param_1']

rawDescription: CherryPy: What would the html command line syntax be if you wanted to pass a dictionary as an argument?


rawDescription: How do I do conditional array arithmetic on a numpy array?

description: Do conditional array arithmetic on a numpy array


code:
_pc = []
for i in range(256):
    c = 0
    while i:
        # clear last set bit
        i &= i-1
        c += 1
    _pc.append(c)

def popcount(i):
    "Return number of bits set."
    result = 0
    while i:
        result += _pc[i & 0xff]
        i >>= 8
    return result

def perm(a):
    "Return permanent of 0-1 matrix.  Each row is an int."
    result = 0
    n = len(a)
    for s in range(1 << n):
        prod = 1
        for row in a:
            prod *= popcount(row & s)
        if popcount(s) & 1:
            result -= prod
        else:
            result += prod
    if n & 1:
        result = -result
    return result

def matrix2ints(a):
    return [int("".join(map(str, row)), 2)
            for row in a]

def matrix_perm(a):
    "Return permanent of 0-1 matrix."
    return perm(matrix2ints(a))

rawDescription: Counting number of ways to select unique elements from list of lists


code:
def upload(self, myFile):
    MySQLconnection = MySQLdb.connect(host=cherrypy.request.app.config['Database']['host'],
                                 passwd=cherrypy.request.app.config['Database']['passwd'],
                                 db=cherrypy.request.app.config['Database']['db'],
                                 user=cherrypy.request.app.config['Database']['user'],
                                 port=cherrypy.request.app.config['Database']['port'],
                                 cursorclass=DictCursor)
    MySQLcursor = MySQLconnection.cursor()
    size = 0

    # add this line
    all_data = bytearray()

    while True:
        data = myFile.file.read(8192)
        all_data += data
        if not data:
            break
        size += len(data)

        saved_file=open('upload_path', 'wb')
        saved_file.write(all_data)
        saved_file.close()

    MySQLcursor.execute("insert into ImagePathDatabase (path) values ('" + MySQLdb.escape_string(myFile.filename) + "')")
    MySQLcursor.execute("commit;")

rawDescription: cherrypy: server side code of getting image by http post and storing its path mysqldatabase

description: Cherrypy: server side code of getting image by http post and storing its path mysqldatabase


rawDescription: Convert strings to list

description: Convert strings to list


code:
class MyClass(webdriver.PhantomJS):
    def __init__(self, *args, **kwargs):
        phantomjs_path = 'node_modules/.bin/phantomjs'
        super().__init__(phantomjs_path, *args, **kwargs)

rawDescription: Python - Proper way of inheritance, super and initialize object (selenium, phantomjs)


code:
import wx

class Frame(wx.Frame):
    def __init__(self,*args,**kwargs):
        wx.Frame.__init__(self,*args,**kwargs)
        panel= wx.Panel(self)
        self.password_shown= False

        sizer= wx.BoxSizer(wx.VERTICAL)
        self.password_sizer= wx.BoxSizer(wx.HORIZONTAL)
        self.text_password= wx.TextCtrl(panel,style=wx.TE_PASSWORD)
        self.password_sizer.Add(self.text_password,0,wx.ALL,5)
        self.text_no_password= wx.TextCtrl(panel)
        self.text_no_password.Hide()
        self.password_sizer.Add(self.text_no_password,0,wx.ALL,5)
        sizer.Add(self.password_sizer)
        self.button= wx.Button(panel,-1,"Toggle Password")
        sizer.Add(self.button,0,wx.ALL,5)
        self.button.Bind(wx.EVT_BUTTON,self.OnButton)
        panel.SetSizer(sizer)

        self.Show()

    def OnButton(self,event):
        self.text_password.Show(self.password_shown)
        self.text_no_password.Show(not self.password_shown)
        if not self.password_shown:
            self.text_no_password.SetValue(self.text_password.GetValue())
            self.text_no_password.SetFocus()
        else:
            self.text_password.SetValue(self.text_no_password.GetValue())
            self.text_password.SetFocus()
        self.text_password.GetParent().Layout()
        self.password_shown= not self.password_shown

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

rawDescription: how to make wxpython password textctrl show chars?

description: Make wxpython password textctrl show chars


code:
# get sibling file
sib = Path(__file__).with_name(same_level_file)

# get parent
par = Path(__file__).parent

# file in sibling parent
sib2 = Path(__file__).parent.with_name(parent_folder).joinpath(file2)

rawDescription: How to set relative path to executive script

description: Set relative path to executive script


code:
def nest(data):
    result = {}
    for record in data:
        assert len(record) > 2
        d = result
        for key in record[:-2]:
            d = d.setdefault(key, {})

        key,value = record[-2:]
        d[key] = value
    return result

rawDescription: From multidimensional array to hierarchy


code:
from random import choice
for key in total_values:
    total_values[key] = (total_values[key], choice((True, False)))

rawDescription: Convert a single valued dictionary to multivalued dictionary in python


code:
def draw(event):
    global history, canvas
    #when a tile gets painted on
    X=event.pos[0]
    Y=event.pos[1]
    history.append(X,Y,canvas[X][Y])
    canvas[X][Y] = current_color

def undo():
    global history, canvas
    X = history[len(history)-1][0]
    Y = history[len(history)-1][1]
    color = history[len(history)-1][2]

    canvas[X][Y] = color
    history.pop(len(history)-1)

rawDescription: Undo Function in python part 2

description: Undo Function in python part 2


code:
from kivy.app import App
from kivy.clock import Clock, _default_time as time  # ok, no better way to use the same clock as kivy, hmm
from kivy.lang import Builder
from kivy.factory import Factory
from kivy.uix.button import Button
from kivy.properties import ListProperty

from threading import Thread
from time import sleep

MAX_TIME = 1/60.

kv = '''
BoxLayout:
    ScrollView:
        GridLayout:
            cols: 1
            id: target
            size_hint: 1, None
            height: self.minimum_height

    MyButton:
        text: 'run'

<MyLabel@Label>:
    size_hint_y: None
    height: self.texture_size[1]
'''

class MyButton(Button):
    def on_press(self, *args):
        Thread(target=self.worker).start()

    def worker(self):
        sleep(5) # blocking operation
        App.get_running_app().consommables.append("done")

class PubConApp(App):
    consommables = ListProperty([])

    def build(self):
        Clock.schedule_interval(self.consume, 0)
        return Builder.load_string(kv)

    def consume(self, *args):
        while self.consommables and time() < (Clock.get_time() + MAX_TIME):
            item = self.consommables.pop(0)  # i want the first one
            label = Factory.MyLabel(text=item)
            self.root.ids.target.add_widget(label)

if __name__ == '__main__':
    PubConApp().run()

rawDescription: Python Kivy: Properly start a background process that updates GUI elements


code:
from Fifa14Client import LoginManager
from Fifa14Client import WebAppFunctioner
import ConfigParser
from extra import EAHash
import threading

def login_thread(email, password, security_hash, platform):
    # This function runs in a separate thread.
    login = LoginManager.LoginManager(email,password,security_hash,platform)
    login.login()
    func = WebAppFunctioner.WebAppFunctioner(login)
    # Do more stuff here

def do_main():
    Config = ConfigParser.ConfigParser()
    Config.read("accounts_example.ini")
    threads = []
    for section in Config.sections():
        email = Config.get(section, 'Email')
        password = Config.get(section, 'Password')
        secret_answer = Config.get(section, 'Secret')
        security_hash = EAHash.EAHashingAlgorithm().EAHash(secret_answer)
        platform = Config.get(section, 'Platform')
        t = threading.Thread(target=login_thread,
                             args=(email, password, security_hash, platform))
        t.start()
        threads.append(t)

    for t in threads: # Wait for all the threads to finish
        t.join()

rawDescription: Assign a thread to each section in an ini file


code:
b = open(a, 'r+')
for line in b:
    if line.startswith("E PRAM") and "OOPS: 1" in line:
        next_line = next(b)
        # do whatever you need

rawDescription: How to access next line in a file(.txt) in Python

description: Access next line in a file(.txt) in Python


code:
#!/usr/bin/env python

import cherrypy

config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  },
}

class App:

  @cherrypy.expose
  def index(self):
    '''For caveats and details on the slippery slope, take a look at ws4py
    https://github.com/Lawouach/WebSocket-for-Python/blob/master/ws4py/server/cherrypyserver.py
    '''
    print(cherrypy.serving.request.rfile.rfile._sock)

    return 'Make sure you know what you are doing.'

if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

rawDescription: Obtaining original destination ip in cherrypy


code:
from django import forms

class MySiteForm(forms.Form):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(MySiteForm, self).__init__(*args, **kwargs)

...

class RegistrationForm(MySiteForm):
    username = forms.CharField(max_length=255)
    ...

rawDescription: Blank label_suffix across entire Django project


code:
import win32serviceutil
import win32service
import win32event
import servicemanager
from multiprocessing import Process

from app import app

class Service(win32serviceutil.ServiceFramework):
    _svc_name_ = "TestService"
    _svc_display_name_ = "Test Service"
    _svc_description_ = "Tests Python service framework by receiving and echoing messages over a named pipe"

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

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        self.process.terminate()
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)

    def SvcDoRun(self):
        self.process = Process(target=self.main)
        self.process.start()
        self.process.run()

    def main(self):
        app.run()

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(Service)

rawDescription: Deploy Flask app as windows service

description: Deploy Flask app as windows service


code:
from psycopg2 import connect
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT

def show_query(title, qry):
    print('%s' % (title))
    cur.execute(qry)
    for row in cur.fetchall():
        print(row)
    print('')

dbname = 'db_name'
print('connecting to default database ...')
con = connect(user ='postgres', host = 'localhost', password = '*****', port=5492)
con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = con.cursor()
show_query('current database', 'SELECT current_database()')
cur.execute('CREATE DATABASE ' + dbname)
show_query('available databases', 'SELECT * FROM pg_database')
cur.close()
con.close()

print('connecting to %s ...' % (dbname))
con = connect(user ='postgres', database=dbname, host = 'localhost', password = '*****', port=5492)
cur = con.cursor()
show_query('current database', 'SELECT current_database()')
cur.close()
con.close()

rawDescription: change database (postgresql) in python using psycopg2 dynamically

description: Change database (postgresql) in python using psycopg2 dynamically


code:
class TablaBaseAdmin(admin.ModelAdmin):

    class Meta:
        exclude = ('tenant',)

class Tabla1Admin(TablaBaseAdmin):
    pass

class Tabla2Admin(TablaBaseAdmin):
    pass

class Tabla3Admin(TablaBaseAdmin):
    pass

rawDescription: Same Options For Different Django Admin Class


code:
tmp = np.concatenate((GRZVV, np.ones((16309,1),dtype=np.double)), axis=1)
EVV1 = np.dot(GinvVV, tmp.T)
#Changed line below based on *askewchan's* recommendation
VVg1 = np.sum(np.multiply(EVV1[:n,:],VV[:,np.newaxis]), axis=0)

rawDescription: How to push the for-loop down to numpy

description: Push the for-loop down to numpy


code: all('__eq__' not in cls.__dict__ for cls in X.mro() if cls is not object)

rawDescription: How to assert class overrides default __hash__ and __eq__

description: Assert class overrides default __hash__ and __eq__


code:
from PyQt4 import QtGui
from PyQt4 import QtCore

class MyHighlighter(QtGui.QTextEdit):
    def __init__(self, parent=None):
        super(MyHighlighter, self).__init__(parent)
        # Setup the text editor
        text = """In this text I want to highlight this word and only this word.\n""" +\
        """Any other word shouldn't be highlighted"""
        self.setText(text)
        cursor = self.textCursor()
        # Setup the desired format for matches
        format = QtGui.QTextCharFormat()
        format.setBackground(QtGui.QBrush(QtGui.QColor("red")))
        # Setup the regex engine
        pattern = "word"
        regex = QtCore.QRegExp(pattern)
        # Process the displayed document
        pos = 0
        index = regex.indexIn(self.toPlainText(), pos)
        while (index != -1):
            # Select the matched text and apply the desired format
            cursor.setPosition(index)
            cursor.movePosition(QtGui.QTextCursor.EndOfWord, 1)
            cursor.mergeCharFormat(format)
            # Move to the next match
            pos = index + regex.matchedLength()
            index = regex.indexIn(self.toPlainText(), pos)

if __name__ == "__main__":
    import sys
    a = QtGui.QApplication(sys.argv)
    t = MyHighlighter()
    t.show()
    sys.exit(a.exec_())

rawDescription: How can I find a substring and highlight it in QTextEdit?

description: Find a substring and highlight it in QTextEdit


code:
import numpy as np
from scipy.stats import mode
data = np.random.randint(1,6, size=(6,8))
data
val, count = mode(data, axis=0)
val
count

rawDescription: Simplest way to find the element that occurs the most in each column


code:
root = logging.getLogger()
root.manager.loggerDict.clear()

rawDescription: Is Python's logging.getLogger scalable with many named loggers?


rawDescription: Add column to Pandas DataFrame based on formula


code: t = Times.objects.exclude(delay=0)

rawDescription: Django Query Filter

description: Django Query Filter


code:
import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

rawDescription: openCV video saving in python

description: OpenCV video saving in python


code:
for i in mylist:
  if i not in newlist:
    newlist.append(i)

rawDescription: Python: How to remove all duplicate items from a list


code:
#Caesar Cipher

#Function that reads and writes data to the file, and calls the encryption and decryption methods.
#It isolates the key and choice of the user, and then calls the appropriate function.
def isolate():
    #Open input file in read mode
    fin = open('Input3.txt', 'r')
    #Open output file in write mode
    fout = open('Out1.txt', 'w')
    #Create a list that holds each line of the file as an element of the list
    container = fin.readlines()

    #For loop that goes through each line of the file (contianed in list) and isolates the choice and key of the user
    #Then it removes the key and choice from the split input list and calls the appropriate method.
    for i in container:
        # List of words, with whitespace and trailing '\n' removed
        words = i.split()

        # Interpret and remove the last two words
        key = int(words[len(words) - 1])
        choice = words[len(words) - 2]
        words.remove(str(key))
        words.remove(choice)

        # Re-join the words of the message. The message may differ from the original if there is consecutive whitespace.
        message = ' '.join(words)
        message = message.upper()

        # Encrypt or decrypt to fout
        if choice == 'e':

            fout.write(encrypt(message, key) + '\n')

        else:
            fout.write(decrypt(message, key) + '\n')

    #Close the file to make sure data is written properly to the file.
    fout.close()

#Encryption method, which takes two parameters, the users message and key, and returns the newly encrypted message.
def encrypt(message, key):
    #Empty string that will contain the encrypted message.
    encrypted_message = ""
    #Alphabet string, which contains all the letters of the alphabet at their index locations.
    alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

    #For loop that goes through each character of the users message and, if a space, adds it straight to the encrypted message or encrypts it through modular division.
    for i in message:
        #If the character is a space, add it to the final message.
        if i == ' ':
            #Concatenate the space to the final message
            encrypted_message += ' '
        #If the character is not a space, determine the final locatin out of index range, % by 26 and re-add the character at this index to the encrypted_message.
        else:
            #Determine the final location of the character (out of index range)
            location = key + alpha.index(i)
            #% this location by 26 to determine the location within the proper index.
            location %= 26
            #Finally, concatenate the letter at this location to the final message.
            encrypted_message += alpha[location]

    #When the function is called, have it return the final encrypted message.
    return encrypted_message

#Decryption method that takes two parameters, the users message and key
def decrypt(message, key):
    #Create a string that reverses the alphabet, since we are moving backwards when we decrypt.
    reverse_alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[::-1]
    decrypted_message = ""

    #For loop that runs through each element of the users message and, if space,  adds it to the message, or encrypts using % division, then concatenates to final message.
    for i in message:
        if i == ' ':
            decrypted_message += ' '
        else:
            #Determine the final location out of index range of the encrypted character
            location = key + reverse_alpha.index(i)
            #% this position by 26 to determine the index location in range of the letter.
            location %= 26
            #Finally, add the letter at this location to the decrypted message.
            decrypted_message += reverse_alpha[location]

    #Converts the decrypted message into lowercase form.
    decrypted_message = decrypted_message.lower()

    return decrypted_message

#Call the function isolate5(), which initiates the program.
isolate()

rawDescription: Ceaser Cipher-Python, using large numbers for shifts


rawDescription: how to get a float with desired precision using python

description: Get a float with desired precision using python


code:
s = "Tuple: " + str(tup)
s

rawDescription: Python: Converting from Tuple to String?

description: Python: Converting from Tuple to String


code:
import spynner
URL = 'https://www.imleagues.com/Login.aspx'
address = "http://www.imleagues.com/School/Team/Home.aspx?Team=27d6c31187314397b00293fb0cfbc79a"

b = spynner.Browser()
b.show()
b.load(URL)
b.runjs('$("#ctl00_ContentPlaceHolder1_inUserName").val("testUser")')
b.runjs('$("#ctl00_ContentPlaceHolder1_inPassword").val("testPass")')

rawDescription: Fill in form using Spynner in Python

description: Fill in form using Spynner in Python


code:
sel_items = listWidget.selectedItems()

for item in sel_items:
    item.setText(item.text() + ' plus more text')

rawDescription: How can I edit a QListWidget item without removing it to edit and adding back?

description: Edit a QListWidget item without removing it to edit and adding back


code:
from __future__ import division
a = 4
b = 6
c = a / b
c

rawDescription: How can I force division to be floating point in Python?

description: Force division to be floating point in Python


code:
X = np.genfromtxt("X.txt",delimiter=" ")
Y = np.genfromtxt("Y.txt",delimiter=" ")

rawDescription: Create a Numpy Array from particular text format


code:
ls = [['kukatpally'], ['gachibowli'], ['Madhapur'], ['Chintal']]
l = [x[0] for x in ls]
l

rawDescription: How do I flatten nested lists in Python?

description: Flatten nested lists in Python


code:
page = 1
url = """http://www.ebay.com/sch/Car-Truck-Parts-/6030/i.html?_from=R40&LH_ItemCondition=4&LH_Complete=1&LH_Sold=1&_mPrRngCbx=1&_udlo=100&_udhi=700&_sop
  =16&_nkw=honda+%281990%2C+1991%2C+1992%2C+1993%2C+1994%2C+1995%2C+1996%2C+
  1997%2C+1998%2C+1999%2C+2000%2C+2001%2C+2002%2C+2003%2C+2004%2C+2005%29&
  _pgn="""+str(page)+"&_skc=50&rt=nc"

has_page = True

myfile = 'c:/users/' + myquery
fw = open(myfile + '.xml', 'w')

while has_page:
    r = requests.get(url)
    soup = BeautifulSoup(r.content, "lxml")
    error_msg = soup.find_all('p', {'class':"sm-md"})
    if len(error_msg) > 0:
        has_page = False
        continue
    for item in soup.find_all('ul',{'class':'ListViewInner'}):
        fw.write(str(item))
        page+=1

fw.close()

rawDescription: tracking frequency of words in an ebay search result

description: Tracking frequency of words in an ebay search result


code:
import multiprocessing as mp
from math import sqrt
worker_pool = mp.Pool()
jobs = [0, 1, 4, 9, 16, 25]
# calculate jobs in blocking batch parallel
results = worker_pool.map(sqrt, jobs)
results
# calculate jobs in asynchronous parallel
results = worker_pool.map_async(sqrt, jobs)
results.get()
# calculate jobs in parallel with an unordered iterator
results = worker_pool.imap_unordered(sqrt, jobs)
list(results)  # NOTE: results may return out of order
# a single blocking job on another process
worker_pool.apply(sqrt, [9])
# a single asynchronous job on another process
y = worker_pool.apply_async(sqrt, [9])
y.get()
# the same interface exists for threads
thread_pool = mp.dummy.Pool()
thread_pool.map(sqrt, jobs)
# finishing up, you should shut down your pools
worker_pool.close()
worker_pool.join()
thread_pool.close()
thread_pool.join()

rawDescription: Python multiprocessing for dummies

description: Python multiprocessing for dummies


code:
def shifter():
    phrase = input("Please enter a message: ")
    key = eval(input("Please enter the number of places to be shifted: "))
    list = phrase.split()
    newPhrase = ""
    for word in list:
        conversion = ''
        for ch in word:
           conversion += (chr)((ord(ch) - ord("a") + key) % 26 + ord("a"))
        newPhrase = newPhrase + conversion + " "
    print(newPhrase)
shifter()

rawDescription: Caesar Cipher in Python 3.4.3

description: Caesar Cipher in Python 3.4.3


code:
from nltk import PorterStemmer
PorterStemmer().stem_word('complications')

rawDescription: Need a python module for stemming of text documents


rawDescription: xpath tag not sure what to put

description: Xpath tag not sure what to put


code:
import json

respBody = resp.read()

responseObject = json.loads(respBody)

rawDescription: Python httplib retrieve json object from getresponse()


code:
class PoolTable(tables.Table):
    class Meta:
        model = Simple
        attrs = {'class': 'paleblue','width':'200%'}

rawDescription: What is the easiest/correct why to change the width of django_tables2 table


code:
lists = [{'firstname': 'John', 'lastname': 'Doe', 'color': 'red'}]

# update value to 30
lists[0]["age"] = 30
print(lists)
# update value to smith
lists[0]["lastname"] = "Smith"
print(lists)
# finally delete using the del statement using the key
del lists[0]["color"]
print(lists)

[{'firstname': 'John', 'lastname': 'Doe', 'age': 30, 'color': 'red'}]
[{'firstname': 'John', 'lastname': 'Smith', 'age': 30, 'color': 'red'}]
[{'firstname': 'John', 'lastname': 'Smith', 'age': 30}]

rawDescription: Append, Remove, Edit a Dictionary Item from List of Dictionary


code:
import tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        b = tk.Button(self, text="Done!", command=self.upload_cor)
        b.pack()
        table = tk.Frame(self)
        table.pack(side="top", fill="both", expand=True)

        data = (
            (45417, "rodringof", "CSP L2 Review", 0.000394, "2014-12-19 10:08:12", "2014-12-19 10:08:12"),
            (45418, "rodringof", "CSP L2 Review", 0.000394, "2014-12-19 10:08:12", "2014-12-19 10:08:12"),
            (45419, "rodringof", "CSP L2 Review", 0.000394, "2014-12-19 10:08:12", "2014-12-19 10:08:12"),
            (45420, "rodringof", "CSP L2 Review", 0.000394, "2014-12-19 10:08:12", "2014-12-19 10:08:12"),
            (45421, "rodringof", "CSP L2 Review", 0.000394, "2014-12-19 10:08:12", "2014-12-19 10:08:12"),
            (45422, "rodringof", "CSP L2 Review", 0.000394, "2014-12-19 10:08:12", "2014-12-19 10:08:12"),
            (45423, "rodringof", "CSP L2 Review", 0.000394, "2014-12-19 10:08:12", "2014-12-19 10:08:12"),
        )

        self.widgets = {}
        row = 0
        for rowid, reviewer, task, num_seconds, start_time, end_time in (data):
            row += 1
            self.widgets[rowid] = {
                "rowid": tk.Label(table, text=rowid),
                "reviewer": tk.Label(table, text=reviewer),
                "task": tk.Label(table, text=task),
                "num_seconds_correction": tk.Entry(table),
                "num_seconds": tk.Label(table, text=num_seconds),
                "start_time": tk.Label(table, text=start_time),
                "end_time": tk.Label(table, text=start_time),
                "checkbox_var": tk.IntVar(),
                "checkbox": tk.Checkbutton(table)
            }

            self.widgets[rowid]["rowid"].grid(row=row, column=0, sticky="nsew")
            self.widgets[rowid]["reviewer"].grid(row=row, column=1, sticky="nsew")
            self.widgets[rowid]["task"].grid(row=row, column=2, sticky="nsew")
            self.widgets[rowid]["num_seconds_correction"].grid(row=row, column=3, sticky="nsew")
            self.widgets[rowid]["num_seconds"].grid(row=row, column=4, sticky="nsew")
            self.widgets[rowid]["start_time"].grid(row=row, column=5, sticky="nsew")
            self.widgets[rowid]["end_time"].grid(row=row, column=6, sticky="nsew")

            self.widgets[rowid]["checkbox"].config(variable=(self.widgets[rowid]["checkbox_var"]))
            self.widgets[rowid]["checkbox"].grid(row=row, column=7, sticky="nsew")

        table.grid_columnconfigure(1, weight=1)
        table.grid_columnconfigure(2, weight=1)
        # invisible row after last row gets all extra space
        table.grid_rowconfigure(row+1, weight=1)

    def upload_cor(self):
        for rowid in sorted(self.widgets.keys()):
            entry_widget = self.widgets[rowid]["num_seconds_correction"]
            new_value = entry_widget.get()
            print("%s: %s" % (rowid, new_value))

        for rowid in sorted(self.widgets.keys()):
            check_var = self.widgets[rowid]["checkbox_var"]
            print(check_var.get())
            if check_var.get():
                print('Check button checked')

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: Create checkboxes programatically and the get their values with tkinter


code:
import csv

def loadCSVfile (path):
    exclusions = ['@', '%', '\n', '[@' , '[%']
    csvData = open(path, 'r')
    spamreader = csv.reader(csvData, delimiter=',', quotechar='|')

    lines = [line for line in spamreader if ( line and line[0][0:1] not in exclusions and line[0][0:2] not in exclusions )]

    for line in lines:
        print(line)

loadCSVfile('C:/Users/anaim/Desktop/Data Mining/OneR/iris.arff')

rawDescription: Python how to filter string based on substring


code: smaller_array =np.delete(array,index)

rawDescription: Delete the elements of a array with a mask


code:
from IPython.core.interactiveshell import InteractiveShell
from IPython.core.history import HistoryManager

def migrate_history(old_histfile, new_histfile):
    """populate an IPython sqlite history from an old readline history file"""
    # shell = InteractiveShell.instance()
    history = HistoryManager(hist_file=new_histfile,
        # this line shouldn't be necessary, but it is in 0.13
        shell = InteractiveShell.instance()
    )

    with open(old_histfile) as f:
        # iterate through readline history,
        # and write to the new history database
        for linenum, line in enumerate(f):
            history.store_inputs(linenum, line)

rawDescription: Recovering / Importing missing IPython history after an upgrade


code: #!/usr/bin/true

rawDescription: How do I mark a .txt file as "not executable"?

description: Mark a .txt file as "not executable"


code:
df_list = []
df_list[0]
df_list[1]

rawDescription: Make seperate pandas data frames per header


code:
'''
CheckBox Test
References:
 http://effbot.org/tkinterbook/checkbutton.htm
'''

from tkinter import *

class App:

    def __init__(self, master):
        self.var = IntVar() #This is the variable bounded to checkbutton to
                            #get the checkbutton state value
        #
        frame = Frame(master)
        frame.pack()

        self.checkbutton = Checkbutton(frame, text="Hello Checkbutton",
                                       command=self.say_hello, variable=self.var)
        self.checkbutton.pack(side=LEFT)
        #
        self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
        self.button.pack(side=LEFT)

    def say_hello(self):
        '''
         Function Bounded to Checkbutton in command parameter, every click
         either check or un-check print the current state of the checkbutton
        '''
        print("State Changed:", self.var.get())

if __name__ == '__main__':
    root = Tk()
    app = App(root)
    #
    root.mainloop()
    root.destroy() # Quit the App when you click "Quit"

rawDescription: Python 3.x tkinter - can't get checkbox' variable value


code:
def get_nodes(l):
    # Recursion base
    if l is None: return ([], [])
    if l.children is None: return ([], [l])

    # Recursion step
    this = ([l], [])
    internal, leaf = get_nodes(l.children.left)
    this[0] += internal
    this[1] += leaf

    internal, leaf = get_nodes(l.children.right)
    this[0] += internal
    this[1] += leaf

    return this

rawDescription: A Binary Tree method

description: A Binary Tree method


rawDescription: Independence of variables bound to NumPy arrays


rawDescription: python.exe crashes (used all system allowance of handles for Window Manager objects)

description: Python.exe crashes (used all system allowance of handles for Window Manager objects)


code:
def readline(a_serial, eol=b'\n\n'):
    leneol = len(eol)
    line = bytearray()
    while True:
        c = a_serial.read(1)
        if c:
            line += c
            if line[-leneol:] == eol:
                break
        else:
            break
    return bytes(line)

rawDescription: Python: serial.readline() - how to define the EOL from \n to \n\n


code:
d = []
for index, tup in enumerate(lst):
    if tup[2] != 0:
        for next in lst[index + 1:]:
            if next[2] == 0 and tup[1] == next[1]:
                d.append(next[0] - tup[0])
                break
        if len(d) - 1 != index:
            d.append('NA')
    else:
        d.append('NA')

rawDescription: python - find position of next item in list, given criteria

description: Python - find position of next item in list, given criteria


code:
def quicksort(lista,izq,der):
  i = izq
  j = der
  swap_count = 0
  compare_count = 0
  pivote = lista[(izq + der)//2]

  while i <= j:
    while lista[i] < pivote:
      i += 1
    while pivote < lista[j]:
      j -= 1
    if i <= j:
      aux = lista[i]
      lista[i] = lista[j]
      lista[j] = aux
      swap_count += 1
      i += 1
      j -= 1
    compare_count += 1

  if izq < j:
    other_swap, other_compare = quicksort(lista, izq, j)
    swap_count += other_swap
    compare_count += other_compare
  if i < der:
    other_swap, other_compare = quicksort(lista, i, der)
    swap_count += other_swap
    compare_count += other_compare

  return (swap_count, compare_count)

rawDescription: How to count swaps in a quicksort? (Python)

description: Count swaps in a quicksort? (Python)


code:
A = np.random.random((2,4,3,5))
B = np.einsum('klij->ijkl', A)
A.shape
B.shape
import itertools as IT
all(B[k,l,i,j] == A[i,j,k,l] for i,j,k,l in IT.product(*map(range, A.shape)))

rawDescription: Swapping the dimensions of a numpy array


code:
import os, cgi
fs = cgi.FieldStorage()
fileitem = fs['userfile']

# Test if the file was uploaded
if fileitem.filename:
   fn = os.path.basename(fileitem.filename)
   open('/tmp/' + fn, 'wb').write(fileitem.file.read())
   message = 'The file "' + fn + '" was uploaded successfully'
else:
   message = 'No file was uploaded'

rawDescription: In my Python CGI script, how do I save to disk a file uploaded via POST request of data entered by the user in a form?


rawDescription: How to add new value to a list without using 'append()' and then store the value in a newly created list?

description: Add new value to a list without using 'append()' and then store the value in a newly created list


rawDescription: Python PIL struggles with uncompressed 16-bit TIFF images


code:
from numpy import array
myVector = array([Vx, Vy, Vz])
myMatrix = array([[Vx, Vy, Vz], [1,2,3]])

rawDescription: creating a numpy vector using 3 components

description: Creating a numpy vector using 3 components


code:
def getIn(d, arraypath, default=None):
    if not d:
        return d
    if not arraypath:
        return d
    else:
        return getIn(d.get(arraypath[0]), arraypath[1:], default) \
            if d.get(arraypath[0]) else default

getIn(specificNode,["parent", "parent", "parent", "header", "title"]) is not None

rawDescription: Check if object path exists in tree of objects


rawDescription: constructor inheriting self python

description: Constructor inheriting self python


rawDescription: Python wont run with Task Scheduler but will run normally?


code:
import re
r = re.compile(r'(?P<name>[^.]+)\.S(?P<S>\d+)E(?P<E>\d+)\.(?P<title>[^.]+)\.(?P<ext>.*)')
r.search('Dexter.S01E01.The Monster.mp4').groupdict()
r.search('The Mentalist.S03E05.Red Lay.mp4').groupdict()

rawDescription: Creating Regex for a file name (python)

description: Creating Regex for a file name (python)


code:
def readmarkers(file, mmap=False):
    if hasattr(file,'read'):
        fid = file
    else:
        fid = open(file, 'rb')
    fsize = _read_riff_chunk(fid)
    cue = []
    while (fid.tell() < fsize):
        chunk_id = fid.read(4)
        if chunk_id == b'cue ':
            size, numcue = struct.unpack('<ii',fid.read(8))
            for c in range(numcue):
              id, position, datachunkid, chunkstart, blockstart, sampleoffset = struct.unpack('<iiiiii',fid.read(24))
              cue.append(position)
        else:
            _skip_unknown_chunk(fid)
    fid.close()
    return cue

rawDescription: read markers of .wav file

description: Read markers of .wav file


code:
def get_sensor_output():
    #
    # Lot of initialisation... forget that part
    #

    accel_xout = read_word_2c(0x3b)
    accel_yout = read_word_2c(0x3d)
    accel_zout = read_word_2c(0x3f)
    afs_sel = read_word_2c(0x28)
    LSB_afs_sel = 16384.0

    accel_xout_sc = accel_xout / LSB_afs_sel
    accel_yout_sc = accel_yout / LSB_afs_sel
    accel_zout_sc = accel_zout / LSB_afs_sel

    i2c_output = str(accel_xout_sc) + str(accel_yout_sc) + str(accel_zout_sc)

    return i2c_output

class Index:
  def GET(self):
    return get_sensor_output()

rawDescription: Python Web application: Refresh values

description: Python Web application: Refresh values


code:
import numpy as np
import re

def atoi(text):
    try:
        return int(text)
    except ValueError:
        return text

def natural_keys(text):
    '''
    alist.sort(key=natural_keys) sorts in human order
    http://nedbatchelder.com/blog/200712/human_sorting.html
    '''
    return [ atoi(c) for c in re.split('([-]?\d+)', text) ]

a = np.array(["3", "-2", "-1", "0", "2", "word"])
print(sorted(a,key=natural_keys))
# ['-2', '-1', '0', '2', '3', 'word']

a = np.array(["3", "-2", "-1", "0", "2", "word", "-1 word", "-2 up"])
print(sorted(a,key=natural_keys))
# ['-2', '-2 up', '-1', '-1 word', '0', '2', '3', 'word']

rawDescription: Sort numpy string array with negative numbers?


code:
plt.rcParams['xtick.labelsize'] = "xx-small"
plt.rcParams['ytick.labelsize'] = "xx-small"

rawDescription: Matplotlib format the scale label

description: Matplotlib format the scale label


rawDescription: plot a matplotlib line with a given slope

description: Plot a matplotlib line with a given slope


code:
name = 'https://www.dropbox.com/s/sbyuft7zscqzgbs/checklist%281%29.pdf?dl=0'
name.split('/')[-1].split('?')[0]

rawDescription: How to exctract a part of a url in this case?

description: Exctract a part of a url in this case


code:
for obj in MyModel.objects.all():
    value = ast.literal_eval(obj.dict_value)
    obj.dict_value = json.dumps(value)
    value.save()

rawDescription: Getting text from db as django dictionary


code:
'abc' > 'bac'
ord('a'), ord('b')

rawDescription: String Comparison Technique Used by Python


code:
from django.db import models
from django_enumfield import enum

class DrinkStyle(enum.Enum):
    LAGER = (0, 'Beer')
    STOUT = (1, 'Beer')
    WEISSBIER = (2, 'Beer')
    COKE = (3, 'SoftDrink')
    LEMONADE = (4, 'SoftDrink')

    def __init__(self, id, drink_type):
        self.id = id
        self.type = drink_type

    @property
    def type(self):
        return self.drink_type

class Drink(models.Model):
    style = enum.EnumField(DrinkStyle, default=DrinkStyle.LAGER)

rawDescription: How can I combine/nest EnumFields in Django?

description: Combine/nest EnumFields in Django


code:
import cv

# get orginal image
orig = cv.LoadImage('fling.png')

# show original
cv.ShowImage("orig", orig)

# blur a bit to remove higher frequency variation
cv.Smooth(orig,orig,cv.CV_GAUSSIAN,5,5)

# normalise RGB
norm = cv.CreateImage(cv.GetSize(orig), 8, 3)
red = cv.CreateImage(cv.GetSize(orig), 8, 1)
grn = cv.CreateImage(cv.GetSize(orig), 8, 1)
blu = cv.CreateImage(cv.GetSize(orig), 8, 1)
total = cv.CreateImage(cv.GetSize(orig), 8, 1)
cv.Split(orig,red,grn,blu,None)
cv.Add(red,grn,total)
cv.Add(blu,total,total)
cv.Div(red,total,red,255.0)
cv.Div(grn,total,grn,255.0)
cv.Div(blu,total,blu,255.0)
cv.Merge(red,grn,blu,None,norm)
cv.ShowImage("norm", norm)

# posterize simply with mean shift filtering
post = cv.CreateImage(cv.GetSize(orig), 8, 3)
cv.PyrMeanShiftFiltering(norm,post,20,30)
cv.ShowImage("post", post)

rawDescription: Rudimentary Computer Vision Techniques for Python Bot.


code:
from PyQt4 import QtGui

class ProductListItem(QtGui.QStandardItem):
    def __lt__(self, other):
        listview = self.model().parent()
        this_widget = listview.indexWidget(self.index())
        other_widget = listview.indexWidget(other.index())
        return this_widget.getText() < other_widget.getText()

class ProductItemWidget(QtGui.QWidget):
    def __init__(self, product_name, parent=None):
        super(ProductItemWidget, self).__init__(parent)
        self.label = QtGui.QLabel(product_name, self)
        layout = QtGui.QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.label)

    def getText(self):
        return self.label.text()

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.list = QtGui.QListView(self)
        layout = QtGui.QHBoxLayout(self)
        layout.addWidget(self.list)
        # model must have the listview as parent
        model = QtGui.QStandardItemModel(self.list)
        self.list.setModel(model)
        for key in 'MHFCLNIBJDAEGK':
            item = ProductListItem()
            model.appendRow(item)
            widget = ProductItemWidget('Item %s' % key, self.list)
            self.list.setIndexWidget(item.index(), widget)
        model.sort(0)

if __name__ == '__main__':

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

rawDescription: Can I override the inputs to the __lt__ comparator of a QListWidgetItem? (PyQt)

description: Override the inputs to the __lt__ comparator of a QListWidgetItem? (PyQt)


code: new_list  = [i for i in text_words1 if not i.startswith(('@','#'))]

rawDescription: How to clean some some strings in the list?

description: Clean some some strings in the list


code:
def replace_score(file_name, line_num, text):
  f = open(file_name, 'r')
  contents = f.readlines()
  f.close()

  contents[line_num] = text+"\n"

  f = open(file_name, "w")
  contents = "".join(contents)
  f.write(contents)
  f.close()

replace_score("file_path", 10, "replacing_text")

rawDescription: How to add a value to a specific line in a file in python?

description: Add a value to a specific line in a file in python


code: sql = "UPDATE %s SET TIMESTAMP = '%s'" % (TLA_dict['TLA_name'], config.time.strftime("%Y-%m-%d %H:%M:%S", config.time.localtime(config.time.time())))

rawDescription: python mysql update timestamp

description: Python mysql update timestamp


code: float('%s%sE%s' % ('+' if sign == '0' else '-', significant, exponent))

rawDescription: Returning the Python floating point number from the string representation of its sign, exponent and significant


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

import time
import os

class Application(Frame):
    def __init__(self, parent):
       Frame.__init__(self,parent)
       self.pack(fill=BOTH)

       self.create_widgets()

    def create_widgets(self):
        self.borderFrame = Frame(self, width=500, height=600, bg="Gray")
        self.borderFrame.pack_propagate(False)
        self.borderFrame.pack(side=TOP)

        self.holderFrame = Frame(self.borderFrame, width=500, height=570, bg="blue")
        self.holderFrame.pack_propagate(False)
        self.holderFrame.pack(side=BOTTOM)

        self.close = Label(self, font=("Arial", 11), bg="Gray", anchor=CENTER, text="X", cursor="hand2")
        self.close.place(x=460, y=0, width=40, height=30)

        self.min = Label(self, font=("Arial", 11), bg="Gray", anchor=CENTER, text="_", cursor="hand2")
        self.min.place(x=420, y=0, width=40, height=30)

        def hoverMin(event):
            event.widget.config(bg="lightBlue")

        def unHoverMin(event):
            event.widget.config(bg="Gray")

        self.min.bind("<Enter>", hoverMin)
        self.min.bind("<Leave>", unHoverMin)
        self.min.bind("<Button-1>", self.minimize)

        def hover(event):
            event.widget.config(bg="red")

        def unhover(event):
            event.widget.config(bg="Gray")

        self.close.bind("<Enter>", hover)
        self.close.bind("<Leave>", unhover)
        self.close.bind("<Button-1>", self.exitProgram)

        self.borderFrame.bind("<Button-1>", self.startMove)
        self.borderFrame.bind("<ButtonRelease-1>", self.stopMove)
        self.borderFrame.bind("<B1-Motion>", self.moving)

        self.borderFrame.bind("<Map>",self.frame_mapped)

    def startMove(self, event):
        self.x = event.x
        self.y = event.y

    def stopMove(self, event):
        self.x = None
        self.y = None

    def moving(self,event):
        x = (event.x_root - self.x - self.borderFrame.winfo_rootx() + self.borderFrame.winfo_rootx())
        y = (event.y_root - self.y - self.borderFrame.winfo_rooty() + self.borderFrame.winfo_rooty())
        root.geometry("+%s+%s" % (x, y))

    def frame_mapped(self,e):
        print(self,e)
        root.update_idletasks()
        root.overrideredirect(True)
        root.state('normal')

    def minimize(self, event):
        root.update_idletasks()
        root.overrideredirect(False)
        #root.state('withdrawn')
        root.state('iconic')

    def exitProgram(self, event):
        os._exit(0)

root = Tk()
root.title("Draggable Root")
root.geometry("500x600")
root.overrideredirect(True)

app = Application(root)

root.mainloop()

rawDescription: TclError: can't iconify: override-redirect flag is set


code:
def create(self, cr, uid, values, context=None):

    values['your_hash_column'] = 'your_hash_result'

    res = super(YourClassName, self).create(cr, uid, ids, values, context)

    return res

rawDescription: What is the class/file that creates invoices in openerp 7


code:
idmap = {}
idmap[id(x)] = y

rawDescription: Is there a Python equivalent of Java's IdentityHashMap?


code:
import collections

def approximate_song(filename):
    text = open(filename).read()
    counts = collections.Counter(text.lower().split())

    return [elem for elem, _ in sorted(counts.most_common(), key=lambda
                                   x: (-x[1], x[0]))[:1]][0]

print(approximate_song('README.txt'))

rawDescription: Remove unwanted '[' and ']' in final output


code:
import random

class RandomFunctions(object):

    def f1(self):
        print("1")

    def f2(self):
        print("2")

    def f3(self):
        print("3")

    def execute(self):
        if not getattr(self, 'functions', None):
            self.functions = [self.f1, self.f2, self.f3]
            random.shuffle(self.functions)
        return self.functions.pop()

def main():
    f = RandomFunctions()
    for i in range(6):
        f.execute()()

main()

rawDescription: Python - Function array class

description: Python - Function array class


code: variable = read_file() or "File was empty"

rawDescription: Do Python Inline if statements execute a function twice?


code:
j=[];
for row in ... :
    i = []
    for value in quoted.findall(str(row[2])):
        i.append(value.replace('"', '').strip())

    j.append(i)

rawDescription: how do i make list of list python

description: Make list of list python


code:
if len(a.shape) == 1:
    a = a[..., np.newaxis]

# or this, if you need more generality:
a = a.reshape(a.shape + (1,) * (desired_dimensions - len(a.shape)))

rawDescription: Force 2-dimensionality in vector

description: Force 2-dimensionality in vector


code: {k:dict1.get(k) for k in list1}

rawDescription: Copy multiple items between dictionaries


code:
import numpy as np
import pylab as pl
import random
import string
import math
random.seed(0)
np.random.seed(0)
n = 100
labels = ["".join(random.sample(string.ascii_letters, random.randint(4, 10))) for _ in range(n)]
x, y = np.random.randn(2, n)

fig, ax = pl.subplots()

ax.scatter(x, y)

ann = []
for i in range(n):
    ann.append(ax.annotate(labels[i], xy = (x[i], y[i])))

mask = np.zeros(fig.canvas.get_width_height(), bool)

fig.canvas.draw()

for a in ann:
    bbox = a.get_window_extent()
    x0 = int(bbox.x0)
    x1 = int(math.ceil(bbox.x1))
    y0 = int(bbox.y0)
    y1 = int(math.ceil(bbox.y1))

    s = np.s_[x0:x1+1, y0:y1+1]
    if np.any(mask[s]):
        a.set_visible(False)
    else:
        mask[s] = True

rawDescription: Non-overlapping scatter plot labels using matplotlib


code:
class MyMailNotifier(MailNotifier):
    def isMailNeeded(self, build, results):
        if build.properties.getProperty('scheduler') == '<SingleBranchSchedulerName>':
            return MailNotifier.isMailNeeded(self, build, results)
        else:
            return False

rawDescription: Buildbot deactivate mail notifier for some schedulers (not for builders)


code: numpy.clip(x, 0, 255)

rawDescription: Forcing Elements in a Numpy Array to be Within a Specified Range


code:
import os
import time
import datetime

while True:
    os.system("echo " + "sample line with timestamp:{0}".format(datetime.datetime.now()) + " >> " + " sample.csv")
    time.sleep(5)

rawDescription: Replicating "tail -f" with Python

description: Replicating "tail -f" with Python


code:
myvar1 = 1
myvar2 = True
del myvar1
del myvar2

rawDescription: How delete all variables available in python to free memory?


code:
import re

import numpy as np

def parser(s):
    for i in re.findall('[a-zA-Z]+', s):
        s = s.replace(i, '')
    return s.replace('=', '').replace(';',' ')

gen = (parser(line) for line in open('demo.txt'))
np.genfromtxt(gen, comments='#', usecols=(0, 1, 2, 3))

rawDescription: Use np.loadtxt to split a column while reading


code:
with open('/tmp/test.tsv') as infile, open('/tmp/test2.tsv', 'w') as outfile:
    for line in infile:
        tsplit = line.split("\t")
        firstcolumns = tsplit[:-1]
        lastitems = tsplit[-1].strip().split(";")
        for item in lastitems:
            allcolumns = firstcolumns + item.split("=")
            outfile.write("\t".join(allcolumns) + "\n")

rawDescription: Extract data from tsv file python

description: Extract data from tsv file python


code:
from PIL import Image, ImageTk
from Tkinter import Tk, Label

root = Tk()

def RBGAImage(path):
    return Image.open(path).convert("RGBA")

face = RBGAImage("faces/face.gif")
eyes = RBGAImage("faces/eyes1.png")

face.paste(eyes, (0, 0), eyes)

facepic = ImageTk.PhotoImage(face)

label1 = Label(image=facepic)
label1.grid(row = 0, column = 0)

root.mainloop()

rawDescription: Tkinter Image transparency

description: Tkinter Image transparency


code:
import glob
import os
import pandas

my_directories = ['/path/to/first', '/path/to/second', ..., '/path/to/nth']
for my_dir in my_directories:
    stata_files = glob.glob(os.path.join(my_dir, '*.dta'))  # collects all the stata files
    for file in stata_files:
         # get the file path/name without the ".dta" extension
         file_name, file_extension = os.path.splitext(file)

         # read your data
         df = pandas.read_stata(file, ...)

         # save the data and never think about stata again :)
         df.to_csv(file_name + '.csv')

rawDescription: Conversion of files to .csv from .dta(stata)


code:
import numpy as np

# load csv data
data = np.loadtxt('data.txt', delimiter=',')
# m is the number of columns minus one
m = data.shape[1]-1
# use slicing to extract subarrays
pred = data[:,:m]
resp = data[:,m]

rawDescription: splitting an array into predictor matrix and response vector

description: Splitting an array into predictor matrix and response vector


code: df['GroupNumber'] = pd.factorize(df.Column1 + ' ' + df.Column2)

rawDescription: Numbering Groups In Pandas DataFrame

description: Numbering Groups In Pandas DataFrame


code:
from distutils.sysconfig import get_python_inc
get_python_inc() #this gives the include dir

rawDescription: Find python header path from within python?


code:
for sprite in sprites:
    if something.distance(sprite) < THRESHOLD:
        do_something_with_near_sprite(sprite)

rawDescription: Pygame - How to detect if sprites are in area?


code:
import urllib2
req = urllib2.Request(url)
req.add_header('Cache-Control', 'max-age=0')
resp = urllib2.urlopen(req)
content = resp.read()

rawDescription: urllib.urlopen returns an old page?

description: Urllib.urlopen returns an old page


code:
myString = "spam\\neggs"
decoded_string = bytes(myString, "utf-8").decode("unicode_escape") # python3
decoded_string = myString.decode('string_escape') # python2
print(decoded_string)

rawDescription: Process escape sequences in a string in Python


code: df[df > .01].min(axis=1)

rawDescription: Calculate minimums in Pandas without `zero`-values?


code:
from twisted.internet.protocol import ClientFactory

class EchoClientFactory(ClientFactory):
    def clientConnectionLost(self, connector, reason):
        connector.connect()

rawDescription: Restarting a Twisted-python Reactor after an unsuccessful connection


code:
import urllib2
import BeautifulSoup
import re

Newlines = re.compile(r'[\r\n]\s+')

def getPageText(url):
    # given a url, get page content
    data = urllib2.urlopen(url).read()
    # parse as html structured document
    bs = BeautifulSoup.BeautifulSoup(data, convertEntities=BeautifulSoup.BeautifulSoup.HTML_ENTITIES)
    # kill javascript content
    for s in bs.findAll('script'):
        s.replaceWith('')
    # find body and extract text
    txt = bs.find('body').getText('\n')
    # remove multiple linebreaks and whitespace
    return Newlines.sub('\n', txt)

def main():
    urls = [
        'http://www.stackoverflow.com/questions/5331266/python-easiest-way-to-scrape-text-from-list-of-urls-using-beautifulsoup',
        'http://stackoverflow.com/questions/5330248/how-to-rewrite-a-recursive-function-to-use-a-loop-instead'
    ]
    txt = [getPageText(url) for url in urls]

if __name__=="__main__":
    main()

rawDescription: Python - Easiest way to scrape text from list of URLs using BeautifulSoup


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

def sphere_depth(x, y, depth, radius):
  squ = x**2 + y**2
  rsqu = radius**2
  squ[squ > rsqu] = rsqu
  res = np.sqrt(rsqu - squ)
  res -= (radius - depth)
  res[res < 0.] = 0.
  return res

y_pix = x_pix = 100.

c_steps = 10

x, y = np.mgrid[0:x_pix:1, 0:y_pix:1]
z = sphere_depth(x - x_pix / 2, y - y_pix / 2, 5., 100.)
lvls = np.linspace(z.min(), z.max(), c_steps)

fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.contourf(x, y, z, levels=lvls, cmap=plt.cm.gray,
            vmin=np.mean(lvls[:2]), vmax=np.mean(lvls[-2:]))
ax.axis('off')

plt.show()

rawDescription: Matplotlib "gray" colormap doesn't span full black to white range


code:
def getIndexFromDB(self, user, username, domID):
    with lite.connect(self.DBName) as con:
        cur = con.cursor()
        cur.execute('PRAGMA foreign_keys = ON')
        cur.execute('select idx from Upass where username = ? and uname = ? and dom = ?', (user, username, domID))
        data = cur.fetchone()
    data = data or None
    return data

rawDescription: Pycharm warning that variable is unused

description: Pycharm warning that variable is unused


code:
def stop(self):
    self.running = False
    socket.socket(socket.AF_INET,
                  socket.SOCK_STREAM).connect( (self.hostname, self.port))
    self.socket.close()

rawDescription: Close listening socket in python thread

description: Close listening socket in python thread


code:
import itertools

for match in itertools.chain(re.finditer(pattern_1, text), re.finditer(pattern_2, text)):
    pass

rawDescription: Adding up re.finditer results

description: Adding up re.finditer results


rawDescription: Python and Gtk - which GTK version is being used?


code:
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
someX, someY = 0.5, 0.5
fig,ax = plt.subplots()
currentAxis = plt.gca()
currentAxis.add_patch(Rectangle((someX - 0.1, someY - 0.1), 0.2, 0.2,
                      alpha=1, facecolor='none'))

rawDescription: Drawing rectangle with border only in matplotlib


code:
# changes vs. original recipe at http://code.activestate.com/recipes/576696/:
# added a position parameter to add
# changed how pop works, and added popleft
# added find, get_start, get_end, next_pos, prev_pos, __getitem__, __setitem__

class OrderedSetPlus(collections.MutableSet, collections.Iterable):
    '''
    >>> oset = OrderedSetPlus([3, 3, 3, 2, 1, 8, 8])
    >>> oset.add(13)
    >>> p = oset.find(2)
    >>> oset.add(15, p)
    >>> oset
    OrderedSetPlus([3, 15, 2, 1, 8, 13])
    >>> p = oset.next_pos(p)
    >>> oset[p]
    1
    >>> oset.add(7, p)
    >>> oset
    OrderedSetPlus([3, 15, 2, 7, 1, 8, 13])
    >>> oset[p] = 20
    >>> oset
    OrderedSetPlus([3, 15, 2, 7, 20, 8, 13])
    '''

    class DuplicateElement(Exception):
        pass

    def __init__(self, iterable=None):
        self.end = end = []
        end += [None, end, end]         # sentinel node for doubly linked list
        self.map = {}                   # key --> [key, prev, next]
        if iterable is not None:
            self |= iterable

    def __len__(self):
        return len(self.map)

    def __contains__(self, key):
        return key in self.map

    def find(self, key):
        return self.map.get(key, None)

    # inserts element before the specified position
    # if pos is None, inserts at the end
    # position can only be obtained by calling instance methods
    def add(self, key, pos = None):
        if pos is None:
            pos = self.end
        if key not in self.map:
            curr = pos[PREV]
            curr[NEXT] = pos[PREV] = self.map[key] = [key, curr, pos]

    def discard(self, key):
        if key in self.map:
            key, prev, next = self.map.pop(key)
            prev[NEXT] = next
            next[PREV] = prev

    def __iter__(self):
        end = self.end
        curr = end[NEXT]
        while curr is not end:
            yield curr[KEY]
            curr = curr[NEXT]

    def get_end(self):
        return self.end[PREV]

    def get_start(self):
        return self.end[NEXT]

    def next_pos(self, pos):
        pos = pos[NEXT]
        return None if pos is self.end else pos

    def prev_pos(self, pos):
        pos = pos[PREV]
        return None if pos is self.end else pos

    def __getitem__(self, pos):
        return pos[KEY]

    def __setitem__(self, pos, key):
        if key in self.map:
            raise DuplicateElement
        pos[KEY] = key

    def __reversed__(self):
        end = self.end
        curr = end[PREV]
        while curr is not end:
            yield curr[KEY]
            curr = curr[PREV]

    def popleft(self):
        return self.pop(pos = self.get_start())

    def pop(self, pos=None):
        if not self:
            raise IndexError()
        if pos is None:
            pos = self.get_end()
        key = self[pos]
        #key = next(reversed(self)) if last else next(iter(self))
        self.discard(key)
        return key

    def __repr__(self):
        return '{}({})'.format(self.__class__.__name__, list(self))

    def __eq__(self, other):
        if isinstance(other, OrderedSet):
            return len(self) == len(other) and list(self) == list(other)
        return set(self) == set(other)

rawDescription: How can I implement a data structure that preserves order and has fast insertion/removal?

description: Implement a data structure that preserves order and has fast insertion/removal


code:
import sys
from PIL import Image

def floodfill(img, seed, color):
    im = img.load()
    work = [seed]
    start_color = im[seed]
    while work:
        x, y = work.pop()
        im[x, y] = color
        for dx, dy in ((-1,0), (1,0), (0,-1), (0,1)):
            nx, ny = x + dx, y + dy
            if im[nx, ny] == start_color:
                work.append((nx, ny))

USA_MAP = Image.open(sys.argv[1]).convert('1')
POINT_STATE = {'AL': (420, 260), 'AZ': (110, 240), 'AR': (350, 250)}

painted_map = USA_MAP.convert('L')
data = {'AL': 10.5, 'AZ': 23.4, 'AR': 15.0}
# Normalize data based on the minimum weight being 0+eps and maximum 30.
for k, v in data.items():
    v = v/30.
    color = int(round(255 * v))
    floodfill(painted_map, POINT_STATE[k], 255 - color)

painted_map.save(sys.argv[2])

rawDescription: Making a weighted USA map based on state-level data


code:
df = pd.DataFrame([1, 2, 3, 4, 5, 6, 7, 8], columns=['data'])
mask = 0b1100
np.bitwise_and(df['data'], mask)

rawDescription: Bitwise operations in Pandas that return numbers rather than bools?


code:
s = 'one'
filter(str.isalnum, s.title())
s = 'hello_world'
filter(str.isalnum, s.title())

s = 'foo_bar_baz'
filter(str.isalnum, s.title())

rawDescription: Python: convert variable-like strings to class-like strings


code:
#inside __init__
self.pathVar = tk.StringVar()
self.path = tk.Entry(textvariable=self.pathVar)
self.path.grid(row=1, column=1, sticky='we')

#...

if __name__ == '__main__':
    root = tk.Tk()
    app = ImageSelect(master=root)
    app.mainloop()
    print(app.pathVar.get())

rawDescription: Python Tkinter - Get value from Entry after root.destroy()


code:
import numpy as np
a = np.matrix([[1, 1, 1],
             [1, 2, 3],
             [3, 3, 3]])

prod_diag = a.diagonal().prod()
print(prod_diag)
# gives 6 as answer

rawDescription: Numpy - Calculating product of a diagonal


code:
import omdb
tv_show_name = "hannibal"
movie = omdb.get(title=tv_show_name, fullplot=True, media_type="series")
rating = movie.imdb_rating

rawDescription: imdbpy rating data missing

description: Imdbpy rating data missing


code:
xl = win32com.client.DispatchEx("Excel.Application")
wb = xl.workbooks.open("C:\file.xlsm")
xl.run("file.xlsm!macro")
xl.Visible = True
wb.Close(savechanges=1)
xl.Quit()

rawDescription: python Win32 Save

description: Python Win32 Save


code:
logcurrent = logging.getLogger("app")
if not logcurrent.hasHandlers():
    logcurrent.setLevel(logging.INFO)
    formatter = logging.Formatter(
        '%(message)s',
        '%d-%m-%Y %I:%M:%S',
    )
    file_handlerCurrent = logging.handlers.WatchedFileHandler(
        '/var/log/app.log'
    )
    file_handlerCurrent.setLevel(logging.INFO)
    file_handlerCurrent.setFormatter(formatter)
    logcurrent.addHandler(file_handlerCurrent)

def change_all_handlers_to(handler):
    logcurrent.handlers = []
    logcurrent.addHandler(handler)

def remove_first_handler():
    if logcurrent.hasHandlers():
        del logcurrent.handlers[0]

rawDescription: Logger with reload duplicate logs printing


code:
def extractURL(self,fileName):

    wordsInLine = []
    tempWord = []
    urlList = []

    #open up the file containing the email
    file=open(fileName)
    for line in file:
        #create a list that contains is each word in each line
        wordsInLine = line.split(' ')
        #For each word try to split it with :
        for word in wordsLine:
            tempWord = word.split(":")
            #Check to see if the word is a URL
            if len(tempWord) == 2:
                if tempWord[0] == "http":
                    urlList.append(word)
    file.close()

    return urlList

rawDescription: Extract URLs out of email in Python

description: Extract URLs out of email in Python


code:
from selenium.webdriver.common.action_chains import ActionChains

saveas = ActionChains(driver).key_down(Keys.CONTROL)\
         .send_keys('s').key_up(Keys.CONTROL)
saveas.perform()

rawDescription: Python Selenium: Save Web Page

description: Python Selenium: Save Web Page


code:
import re
tag_string = "001003004"
regex = re.compile("\d{3}")
tag_list = map(int, regex.findall(tag_string))

rawDescription: Django - URL regex pattern

description: Django - URL regex pattern


code:
import random
num = sorted([random.randint(0,27000000/4)*4 for i in range(50000000/4)])

lines_to_write = 0
with open("all.fastq", "r") as fastq:
    with open("sub.fastq", "w") as subset:
        for i,line in enumerate(fastq):
            if len(num)==0:
                break
            if i == num[0]:
                num.pop(0)
                lines_to_write = 4
            if lines_to_write>0:
                lines_to_write -= 1
                subset.write(line)

rawDescription: Go to a specific line and read the next few in Python


code:
import inspect

for func in dir(m):  # `func`: str
    if inspect.isfunction(getattr(m, func)):  # <----
        print(func)

rawDescription: Python Inspect and Functions

description: Python Inspect and Functions


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

array = np.array([[0, 0, 3, 2, 0, 0],
                 [5, 2, 1, 2, 6, 7],
                 [0, 0, 2, 4, 0, 0]])
flat_non_zero = array[np.nonzero(array)]
mode(flat_non_zero)

rawDescription: How can I find the second most common number in an array?

description: Find the second most common number in an array


code:
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': tasks})

if __name__ == '__main__':
    app.run(debug=True)

rawDescription: Python web api using flask

description: Python web api using flask


code:
from graphic import *

def main():
    repeat = 5
    diameter = 40
    radius = diameter // 2
    offset = radius // 2

    win = GraphWin("Graphic Design", diameter*repeat + offset, diameter*repeat)
    win.setBackground('white')

    for i in range(repeat):
        for j in range(repeat):
            draw_symbol(win, i % 2,
                        Point(i*diameter + offset, j*diameter), radius, 'red')

    win.getMouse()
    win.close()

def draw_symbol(win, kind, lower_left, radius, colour):
    centre = Point(lower_left.x+radius, lower_left.y+radius)
    circle = Circle(centre, radius)
    circle.setOutline('')
    circle.setFill(colour)
    circle.draw(win)

    if kind == 0:
        rectangle = Rectangle(lower_left,
                             Point(lower_left.x+radius, lower_left.y+radius*2))
    else:
        rectangle = Rectangle(lower_left,
                             Point(lower_left.x+radius*2, lower_left.y+radius))
    rectangle.setOutline('white')
    rectangle.setFill('white')
    rectangle.draw(win)

    circle = Circle(centre, radius)
    circle.setWidth(1)
    circle.setOutline(colour)
    circle.setFill('')
    circle.draw(win)

main()

rawDescription: Replicating this design in Python

description: Replicating this design in Python