code:
from datetime import datetime
from dateutil.relativedelta import relativedelta

def add_time(d, rd):
    day = relativedelta(days=+1)

    out = d + rd
    if d.day > out.day:
        out = out + day

    return out

# Check that it "rolls over"
print(add_time(datetime(year=2015, month=1, day=29), relativedelta(years=+4, months=+1))) # 2019-03-01 00:00:00
print(add_time(datetime(year=2015, month=3, day=31), relativedelta(years=+0, months=+2))) # 2015-05-01 00:00:00

# Check that it handles "normal" scenarios
print(add_time(datetime(year=2015, month=6, day=19), relativedelta(months=+1))) # 2015-07-19 00:00:00
print(add_time(datetime(year=2015, month=6, day=30), relativedelta(years=+2, months=+1))) # 2017-07-30 00:00:00

# Check across years
print(add_time(datetime(year=2015, month=12, day=25), relativedelta(months=+1))) # 2016-01-25 00:00:00

# Check leap years
print(add_time(datetime(year=2016, month=1, day=29), relativedelta(years=+4, months=+1))) # 2020-02-29 00:00:00

rawDescription: Add one month to a given date (rounded day after) with Python


code:
def ExecuteScript(saveFile, updatedSaveFile, codeSnippet ):
    decryptedData, jsonData = FixSave.GetDataFromSaveFile(saveFile)
    FixSave.Save(decryptedData, jsonData, updatedSaveFile + "_original")

    dynamicFunction = ""
    dynamicFunction += "def execCodeSnippet(json_data):\n"
    for line in codeSnippet.splitlines():
        line = "    " + line.strip() + "\n"
        dynamicFunction += line
    dynamicFunction += "    return json_data\n"

    module = imp.new_module('codesnippets')
    exec(dynamicFunction, module.__dict__)

    jsonDataFixed = module.execCodeSnippet(jsonData)

    FixSave.Save(decryptedData, jsonDataFixed, updatedSaveFile)

rawDescription: Dynamically generate/create a function in Python


rawDescription: Removing elements from a list containing specific characters


code:
response = br.response()
response.read()

rawDescription: Python mechanize loses attributes on second open


code:
def input_scores():
    scores = []
    y = 1
    for num in range(5):
        score = int(input('Please enter your score for test %d: ' %y))
        while score < 0 or score > 100:
            print ('Error --- all test scores must be between 0 and 100 points')
            score = int(input('Please try again: '))
        scores.append(score)
        y += 1
    return scores

rawDescription: For loop only executes 1 time, though given a range of 5


code:
def get_width(num_characters):
    return int((1+num_characters) * 256)

rawDescription: Python XLWT adjusting column widths

description: Python XLWT adjusting column widths


code:
filename = 'greatv02_v001_jam.mb'
import re
re.findall(r'(?<=_v)\d+', filename)

filename = 'greatv02_v001_av456jam.mb'
re.findall(r'(?<=_v)\d+', filename)
filename = 'greatv02_v001_v456jam.mb'
re.findall(r'(?<=_v)\d+', filename)

rawDescription: python find digits with leading '_v'

description: Python find digits with leading '_v'


code:
#run for n months, rabbits die after m months.
n, m = input("Enter months to run, and how many months rabbits live, separated by a space ").split()
n, m = int(n), int(m)
generations = [1, 1] #Seed the sequence with the 1 pair, then in their reproductive month.
def fib(i, j):
    count = 2
    while (count < i):
        if (count < j):
            generations.append(generations[-2] + generations[-1]) #recurrence relation before rabbits start dying (simply fib seq Fn = Fn-2 + Fn-1)
        elif (count == j or count == j+1):
            print ("in base cases for newborns (1st+2nd gen. deaths)") #Base cases for subtracting rabbit deaths (1 death in first 2 death gens)
            generations.append((generations[-2] + generations[-1]) - 1)#Fn = Fn-2 + Fn-1 - 1
        else:
            generations.append((generations[-2] + generations[-1]) - (generations[-(j+1)])) #Our recurrence relation here is Fn-2 + Fn-1 - Fn-(j+1)
        count += 1
    return (generations[-1])

print (fib(n, m))
print ("Here's how the total population looks by generation: \n" + str(generations))

rawDescription: Fibonacci Rabbits Dying After Arbitrary # of Months


code:
block = 1024
with open(fileName, 'rb') as f:
    tmp = [chunk for chunk in iter(lambda: f.read(block), b'')]

rawDescription: What is the best data structure to store chunks of file in python


code:
input = "Self contained underwater breathing apparatus"
output = ""
for i in input.upper().split():
    output += i[0]

rawDescription: How do I find the first letter of each word?

description: Find the first letter of each word


code:
from dateutil import parser
parser.parse("Tue May 08 15:14:45 +0800 2012")

rawDescription: Parsing time string in Python

description: Parsing time string in Python


code:
name = "ABCDEFGH"
nameL = list(name)

for i in range(len(nameL)):
    if i%2==1:
        nameL[i] = '$'

name = ''.join(nameL)
print(name)

rawDescription: How to replace characters in a string in python

description: Replace characters in a string in python


code: dictionary["territory"], dictionary["numeric_id"], dictionary["continent"] = line.split(',')

rawDescription: Python read from file, split each line into different segments, assign to keys


code:
repr("I don't want it, there'll be others")
print("I don't want it, there'll be others")

rawDescription: removing an backslash from a string

description: Removing an backslash from a string


code:
from Tkinter import *
import tkFileDialog, os

def demana_directori():
    global items, directori
    d = tkFileDialog.askdirectory(title='Escolleix directori')
    directori.set(d)

##MAIN
finestra=Tk()
finestra.title("cc")
finestra.minsize('0','0')

f=Frame(finestra)
f.pack()

esq=Frame(finestra)
drt=Frame(finestra)

esqtp=Frame(esq)
esq.pack(side=LEFT,fill=BOTH)
esqtp.pack(side=TOP,fill=X)

esqtp1=Frame(esqtp)
esqtp2=Frame(esqtp)

esqtp2.pack()
esqtp1.pack()

directori=StringVar()
items=['']

dr=Button(esqtp1,text='Escollir directori treball',command=demana_directori)
dr.pack(side=LEFT)
imdr=Label(esqtp1,width=30,relief=SUNKEN,textvariable=directori)
imdr.pack(side=LEFT,fill=X)
finestra.mainloop()

rawDescription: Label text not updating after tkFileDialog.askdirectory() || Python


code: df.sort_index(ascending=False).groupby('A').agg([np.mean, lambda x: x.iloc[1] ])

rawDescription: Python Pandas: Is Order Preserved When Using groupby() and agg()?


code:
l = [10, 20, 30, 40, 50]
inp = "a b a d e"

import re

repl = iter(l)
result = re.sub(r'\w+', lambda m: str(next(repl)), inp)

rawDescription: Ordered substitution with regex in Python


code: plt.clim(0, 3)

rawDescription: Getting the correct colours for pcolormesh


code:
from functools import partial

...

QtCore.QObject.connect(..., partial(self.SelectLogFileToJoin, 1))

rawDescription: Connect two buttons to same callback function two arguments


code:
g = (None, 'b', None, None)
next(x for x in g if x is not None)
g = (None, None, None)
next((x for x in g if x is not None), "default")  # try this with filter :)
g = (None, None, None)  # so you know what happens, and what you could catch
next(x for x in g if x is not None)

rawDescription: How to extract the first non-Null match from a group of regexp matches in Python?

description: Extract the first non-Null match from a group of regexp matches in Python


code:
class SettingsTest(TestCase):
    def test_account_is_configured(self):
        assert 'accounts' in INSTALLED_APPS
        assert 'accounts.User' == AUTH_USER_MODEL

class UserTest(TestCase):
    def setUp(self):
        self.username = "testuser"
        self.email = "testuser@testbase.com"
        self.first_name = "Test"
        self.last_name = "User"
        self.password = "z"

        self.test_user = User.objects.create_user(
            username=self.username,
            email=self.email,
            first_name=self.first_name,
            last_name=self.last_name
        )

    def test_create_user(self):
        assert isinstance(self.test_user, User)

    def test_default_user_is_active(self):
        assert self.test_user.is_active

    def test_default_user_is_staff(self):
        assert not self.test_user.is_staff

    def test_default_user_is_superuser(self):
        assert not self.test_user.is_superuser

    def test_get_full_name(self):
        assert self.test_user.get_full_name() == 'Test User'

    def test_get_short_name(self):
        assert self.test_user.get_short_name() == self.email

    def test_unicode(self):
        assert self.test_user.__unicode__() == self.username

rawDescription: How to test a Django model with pytest?

description: Test a Django model with pytest


code:
def _deleteSelectedRows(self):
    select = self.mainForm.tblItems.selectionModel()

    if select.hasSelection():
        selectedRows = select.selectedRows()

        for r in selectedRows:
            rowFlag = self.items_Model.itemsModel.headerData(r.row(), QtCore.Qt.Vertical)
            if rowFlag == "!":
                self.items_Model.itemsModel.revertRow(r.row())
            else:
                self.items_Model._deleteRowByIndex(r.row())

rawDescription: undelete row from QTableView

description: Undelete row from QTableView


code:
df_address['country_lower'] = df_address['Country'].str.lower()
df_CountryMapping['name_lower'] = df_CountryMapping['NAME'].str.lower()
df_merged = df_address.merge(df_CountryMapping, left_on="country_lower", right_on="name_lower", how="left")

rawDescription: Case insensitive pandas dataframe.merge

description: Case insensitive pandas dataframe.merge


code:
#input is defined somewhere prior to the loop
output = []
for char in input:
    if not unicodedata.category(char).startswith('P'):
        output.append(char)
''.join(output)

rawDescription: Python for loop control variable accessed before declaration


code:
config.registry['wsdl_client'] = Client(wsdl_url)

def some_view(request):
    client = request.registry['wsdl_client']

rawDescription: Python Pyramid & suds - what is the correct way to design my Pyramid web app to connect to a SOAP service?


code:
oninterval = False
dd = {}
keys = d.keys()
keys.sort()
start_key, first_val = keys[0], d[keys[0]]

for k in keys:
    v = float(d[k])
    if oninterval:
        cur_list.append(v)
        if not int(v) <= 70: # interval ends
            oninterval = False
            dd[(start_key,k)] = cur_list
    else:
        if int(v) <= 70:
            cur_list = [first_val, v]
            oninterval = True
        else:
            start_key, first_val = k, v

if oninterval: dd[(start_key, keys[-1])] = cur_list

rawDescription: Identify intervals with certain values

description: Identify intervals with certain values


code:
def check_for_admin(*args, **kw):
    if request.path.startswith('/admin/'):
        if not user.is_admin():
            return redirect(url_for('login_form'))

rawDescription: Restrict Pages/URLs to Admin only in Flask


code: return a != b

rawDescription: Integer to Boolean

description: Integer to Boolean


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

theta = np.linspace(0, 9*np.pi, 100)
r = theta
x = r * np.cos(theta)
y = r * np.sin(theta)
plt.plot(x, y, color='red', linewidth=5, dashes=[5, 3])
plt.show()

rawDescription: Changing matplotlib's dashed line characteristics other than just line width


code:
def add_win(people_list, name):
    person = find_person(people_list, name)
    person['wins'] += 1

def find_person(people_list, name):
    for person in people_list:
        if person['name'] == name:
            return person
    person = {'name': name, 'wins': 0}
    people_list.append(person)
    return person

rawDescription: Python find object in a list

description: Python find object in a list


code:
data = myAPI.readArr(arg1, arg2)
if data is None:
   raise Exception("Problem!")

rawDescription: Check if return value is instance of Py_None


rawDescription: How to select with ease several circular areas in a square array?

description: Select with ease several circular areas in a square array


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

def flip(items, ncol):
    return itertools.chain(*[items[i::ncol] for i in range(ncol)])

x = np.arange(-2*np.pi, 2*np.pi, 0.1)
ax = plt.subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')

handles, labels = ax.get_legend_handles_labels()
plt.legend(flip(handles, 2), flip(labels, 2), loc=9, ncol=2)

plt.grid('on')
plt.show()

rawDescription: Matplotlib legend, add items across columns instead of down


code:
while True:
  data = f.read(BUFSIZE)
  if not data:
    p.Parse('', True)
    break
  p.Parse(data, False)
  time.sleep(0.0)

rawDescription: How can I process xml asynchronously in python?

description: Process xml asynchronously in python


code:
import statsmodels.api as sm
logmodel=sm.GLM(trainingdata[['Successes', 'Failures']], trainingdata[['const', 'A', 'B', 'C', 'D']], family=sm.families.Binomial(sm.families.links.logit)).fit()

rawDescription: Is there a way to implement sample weights in python logistic regression?


code:
specified_value = 7

answer = np.where(np.logical_and(
                      np.logical_and.reduce(
                          [data == f(data,
                                     footprint=np.ones((3,3)),
                                     mode='constant',
                                     cval=np.inf) for f in
                                         (filters.maximum_filter,
                                          filters.minimum_filter)]),
                      data == specified_value))

rawDescription: Retrieve position of specified element sourrounded by same element


code:
def distance(x1,x2,y1,y2):
    xx = x1 - x2
    yy = y1 - y2
    xxx = xx ** 2
    yyy = yy ** 2
    xy = xxx + yyy
    return sqrt(xy)

x1 = int(input("x1?: "))
x2 = int(input("x2?: "))
y1 = int(input("y1?: "))
y2 = int(input("y2?: "))

print( distance( x1, x2, y1, y2 ) )

rawDescription: my 2 point distance code returns syntax error in python 3

description: My 2 point distance code returns syntax error in python 3


code:
from twilio.rest import TwilioRestClient
account_sid = "ACXXXXXXXXXXXXXXXXX"
auth_token = "YYYYYYYYYYYYYYYYYY"
client = TwilioRestClient(account_sid, auth_token)

child_calls = client.calls.list(parent_call_sid=PARENT_CALL_SID)

rawDescription: Twilio : Getting child call sid in android client


code:
while True:
     newsock, fromaddr = s.accept()
     ssl_sock = context.wrap_socket(newsock, server_side=True)
     threading.Thread(target=tls_listener, args=(ssl_sock,)).start()

def tls_listener(ssl_sock):
    t = TlsListener()  # new instance of TlsListener class

rawDescription: Initializing a class using threading (Python)


code:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import OpenOPC

client = OpenOPC.client()
client.connect('CODESYS.OPC.DA')
tags = client.list("PLC2.Application.GVL.*")
while True:
    res = client.read(tags, group='MyGroup')
client.close()

rawDescription: Why my app leaks memory ? How to avoid memory leakage?


rawDescription: Is it possible to accelerate python nested loop?


code:
for result in getLexicographicPermutationsOf(rest, state):
    yield result

rawDescription: Python Lists and Yielding

description: Python Lists and Yielding


rawDescription: The *args and **kwds in python super call


rawDescription: Logging problems when using modules individually


code:
np.einsum('ik,jk->kij', puy, puy2)
np.allclose(np.einsum('ik,jk->kij', puy, puy2), zz)

rawDescription: Numpy Dot Product of two 2-d arrays in numpy to get 3-d array


code:
import turtle
def draw_square(t, size):
   for i in range(4):
       t.forward(size)
       t.left(90)
wn = turtle.Screen()
dan = turtle.Turtle()
sizevar = 1
for i in range(10):
   draw_square(dan, sizevar)
   sizevar += 20
   dan.penup()
   dan.backward(10)
   dan.right(90)
   dan.forward(10)
   dan.left(90)
   dan.pendown()

rawDescription: Concentric Squares in Python with Turtle


code:
import numpy as np
result_array = np.vstack(tuple(list_of_arrays))

rawDescription: Stack list elements to make an array?

description: Stack list elements to make an array


code:
import xml.etree.cElementTree as ET

ET.iterparse(sourcefile) # sourcefile being a cStringIO.StringIO instance holding your worksheet XML document

element.clear() # leave only scorched earth behind you

rawDescription: How to wrap a proper generator function around a SAX Parser

description: Wrap a proper generator function around a SAX Parser


code:
import re
sentence = "You are my favorite. Are you my friend? Are you an elephant?"
items = []
for item in re.finditer("[Aa]re", sentence, ):
    items.append(item.start())

rawDescription: python choose one object from array

description: Python choose one object from array


code:
import sys

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class FeedbackWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.main_layout = QVBoxLayout(self)
        #self.main_widget = QWidget(self)              # main_widget is not used.
        #self.main_widget.setLayout(self.main_layout)
        self.setLayout(self.main_layout)
        self.title_label = QLabel("Tell us what you think:")
        self.feedback_text_editor = QTextEdit()
        self.send_button = QPushButton("Send")

        self.main_layout.addWidget(self.title_label)
        self.main_layout.addWidget(self.feedback_text_editor)
        self.main_layout.addWidget(self.send_button)

        self.setWindowTitle("Feedback")
        self.setGeometry(200,120,300,300)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = FeedbackWindow()
    w.show()
    app.exec_()

rawDescription: widgets are not expandig according to window size

description: Widgets are not expandig according to window size


rawDescription: Converting Ints into binary / hex with ^ operator


code:
import os
os.getenv("PATH")

rawDescription: Send bash environment variable back to python fabric


code: pyplot.plot(x, y, color='#112233')

rawDescription: How to avoid line color repetition in matplotlib.pyplot?

description: Avoid line color repetition in matplotlib.pyplot


rawDescription: Working with string and json in python (json.loads json.dumps)


code:
import collections

def total(records):
    dct = collections.defaultdict(int)
    for cust_id, contrib in records:
        dct[cust_id] += contrib

    return dct.items()

rawDescription: Sum second value in tuple for each given first value in tuples using Python


code: 'A1' in ws.merged_cells

rawDescription: Locating merged cell ranges in pyopenxl

description: Locating merged cell ranges in pyopenxl


code:
for table in tree.xpath(".//table"):
    print("---  new table: ---")
    for td in table.xpath(".//td"):
        print(td)

rawDescription: Python2 Scrape html with xpath

description: Python2 Scrape html with xpath


code:
# settings.py file
SECRET_KEY = 'fake stuff'

try:
    from settings_local import *
except ImportError:
    pass

rawDescription: Using un-managed file in Jenkins build step


code:
x = numpy.arange(5)
x
y = x.copy()
x[:] = 0
x
y

rawDescription: values of an array set to 0

description: Values of an array set to 0


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

X = 100*np.random.rand(6,6)

fig, ax = plt.subplots()
i = ax.imshow(X, cmap=cm.jet, interpolation='nearest')
fig.colorbar(i)

plt.show()

rawDescription: Is it possible to plot a "checkerboard" type plot in python?


code:
import seaborn as sns
import matplotlib.pyplot as plt
from numpy import arange
# here set the scale by 3
sns.set(font_scale=3)
x = arange(25).reshape(5, 5)
cmap = sns.diverging_palette(220, 20, sep=20, as_cmap=True)
ax = sns.heatmap(x, cmap=cmap)
plt.show()

rawDescription: Seaborn, change font size of the colorbar


code:
from stem import Signal
from stem.control import Controller

with Controller.from_port(port = 9051) as controller:
    controller.authenticate(password='your password set for tor controller port in torrc')
    print("Success!")
    controller.signal(Signal.NEWNYM)
    print("New Tor connection processed")

rawDescription: Make requests using Python over Tor

description: Make requests using Python over Tor


code:
# Normalize the rows of ve.
row_sums = np.array(ve.sum(axis=1))[:,0]
row_indices, col_indices = ve.nonzero()
ve.data /= row_sums[row_indices]

rawDescription: SciPy/NumPy: Normalize a csr_matrix

description: SciPy/NumPy: Normalize a csr_matrix


code:
import numpy as np
import pandas as pd

df = pd.read_csv('test.csv', parse_dates=[1])  # read time as date
print(df)
df['time'] -= pd.datetime.now().date()  # convert to timedelta
print(df)
df['time'] /= np.timedelta64(1,'s')  # convert to seconds
print(df)

rawDescription: Python 2.7 CSV graph time format

description: Python 2.7 CSV graph time format


code:
from lxml import etree
text = '''<s id="1792387-2">Castro Verde is situated in the Baixo Alentejo Subregion within a territory known locally as the Campo Branco (English: White Plains).</s>'''
def edit(s):
    return 'Changed Text'

t = etree.fromstring(text)
t.text = edit(t.text)
etree.tostring(t)

rawDescription: parsing xml in python

description: Parsing xml in python


rawDescription: Apply logarithm only on positive entries of array


code:
a = function_x()
b = function_y()
"a={a}, b={b}, a+b={c}".format(a=a, b=b, c=a+b)

rawDescription: How to use the values assigned to variables during string formatting?

description: Use the values assigned to variables during string formatting


code:
import re

word = "aliows"
folder = '/Users/jordanfreedman/Thinkful/Projects/Spam_Filter/enron1/spam/'
email = '4201.2005-04-05.GP.spam.txt'

file = folder + email
fh = open(file, 'r')

contents = re.findall(word, fh.read())

print(len(contents))

rawDescription: Why is grep not finding string when definitely in file?


code:
import numpy as np
arr1 = np.array(['a', 'b', 'c'])
index = np.array([2, 1, 0])
arr1[index]

rawDescription: Specify Order numpy array

description: Specify Order numpy array


code: next(x[0] for x in enumerate(L) if x[1] > 0.7)

rawDescription: First Python list index greater than x?

description: First Python list index greater than x


code:
# Returns a string minus all levels of empty formatting tags
def remove_empty_html_tags(input_string):
    matcher = r'<(?P<tag>strong|span|em)\b[^>]*>(\s*)</(?P=tag)>'
    old_string = input_string
    new_string = re.sub(matcher, r'\1', old_string)
    while new_string != old_string:
        old_string = new_string
        new_string = re.sub(matcher, r'\1', new_string)
    return new_string

rawDescription: Python grouped backreferences

description: Python grouped backreferences


code:
from matplotlib import pyplot as plt

class LineBuilder:
    def __init__(self, line):
        self.line = line
        self.xs = list(line.get_xdata())
        self.ys = list(line.get_ydata())
        self.cid = line.figure.canvas.mpl_connect('button_press_event', self)

    def __call__(self, event):
        print('click', vars(event))
        if event.button==3:
            print('clean up')
            event.canvas.mpl_disconnect(self.cid)
            return
        if event.inaxes != self.line.axes:
            return
        self.xs.append(event.xdata)
        self.ys.append(event.ydata)
        self.line.set_data(self.xs, self.ys)
        self.line.figure.canvas.draw_idle()

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click to build line segments')
line, = ax.plot([0], [0])  # empty line
linebuilder = LineBuilder(line)

plt.show()

rawDescription: How to regain control using mpl_disconnect() to end custom event_handling in matplotlib

description: Regain control using mpl_disconnect() to end custom event_handling in matplotlib


code:
class Car(models.Model):
    brand = models.CharField(max_length=20)

    def __unicode__(self):
        return u'%s' % (self.brand)

rawDescription: Django populate choice from ForeignKey

description: Django populate choice from ForeignKey


code:
NUL = '\x00'
def lines_without_nulls(path):
    with open(path, 'Urb') as f:
        for line in f:
            yield line.replace(NUL, '').replace('\n', '\r')

rawDescription: Specifying chars in python

description: Specifying chars in python


code:
reservations = conn.get_all_instances()
instance = reservations[0].instances[0]
dir(instance)

rawDescription: trying to get info on boto docs

description: Trying to get info on boto docs


code:
from twisted.internet.protocol import ConsumerToProtocolAdapter
from twisted.internet.interfaces import IPushProducer
from twisted.protocols.ftp import IReadFile

class FinishNotifier(ConsumerToProtocolAdapter):
    def connectionLost(self, reason):
        reason.trap(ConnectionDone)
        self.finished.callback(None)

@implementer(IReadFile, IPushProducer)
class HTTP2FTP(object):
    def send(self, consumer):
        protocol = FinishNotifier(consumer)
        response.deliverBody(protocol)
        # Lazy hack.
        # This code probably belongs in protocol.connectionMade instead.
        self._producer = protocol.transport
        consumer.registerProducer(self._producer, streaming=True)
        protocol.finished.addCallback(
            lambda ignored: consumer.unregisterProducer()
        )
        return protocol.finished

    def pauseProducing(self):
        self._producer.pauseProducing()

    def resumeProducing(self):
        self._producer.resumeProducing()

    def stopProducing(self):
        self._producer.stopProducing()

rawDescription: Streaming HTTP body over FTP with twisted


code: """Get the next random number in the range [0.0, 1.0)."""

rawDescription: Could random.randint(1,10) ever return 11?


code:
if line.lower().startswith(startswith):
    if completeline:
        lines_1.append(completeline)
    completeline = line

rawDescription: Python: Appending string constructed out of multiple lines to list


code:
f = open('hr.dat', 'rb')
array = (c_int * 32487834)()
f.readinto(array)

rawDescription: ctypes initializing c_int array by reading file

description: Ctypes initializing c_int array by reading file


code:
sqlalchemy.sql.expression.insert(table, values=None, inline=False,
  bind=None, prefixes=None, returning=None, return_defaults=False, **dialect_kw)

rawDescription: How to turn off SQLAlchemy implicit_returning?

description: Turn off SQLAlchemy implicit_returning


code:
SOCIALACCOUNT_PROVIDERS = {
    "github": {
        "AUTH_PARAMS": {"scope": "repo"}
    },
}

rawDescription: Adding permissions to django-allauth's OAuth token


code:
import Tkinter as tk
import random

class App():
    def __init__(self):
        self.root = tk.Tk()
        self.label = tk.Label(self.root, text='Bla')
        self.label.pack()
        self.button = tk.Button(self.root, text='Button', command=self.sleep)
        self.button.pack()

        self.root.bind('<Up>', self.func)

        self.root.mainloop()

    def func(self, event):
        self.label.config(text='Up '+str(random.random()))

    def sleep(self):
        self.root.unbind('<Up>')
        self.label.config(text='sleeping')
        self.root.after(2000, self.done_sleeping)

    def done_sleeping(self):
        self.label.config(text='done sleeping')
        self.root.bind('<Up>', self.func)

App()

rawDescription: tkinter unbind function do not work as I want

description: Tkinter unbind function do not work as I want


code:
with open(r'c:\configfile.txt', 'w', encoding='utf-8-sig') as cf:
    ...

rawDescription: Write UTF-8 textfile with Python that Windows Editor can read


code:
permutation_indices = set()
while len(permutation_indices) < k:
    permutation_indices.add(random.randrange(total_permutations))

rawDescription: Sample k random permutations without replacement in O(N)


code:
file = open('input.txt', 'r')

#coordinates
c = {}

for line in file:
    #items
    (x, y, z) = (float(n) for n in line.split())

    if (x, y) not in c:
        c[(x, y)] = [z, 1]
    elif c[(x, y)][0] > z:
        c[(x, y)][0], c[(x, y)][1] = z, 1
    elif c[(x, y)][0] == z:
        c[(x, y)][1] += 1

for key in c:
    print("{} {} {} {}".format(key[0], key[1], c[key][0], c[key][1]))

rawDescription: Suggestions for faster for/if statements in my code?


code:
def rollList(n):
    a = n[0].getSize()
    faceList = [0] * a

    for d in n:
        d.roll()
        x = d.getFaceValue()
        faceList[x-1] += 1

rawDescription: Increment the value inside a list element


code:
import struct
two_octets = '\x56\x20'
values = struct.unpack('<H', two_octets)[0]
a = values & 0xFFF  # Select right-most 12 bits
b = values >> 12    # Select left-most 4 bits

rawDescription: decoding inter-octet binary data

description: Decoding inter-octet binary data


code:
class Article(models.Model):

    name = models.Charfield()

    def __unicode__(self):
        return self.name

rawDescription: Django admin listing not showing data correctly


rawDescription: Why does fftfreq produce negative values?


rawDescription: How can I set dataless areas of a hist2d plot to the zero-value color?

description: Set dataless areas of a hist2d plot to the zero-value color


code: db.execute("SELECT id2 from my_table where id = '%s';" % user)

rawDescription: Select data from MySQL database and make it a value using Python


code:
import csv
import requests

inputfile = open('trycode.csv','r')
for row in inputfile:
    url = 'http://en.wikipedia.org/wiki/Monty_Python/' + row
    source = requests.get(url)
inputfile .close()

rawDescription: Python requests url link which contains a variable part


code:
def localize_libpaths(libpath, local_libs, enc_path=None):
    """ Set rpaths and install names to load local dynamic libs at run time

    Use ``install_name_tool`` to set relative install names in `libpath` (as
    named in `local_libs` to be relative to `enc_path`.  The default for
    `enc_path` is the directory containing `libpath`.

    Parameters
    ----------
    libpath : str
        path to library for which to set install names and rpaths
    local_libs : sequence of str
        library (install) names that should be considered relative paths
    enc_path : str, optional
        path that does or will contain the `libpath` library, and to which the
        `local_libs` are relative.  Defaults to current directory containing
        `libpath`.
    """
    if enc_path is None:
        enc_path = abspath(dirname(libpath))
    install_names = osx_get_install_names(libpath)
    need_rpath = False
    for install_name in install_names:
        if install_name[0] in '/@':
            continue
        if hasattr(sys, 'real_prefix'):
            # virtualenv detected - use @executable_path
            back_tick('install_name_tool -change %s @executable_path/../lib/python2.7/site-packages/PySide/%s %s' %
               (install_name, install_name, libpath))
        else:
            # not a virtualenv - use @rpath
            back_tick('install_name_tool -change %s @rpath/%s %s' %
               (install_name, install_name, libpath))
            need_rpath = True
    if need_rpath and enc_path not in osx_get_rpaths(libpath):
        back_tick('install_name_tool -add_rpath %s %s' %
           (enc_path, libpath))

rawDescription: How to properly install PySide into relocatable virtualenv?

description: Properly install PySide into relocatable virtualenv


code:
class getDict(dict):
   def __getitem__(self,key):
       if key in self:
          return dict.__getitem__(self,key)
       else:
          return None

rawDescription: __getitem__ or square brackets for recursive data structure


code:
a = ([1]) # equivalent to [1], not a tuple
b = ([2]) # equivalent to [2], not a tuple
list(zip(a,b))
a = ([1],[2])
b = ([3],[4])
list(zip(a,b))

rawDescription: set and zip questions with Python

description: Set and zip questions with Python


code: {{ forloop.counter|add:rank }}

rawDescription: Django Template - Increasing the value of a variable in a template in a for loop


code: res = sum(x for x in range(100, 2001) if x % 3 == 0)

rawDescription: Sum up all the integers in range()

description: Sum up all the integers in range()


code:
import os
os.environ['PDBVIEWER'] = 'C:/Program Files (x86)/University of Illinois/VMD/vmd.exe'

from MMTK import *
molecule = Molecule('water')
molecule.view()

rawDescription: Python MMTK "There is no program associated with ..pdb files, please install a suitable viewer"


code:
from django.db import models
from django.contrib.contenttypes.models import ContentType

class BaseModel(models.Model):
    type = models.ForeignKey(ContentType,editable=False)
    # other base fields here

    def save(self,force_insert=False,force_update=False):
        if self.type_id is None:
            self.type = ContentType.objects.get_for_model(self.__class__)
        super(BaseModel,self).save(force_insert,force_update)

    def get_instance(self):
        return self.type.get_object_for_this_type(id=self.id)

rawDescription: Making a multi-table inheritance design generic in Django


rawDescription: Best way to get query string from a URL in python?

description: Get query string from a URL in python


code:
connect: {
    options: {
        port: 5000,
        hostname: 'localhost'
    },
    proxies: [
        {
            context: '/api',
            host: '127.0.0.1',
            port: 5001,
            https: false,
            changeOrigin: false,
            xforward: false
        }
    ]
}

rawDescription: Serve a Flask app on a sub-url during localhost development


code:
arguments["x-ha-policy"] = "nodes"
arguments["x-ha-policy-params"] = 'rabbit@node1'

rawDescription: Pika and RabbitMQ - create a queue on a specific node


code:
levels = np.logspace(0,np.log10(Z.max()), 100 )[30:80]
levels_black = [level for i,level in enumerate(levels) if (i+5) % 10 != 0]
levels_red =  [level for i,level in enumerate(levels) if (i+5) % 10 == 0]

CS2_black = pyplot.contour(X,Y,Z,locator=ticker.LogLocator(), colors='k', levels=levels_black, lw=2,norm=colors.LogNorm(),vmin=1,vmax =Z.max())
CS2_red = pyplot.contour(X,Y,Z,locator=ticker.LogLocator(), colors='r', levels=levels_red, lw=2,norm=colors.LogNorm(),vmin=1,vmax =Z.max())

cbar.add_lines(CS2_red)

rawDescription: Add certain lines from contourplot in colorbar


code: formatter = logging.Formatter('[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s','%m-%d %H:%M:%S')

rawDescription: Extend standard python logging, to include the line number where a log method was invoked


code:
def material_path(instance, filename):
    return 'documents/%d' % instance.id_presentations.id

class Materials(models.Model):
    id_presentations = models.ForeignKey(Presentations)
    document = models.FileField(upload_to=material_path)
    docname = models.CharField(max_length=40)

rawDescription: converting django ForeignKey to a usable directory name

description: Converting django ForeignKey to a usable directory name


code:
token = "999999999:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
url="https://api.telegram.org/bot" +token + "/getme"

req = Request(url)
response = urlopen(req)
data = response.read().decode('utf-8')
json_data = json.loads(data)

print(str(data['ok'])) #should print True

rawDescription: Telegram bot updates to python dict conversion


code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class orange(QWidget):
    def __init__(self, parent=None):
        super(orange, self).__init__(parent)

        self.setMinimumSize(256, 256)
        self.setMaximumSize(256, 256)

        self.frame = QFrame(self)
        self.frame.setMinimumSize(128, 128)
        self.frame.setMaximumSize(128, 128)
        self.frame.setGeometry(QRect(0, 128, self.width(), self.height()))
        self.frame.setStyleSheet("background: orange")

if __name__ == "__main__":
    import  sys

    app = QApplication(sys.argv)
    main = orange()
    main.show()
    sys.exit(app.exec_())

rawDescription: setGeometry() right after addWidget() issue

description: SetGeometry() right after addWidget() issue


code:
from datetime import datetime
tuple((str(n), str(n)) for n in range(1995, datetime.now().year + 1))
import calendar
tuple((m, m) for m in calendar.month_abbr[1:])

rawDescription: Smart Loop List Creation in Python for Django Choice fields


code: [[0]*8 for x in xrange(8)]

rawDescription: Python - multi-line array

description: Python - multi-line array


code:
class UnsplitableUnicode(unicode):
    "An object that behaves like a unicode string but cannot be split()"
    def split(self, *args, **kwargs):
        return [self]

class MultiWordSearchChangeList(ChangeList):
    "Changelist that allows searches to contain spaces"
    def get_query_set(self, request):
        self.query = UnsplitableUnicode(self.query)
        return super(MultiWordSearchChangeList, self).get_query_set(request)

class FooAdmin(admin.ModelAdmin):
    def get_changelist(self, request, **kwargs):
        return MultiWordSearchChangeList

rawDescription: django admin search with multiple words

description: Django admin search with multiple words


code: diff = sframe_obj[t2_colname].astype(int) - sframe_obj[t1_colname].astype(int)

rawDescription: Datetime in python - speed of calculations - big data


code:
import os
import signal
terminate = False

for filename in os.listdir("<your dir>"):
    if terminate:
       break
    process_next_file(filename)

def handler(signum, frame):
    global terminate
    print("Termination requested")
    terminate = True

signal.signal(signal.SIGTERM, handler)

rawDescription: How to stop the python script

description: Stop the python script


code:
def add_instance(request):
   if request.POST:
      form=InstanceForm(request.POST, request.FILES)
      if form.is_valid():
         new_instance=form.save()
   else:
      form=InstanceForm()

   locals().update(csrf(request))
   return render_to_response(...)

rawDescription: How to save path to image when I create object using forms

description: Save path to image when I create object using forms


code:
s_pat_row = r'''
    "([^"]+)"          # match column; this is group 1
    \s*\t\s*           # match separating tab and any optional white space
    ([^\t]+)           # match a string of non-tab chars; this is group 2
    \s*\t\s*           # match separating tab and any optional white space
    "((?:\\"|[^"])*)"  # match string data that can include escaped quotes
'''

rawDescription: Delete whitespace characters in quoted columns in tab-separated file?


code: any(isinstance(el, list) for el in input_list)

rawDescription: determine if a list contains other lists

description: Determine if a list contains other lists


code:
import urllib2
from bs4 import BeautifulSoup
from time import sleep

def getData():
    htmlfile = open('C:/html.html', 'rb')
    html = htmlfile.read()
    soup = BeautifulSoup(html)
    items = soup.find_all('div', class_="blocks")
    for item in items:
        links = item.find_all('a')
        for link in links:
            if link.parent.name == 'h3':
                print(link.text)

getData()

rawDescription: Using beautifulsoup in python to get link names and "selecting" links instead of limiting?


rawDescription: Django change url from http:\/\/ to http://


code:
from bokeh.plotting import figure, output_file, show
from bokeh.palettes import Blues9

output_file('palette.html')

p = figure()
p.scatter(x=[0,1,2,3,4,5,6,7,8], y=[0,1,2,3,4,5,6,7,8], radius=1, fill_color=Blues9)

show(p)

rawDescription: Coloring lines in a Bokeh Plot

description: Coloring lines in a Bokeh Plot


code:
import csv

with open('somefile.csv') as f:
   reader = csv.DictReader(f)
   rows = list(reader)

rawDescription: Type casting several dictionaries generated from a loop into a single list


code:
for item in by_school.get_xticklabels():
    item.set_rotation(45)

rawDescription: Rotate tick labels for seaborn barplot

description: Rotate tick labels for seaborn barplot


code:
custQuery = db.Query(Customer)
birthdate = datetime.strptime(q,"%Y-%m-%d").date()
custQuery.filter('birthdate = ',birthdate)

rawDescription: Filter by exact date after receiving webapp2 request on Python GAE


code:
tables = soup.findAll("table")
depth3 = []
for t in tables:
  if len(t.find_parents("table")) == 3:
    depth3.append(t)

rawDescription: BeautifulSoup ignore nested tables inside table


code:
import numpy as np
from matplotlib import pyplot as plt
from scipy import randn, convolve

#data
t = np.arange(0.0, 20.0, 0.001)
r = np.exp(-t[:1000]/0.05)
x = randn(len(t))
s = convolve(x,r)[:len(x)]*0.001
theta = 2 * np.pi * t
#
fig = plt.figure(figsize=(7, 6))
#main
plt.plot(t, s)
plt.axis([0, 1, np.amin(s), 2.5*np.amax(s)])
plt.xlabel('xlabel')
plt.ylabel('ylabel')
#polar
ax = fig.add_axes([0.2, 0.47, 0.30, 0.40], polar=True, axisbg='yellow')
ax.plot(theta, t, color='blue', lw=3)
ax.set_rmax(1.0)
plt.grid(True)

plt.show()

rawDescription: Matplotlib inset polar plot

description: Matplotlib inset polar plot


code:
import numpy as np
myarray = np.asarray(mylist)

rawDescription: List to array conversion

description: List to array conversion


code:
from collections import OrderedDict
data = OrderedDict()
for item in container:
  data[item] = OrderedDict()
  ...
  for key, val in item_container.iteritems():
    ...
    data[item][key] = val

rawDescription: python: sorting

description: Python: sorting


code:
class Parent(Base):
    __tablename__ = 'parents'
    # ...

    @hybrid_property
    def child_count(self):
        #return len(self.children)   # @note: use when non-dynamic relationship
        return self.children.count()# @note: use when dynamic relationship

    @child_count.expression
    def child_count(cls):
        return (select([func.count(Child.child_id)]).
                where(Child.parent_id == cls.parent_id).
                label("child_count")
                )

    @hybrid_method
    def child_count_ex(self, stime, etime):
        return len([_child for _child in self.children
            if stime <= _child.time <= etime ])

    @child_count_ex.expression
    def child_count_ex(cls, stime, etime):
        return (select([func.count(Child.child_id)]).
                where(Child.parent_id == cls.parent_id).
                where(Child.time >= stime).
                where(Child.time <= etime).
                label("child_count")
                )

# usage of expressions:
stime, etime = datetime.datetime(2012, 1, 1), datetime.datetime(2012, 1, 31)
qry = session.query(Parent)
#qry = qry.filter(Parent.child_count > 2)
qry = qry.filter(Parent.child_count_ex(stime, etime) > 0)

rawDescription: SQLAlchemy - Writing a hybrid method for child count


code:
from IPython.display import Markdown, display
def printmd(string):
    display(Markdown(string))
printmd('**bold**')

rawDescription: Format output of code cell with Markdown


rawDescription: identify zeros in list of list python itertools

description: Identify zeros in list of list python itertools


code:
class MyGrid(wx.grid.Grid):
    """ A Copy&Paste enabled grid class"""
    def __init__(self, parent, id, style):
        wx.grid.Grid.__init__(self, parent, id, wx.DefaultPosition, wx.DefaultSize, style)
        # wx.EVT_KEY_DOWN(self, self.OnKey)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKey)
        self.data4undo = [0, 0, '']

    def OnKey(self, event):
        # If Ctrl+C is pressed...
        if event.ControlDown() and event.GetKeyCode() == 67:
            self.copy()
        # If Ctrl+V is pressed...
        if event.ControlDown() and event.GetKeyCode() == 86:
            self.paste('clip')
        # If Ctrl+Z is pressed...
        if event.ControlDown() and event.GetKeyCode() == 90:
            if self.data4undo[2] != '':
                self.paste('undo')
        # If del is pressed...
        if event.GetKeyCode() == 127:
            # Call delete method
            self.delete()
        # Skip other Key events
        if event.GetKeyCode():
            event.Skip()
            return

    def copy(self):
        # Number of rows and cols
        topleft = self.GetSelectionBlockTopLeft()
        if list(topleft) == []:
            topleft = []
        else:
            topleft = list(topleft[0])
        bottomright = self.GetSelectionBlockBottomRight()
        if list(bottomright) == []:
            bottomright = []
        else:
            bottomright = list(bottomright[0])
        if list(self.GetSelectionBlockTopLeft()) == []:
            rows = 1
            cols = 1
            iscell = True
        else:
            rows = bottomright[0] - topleft[0] + 1
            cols = bottomright[1] - topleft[1] + 1
            iscell = False
        # data variable contain text that must be set in the clipboard
        data = ''
        # For each cell in selected range append the cell value in the data variable
        # Tabs '    ' for cols and '\r' for rows
        for r in range(rows):
            for c in range(cols):
                if iscell:
                    data += str(self.GetCellValue(self.GetGridCursorRow() + r, self.GetGridCursorCol() + c))
                else:
                    data += str(self.GetCellValue(topleft[0] + r, topleft[1] + c))
                if c < cols - 1:
                    data += '    '
            data += '\n'
        # Create text data object
        clipboard = wx.TextDataObject()
        # Set data object value
        clipboard.SetText(data)
        # Put the data in the clipboard
        if wx.TheClipboard.Open():
            wx.TheClipboard.SetData(clipboard)
            wx.TheClipboard.Close()
        else:
            wx.MessageBox("Can't open the clipboard", "Error")

    def paste(self, stage):
        topleft = list(self.GetSelectionBlockTopLeft())
        if stage == 'clip':
            clipboard = wx.TextDataObject()
            if wx.TheClipboard.Open():
                wx.TheClipboard.GetData(clipboard)
                wx.TheClipboard.Close()
            else:
                wx.MessageBox("Can't open the clipboard", "Error")
            data = clipboard.GetText()
            if topleft == []:
                rowstart = self.GetGridCursorRow()
                colstart = self.GetGridCursorCol()
            else:
                rowstart = topleft[0][0]
                colstart = topleft[0][1]
        elif stage == 'undo':
            data = self.data4undo[2]
            rowstart = self.data4undo[0]
            colstart = self.data4undo[1]
        else:
            wx.MessageBox("Paste method "+stage+" does not exist", "Error")
        text4undo = ''
        # Convert text in a array of lines
        for y, r in enumerate(data.splitlines()):
            # Convert c in a array of text separated by tab
            for x, c in enumerate(r.split('    ')):
                if y + rowstart < self.NumberRows and x + colstart < self.NumberCols :
                    text4undo += str(self.GetCellValue(rowstart + y, colstart + x)) + '    '
                    self.SetCellValue(rowstart + y, colstart + x, c)
            text4undo = text4undo[:-1] + '\n'
        if stage == 'clip':
            self.data4undo = [rowstart, colstart, text4undo]
        else:
            self.data4undo = [0, 0, '']

    def delete(self):
        # print "Delete method"
        # Number of rows and cols
        topleft = list(self.GetSelectionBlockTopLeft())
        bottomright = list(self.GetSelectionBlockBottomRight())
        if topleft == []:
            rows = 1
            cols = 1
        else:
            rows = bottomright[0][0] - topleft[0][0] + 1
            cols = bottomright[0][1] - topleft[0][1] + 1
        # Clear cells contents
        for r in range(rows):
            for c in range(cols):
                if topleft == []:
                    self.SetCellValue(self.GetGridCursorRow() + r, self.GetGridCursorCol() + c, '')
                else:
                    self.SetCellValue(topleft[0][0] + r, topleft[0][1] + c, '')

rawDescription: Work with ctrl-c and ctrl-v to copy and paste into a wx.Grid in wxPython


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

# initializing the figure:
fig = plt.figure()

# the (carthesian) axis:
ax = fig.add_subplot(111,aspect='equal')
ax.grid(True)

# parameters of the ellipse:
a = 5.0
e = 4.0
b = np.sqrt(a**2.0 - e**2.0)

# the center of the ellipse:
x = 6.0
y = 6.0

# the angle by which the ellipse is rotated:
angle = -45.0
#angle = 0.0

# plotting the ellipse, using an artist:
ax.add_artist(Ellipse(xy=[x,y], width=2.0*a, height=2.0*b, \
                                angle=angle, facecolor='none'))
ax.set_xlim(0,2.0*x)
ax.set_ylim(0,2.0*y)

# marking the focus (actually, both)
# and accounting for the rotation of the ellipse by angle
xf = [x - e*np.cos(angle * np.pi/180.0),
      x + e*np.cos(angle * np.pi/180.0)]

yf = [y - e*np.sin(angle * np.pi/180.0),
      y + e*np.sin(angle * np.pi/180.0)]

ax.plot(xf,yf,'xr')

# plotting lines from the focus to the ellipse:
# these should be your "rays"
t = np.arange(np.pi,3.0*np.pi,np.pi/5.0)
p = b**2.0 / a
E = e / a
r = [p/(1-E*np.cos(ti)) for ti in t]

# converting the radius based on the focus
# into x,y coordinates on the ellipse:
xr = [ri*np.cos(ti) for ri,ti in zip(r,t)]
yr = [ri*np.sin(ti) for ri,ti in zip(r,t)]

# accounting for the rotation by anlge:
xrp = [xi*np.cos(angle * np.pi/180.0) - \
       yi*np.sin(angle * np.pi/180.0) for xi,yi in zip(xr,yr)]
yrp = [xi*np.sin(angle * np.pi/180.0) + \
       yi*np.cos(angle * np.pi/180.0) for xi,yi in zip(xr,yr)]

for q in range(0,len(t)):
    ax.plot([xf[0], xf[0]+xrp[q]],[yf[0], yf[0]+yrp[q]],'--b')

# put labels outside the "rays"
offset = 0.75
rLabel = [ri+offset for ri in r]
xrl = [ri*np.cos(ti) for ri,ti in zip(rLabel,t)]
yrl = [ri*np.sin(ti) for ri,ti in zip(rLabel,t)]

xrpl = [xi*np.cos(angle * np.pi/180.0) - \
        yi*np.sin(angle * np.pi/180.0) for xi,yi in zip(xrl,yrl)]
yrpl = [xi*np.sin(angle * np.pi/180.0) + \
        yi*np.cos(angle * np.pi/180.0) for xi,yi in zip(xrl,yrl)]

# for fancy label rotation reduce the range of the angle t:
tlabel = [(ti -np.pi)*180.0/np.pi for ti in t]
for q in range(0,len(tlabel)):
    if tlabel[q] >= 180.0:
        tlabel[q] -= 180.0

# convert the angle t from radians into degrees:
tl = [(ti-np.pi)*180.0/np.pi for ti in t]

for q in range(0,len(t)):
    rotate_label = angle + tlabel[q]
    label_text = '%.1f' % tl[q]
    ax.text(xf[0]+xrpl[q],yf[0]+yrpl[q],label_text,\
            va='center', ha='center',rotation=rotate_label)

plt.show()

rawDescription: Elliptic orbit with polar method tracing phases, axes and Earth direction


rawDescription: Convert string into datetime.time object


code:
from pymouse import PyMouseEvent
from threading import Thread

class DetectMouseClick(PyMouseEvent):
    def __init__(self):
        PyMouseEvent.__init__(self)

    def print_message(self):
        while self.do == 1:
            print("click")

    def click(self, x, y, button, press):
        if button == 1:
            if press:
                print("click")
                self.do = 1
                self.thread = Thread(target = self.print_message)
                self.thread.start()
            else:
                self.do = 0
                print("end")
        else:
            self.do = 0
            self.stop()

O = DetectMouseClick()
O.run()

rawDescription: Print while mouse pressed

description: Print while mouse pressed


code:
import numpy as np
import matplotlib.pyplot as plt
x = np.loadtxt('data')
plt.semilogy(x)
plt.show()

rawDescription: How to smooth from data and plot it with Python

description: Smooth from data and plot it with Python


code: boxes = Box.objects.filter(name__startswith='Big', pencils__title='blue')

rawDescription: How to filter for ManyToMany that contains object

description: Filter for ManyToMany that contains object


code:
seen_pages = dict()

# Adding a page
seen_pages.setdefault(domain, set()).add(subdomain)

# Check whether page was seen before
is_known = False
seen_subdomains = seen_pages.get(domain)
if seen_subdomains is not None:
    is_known = subdomain in seen_subdomains

rawDescription: Nested hash VS hash

description: Nested hash VS hash


code:
from xml.etree import ElementTree as ET
ET.tostring(ET.fromstring('<mytag/>'), method='html')

rawDescription: Python etree control empty tag format

description: Python etree control empty tag format


code:
with open('myfile') as fh:
  for line in fh:
    if line == match: # Some actual code here in your conditional:
      for i in range(5):
        additionalData = next(fh)

rawDescription: Python File Search Line And Return Specific Number of Lines after Match


code:
class ListMOdel(QtCore.QAbstractListModel):
    def __init__(self , data=[] ,parent=None):
        QtCore.QAbstractListModel.__init__(self,parent)
        self.__data=data

    def rowCount(self ,parent):
        return len(self.__data)

    def data(self,index,role):

        if role == QtCore.Qt.DisplayRole:
            row=index.row()
            value = self.__data[row]
            return value

    def flags(self,index):
        return QtCore.Qt.ItemIsEditable |QtCore.Qt.ItemIsEnabled| QtCore.Qt.ItemIsSelectable

    def setData(self,index,value,role=QtCore.Qt.EditRole):
        if role == QtCore.Qt.EditRole:
            row= index.row()
            self.__data[row]=value
            return True
        return False

class MainWin(QtWidgets.QMainWindow):
    itemName = ""
    def __init__(self, inheritance=None):
        super(MainWin, self).__init__()
        self.ui=uic.loadUi("MainWin.ui", self)

        self.wordList = FileProc.WordStorage().readWordFile()

        self.showListView()
        self.itemName = ""

    def showListView(self, file = 'wordlist.db'):
        MainWin.wordList = FileProc.WordStorage().readWordFile(file)
        data=[]
        for row in MainWin.wordList:
            data.append(row)

        model = ListMOdel(data)
        self.listView.setModel(model)

rawDescription: PyQt QListView retrieving item after item edited by user interface


code:
import win32api, win32con, win32process

def setaffinity():
    pid  = win32api.GetCurrentProcessId()
    mask = 128 # core 7
    handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
    win32process.SetProcessAffinityMask(handle, mask)

rawDescription: Launch program with python on a specific core


code: xl.Run("my_macro", path1, path2)

rawDescription: Python: hide Open File Dialog when running Excel macro


code:
def validatable(cls):

    # merge constraints from derived class and base classes here ...

    original_init = cls.__init__
    def init_to_insert(self, *args, **keywords):
        self.errors = {}
        original_init(self, *args, **keywords)
    cls.__init__ = init_to_insert
    return cls

rawDescription: How to initialize classes (not instances) in Python?

description: Initialize classes (not instances) in Python


code:
import novaclient.client
client = novaclient.client.Client(2, 'username', 'password',
'myproject', auth_url='http://controller:5000/v2.0')
[server.id for server in client.servers.list()]

rawDescription: Manipulate a function output in python

description: Manipulate a function output in python


code:
today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
Invoice.objects.get(user=user, date__range=(today_min, today_max))

rawDescription: Query datetime by today's date in Django


code:
list1 = ['f', 'o', 'o']
list2 = ['hello', 'world']
result = [None]*(len(list1)+len(list2))
result[::2] = list1
result[1::2] = list2
result

rawDescription: Pythonic way to combine two lists in an alternating fashion?


code:
import os

def list_files(dir):
    r = []
    subdirs = [x[0] for x in os.walk(dir)]
    for subdir in subdirs:
        files = os.walk(subdir).next()[2]
        if (len(files) > 0):
            for file in files:
                r.append(subdir + "/" + file)
    return r

rawDescription: How could I grab file from many sub-folder via main folder?


rawDescription: Loading all modules in a folder in Python


rawDescription: How to pass additional parameters to user-defined methods in pyspark for filter method?

description: Pass additional parameters to user-defined methods in pyspark for filter method


code:
import re
def asterisk_extension_match(extension, pattern):
    '''Returns True if the extension matches the pattern,
       according to the asterisk extension matching rules'''
    pattern = re.sub(r'x', '[0-9]', pattern, flags=re.I)
    pattern = re.sub(r'z', '[1-9]', pattern, flags=re.I)
    pattern = re.sub(r'n', '[2-9]', pattern, flags=re.I)
    match = re.match(pattern, extension)
    if match:
        return match.group()

rawDescription: Apply asterisk extension expression matching in a python script


code:
number_of_lines_to_print = 2

with open(filename) as adele_text:
    for line in adele_text:
        if "Hello, its me" in line:
            # printing next "number_of_lines_to_print" lines
            for _ in range(number_of_lines_to_print):
                print(next(adele_text, ''))
            break  # remove if you want to continue searching the file

rawDescription: Python3.4: for each line in text

description: Python3.4: for each line in text


code:
html_str = """

       Number
       Square

     <indent>
     <% for i in range(10): %>

         <%= i %>
         <%= i**2 %>

     </indent>

"""

Html_file= open("filename","w")
Html_file.write(html_str)
Html_file.close()

rawDescription: How to write and save html file in python?

description: Write and save html file in python


code:
f = open('house.html','w')
f.write(this_dwelling.prettify())
f.close()

rawDescription: trouble writing the output of script to a file

description: Trouble writing the output of script to a file


rawDescription: replace column in data frame with elements from another column - python

description: Replace column in data frame with elements from another column - python


code:
import sys
from tkinter import * #or Tkinter if you're on Python2.7

def button1():
    novi = Toplevel()
    canvas = Canvas(novi, width = 300, height = 200)
    canvas.pack(expand = YES, fill = BOTH)
    gif1 = PhotoImage(file = 'image.gif')
                                #image not visual
    canvas.create_image(50, 10, image = gif1, anchor = NW)
    #assigned the gif1 to the canvas object
    canvas.gif1 = gif1

mGui = Tk()
button1 = Button(mGui,text ='Sklop',command = button1, height=5, width=20).pack()

mGui.mainloop()

rawDescription: Image in tkinter window by clicking on button


code:
try:
    from unittest.mock import patch
except ImportError:
    # Python < 3.4
    from mock import patch

with patch('module.class1') as class1_mock:
    mocked_instance = class1_mock.return_value
    mocked_instance.method_to_be_called.return_value = 'Test return value'

    method()

    mocked_instance.method_to_be_called.assert_called_with('Foo', 'bar')

rawDescription: implement decorator who will be substitute one class with another implementation

description: Implement decorator who will be substitute one class with another implementation


code:
f.write("""
  <p style="color: red; font-family: 'Liberation Sans',sans-serif">
    {}
  </p>
""".format(sentences2[i]))

rawDescription: Python - Write to file with color and font


code:
from collections import defaultdict

dct1 = defaultdict(list)

with open('test.txt') as f1:
    for row in formatter(f1):
       dct1[tuple(row[:3])].append(row[3])

dct1 = {k: sum(v)/len(v) for k, v in dct1.iteritems()}

rawDescription: Averaging Repeats in Dictionary

description: Averaging Repeats in Dictionary


code:
from flask import request

@app.route('/')
@app.route('/json')
def index():
    if request.path == '/json':
        return {}
    return render_template('index.html')

rawDescription: How do I serve both HTML and JSON content with Flask?

description: Serve both HTML and JSON content with Flask


code:
def load_plugin(filename, context):
    source = open(filename).read()
    code = compile(source, filename, 'exec')
    exec(code, context)
    return context['func']

context = { 'func_one': func_one, 'func_two': func_two, 'abc': abc }
func = load_plugin(filename, context)
func()

rawDescription: python: dynamically loading one-time plugins?

description: Python: dynamically loading one-time plugins


code: f.set_attribute('metadata::emblems', gio.FILE_ATTRIBUTE_TYPE_STRINGV, ['emblem-important', 'emblem-urgent'])

rawDescription: How to write lists as a file attribute using PyGTK

description: Write lists as a file attribute using PyGTK


code:
import nltk

YOUR_STRING = "Your words"

words = [w for w in YOUR_STRING.split()]
freq_dist = nltk.FreqDist(words)

tokens = freq_dist.keys()

#50 most frequent
most_frequent = tokens[:50]

#50 least frequent
least_frequent = tokens[-50:]

rawDescription: Python script to find word frequencies of a given document


code:
infile = file('./infile_test.txt')
outfile = open('./newfile.txt', 'w')

ignore_list = ['ssh', 'snmp', 'etc']

for line in infile:
    if not any(word in line for word in ignore_list):
        outfile.write(line)

rawDescription: check if any of the items of a list is in a line of a file, if not, then write the line in a new file

description: Check if any of the items of a list is in a line of a file, if not, then write the line in a new file


code:
creCmb = (lambda v: ([v], 1))
mrgVal = (lambda x, v: (x[0]+[v], x[1]+1))

rawDescription: Pyspark combineByKey list of tuples and count


code:
import Image, ImageDraw
from math import sin, cos, pi

width, height = 400, 400

skyBlue = (135, 206, 235)

im = Image.new("RGBA", (width, height), skyBlue)

#Draw Sun
draw = ImageDraw.Draw(im)

def drawSun(draw, centre, radius, rays=False, startAngle=0, finishAngle=360, rayAngle=10, rayGap=10, rayLength=1000, rayColour="Yellow", rayOutline="Orange"):
  x1,x2 = centre[0] - radius, centre[0] + radius
  y1,y2 = centre[1] - radius, centre[1] + radius

  if rays:
    for rayStart in range(startAngle, finishAngle, rayAngle+rayGap):

      rayEnd = (rayStart+rayAngle) * pi/180
      rayStart *= pi/180

      corner1 = centre[0] + rayLength*cos(rayStart), centre[1] + rayLength*sin(rayStart)
      corner2 = centre[0] + rayLength*cos(rayEnd), centre[1] + rayLength*sin(rayEnd)

      print [centre, corner1, corner2]

      draw.polygon([centre, corner1, corner2], fill="Yellow", outline="Orange")

  draw.ellipse((x1, y1, x2, y2), fill="Yellow", outline="Orange")

drawSun(draw, (100, 100), 40, rays=True, startAngle=0, finishAngle=145, rayAngle=3, rayGap=5)

im.save("example.png")

rawDescription: Python PIL to draw a circle-segment of sunshine


code:
from bokeh.plotting import figure, show, output_notebook
import pandas as pd
output_notebook()

TESTDATA=StringIO("""1,3,123
1,4,97
1,5,83
1,6,192
2,3,126
2,3.5,97
2,4.6,102
2,5.8,45
""")

data_headers = ['eastings', 'northings', 'obs']
data_points = pd.read_csv(TESTDATA, header=None, names=data_headers)

my_color_map = ["rgb({!s},{!s},{!s})".format(20, green_val, blue_val) for blue_val, green_val in zip(data_points.obs, 255-data_points.obs)]

p=figure(x_range=(0, 5), y_range=(0, 10))
p.scatter(x=data_points.eastings, y=data_points.northings, size=25, fill_color=my_color_map)
show(p)

rawDescription: Colour palette creation with python bokeh


code:
spans = soup.find_all('span', attrs={'id':'titleDescriptionID'})
for span in spans:
    if span.string:
         "your code"

rawDescription: How to find any element inside <div> using beautifulsoup

description: Find any element inside <div> using beautifulsoup


code:
def raise_to_power(base_val, exponent_val):
   if exponent_val == 0:
      return 1
   else:
      return base_val * raise_to_power(base_val, exponent_val-1)

user_base = 4
user_exponent = 2

print('%d^%d = %d' % (user_base, user_exponent,
      raise_to_power(user_base, user_exponent)))

rawDescription: Recursion in Python with exponents

description: Recursion in Python with exponents


code:
def get_user_version(username):
    version = cache.get("%s_version" % username)
    if version is None:
        version = random.randint(1, 1000000000)
        cache.set("%s_version" % username, version)
    return version

def get_user_cache(username, key):
    version = get_user_version(username)
    return cache.get("%s_%d_%s" % (username, version, key))

def set_user_cache(username, key, value):
    version = get_user_version(username)
    cache.set("%s_%d_%s" % (username, version, key), value)

def invalidate_user_cache(username):
    version = cache.incr("%s_version" % username)

rawDescription: how to delete a particular key from low-level cache API in django

description: Delete a particular key from low-level cache API in django


code:
from random import randint
from collections import defaultdict

d = defaultdict(set)

for i in range(10):
    el = randint(0, 5)
    d[el].add(randint(0,10))

d
d[0]
d[2]

rawDescription: Adding elements to a dictionary of sets

description: Adding elements to a dictionary of sets


code:
soup = BeautifulSoup(data, 'html5lib')
soup = BeautifulSoup(data, 'html.parser')
soup = BeautifulSoup(data, 'lxml')

rawDescription: Beautifulsoup Cannot FindAll

description: Beautifulsoup Cannot FindAll


code:
from dateutil.parser import parse

def update_event(start_datetime=None, end_datetime=None, description=None):
    if start_datetime is not None:
        new_start_time = parse(start_datetime)

        return new_start_time

d = ['23/04/2014', '24-04-2013', '25th April 2014']

new = [update_event(i) for i in d]

for date in new:
    print(date)
    # 2014-04-23 00:00:00
    # 2013-04-24 00:00:00
    # 2014-04-25 00:00:00

rawDescription: Guessing the date format python

description: Guessing the date format python


code:
from collections import namedtuple
# We define our data type like this:
fileData = namedtuple('fileData', ('name', 'path', 'size'))

# Now we can create an instance of it:

def pathToData(pathAndName):
    path, name = os.path.split(pathAndName)
    size = os.path.getsize(pathAndName)
    return fileData(name, path, size)

# Or a whole bunch at once, using a list comprehension:
def pathsToData(filePaths):
    return [pathToData(p) for p in filePaths]
    # There is no need to do all the 'append' logic yourself.

rawDescription: I need help with classes - class for displaying filenames, file size, path, and anything else


code:
sshFile="darkorange.stylesheet"
with open(sshFile,"r") as fh:
    self.setStyleSheet(fh.read())

rawDescription: reading pyqt stylesheet from external qss file

description: Reading pyqt stylesheet from external qss file


code:
def nodes_connected(u, v):
    return u in G.neighbors(v)

nodes_connected("a", "d")
nodes_connected("a", "c")

rawDescription: How to check whether two nodes are connected?

description: Check whether two nodes are connected


code:
my_array[0,:,:]
my_array[0,:,:].shape

rawDescription: how to extract required dimension from a numpy array

description: Extract required dimension from a numpy array


code:
import re
def get_encoding(soup):
    encod = soup.meta.get('charset')
    if encod == None:
        encod = soup.meta.get('content-type')
        if encod == None:
            content = soup.meta.get('content')
            match = re.search('charset=(.*)', content)
            if match:
                encod = match.group(1)
            else:
                raise ValueError('unable to find encoding')
    return encod

rawDescription: Trying to get encoding from a webpage Python and BeautifulSoup


code:
msg = dbus.Struct((dbus.String(u'msg_subject:Re: email subject'),), signature=None)
msg[0]

rawDescription: get dbus.Struct properties

description: Get dbus.Struct properties


code:
# Pull start and end dates from form
# ...
# Build a constraint if `start` and / or `end` have been set.
created = None
if start and end:
    created = sa.sql.between(msg.c.create_time_stamp,
        start.replace(hour=0, minute=0, second=0),
        end.replace(hour=23, minute=59, second=59))
elif start:
    created = (msg.c.create_time_stamp >=
               start.replace(hour=0, minute=0, second=0))
elif end:
    created = (msg.c.create_time_stamp <=
               end.replace(hour=23, minute=59, second=59))

# More complex `from_` object built here, elided for example
# [...]
# Final query build
query = sa.select([unit.c.eli_uid], from_obj=[from_])
query = query.column(count(msg.c.id).label('sent'))
query = query.where(current_store)
if created:
    query = query.where(created)

rawDescription: Is SQLAlchemy still recommended if only used for raw sql query?


code:
def parseLocation(self,response):
    hxs = HtmlXPathSelector(response)
    item = response.meta['item']

    dl = hxs.select("//dl")
    if len(dl)>0:
        address = hxs.select("//dl[1]/dd").extract()
        loc = {'address':remove_entities(replace_escape_chars(replace_tags(address[0], token=' '), replace_by=''))}
        yield loc

    locations_select = hxs.select("//select/option/@value").extract()
    if len(locations_select)>0:
        yield self.fetchLocations(locations_select, response.meta['company_id'], item)

rawDescription: Scrapy - Crawl Multiple Pages Per Item

description: Scrapy - Crawl Multiple Pages Per Item


code:
from sphinx.ext.mathbase import MathDirective, math_role

def setup(app):
    app.add_directive('m', MathDirective)
    app.add_role('m', math_role)

rawDescription: Sphinx: how to add a role and directive alias


code:
class Array(list):

    def __init__(self, l):

        def a(x):
            if isinstance(x, list):
                return Array([a(y) for y in x])
            return x

        if isinstance(l, list):
            self.extend(a(x) for x in l)
        else:
            self.append(l)

z = Array([1,[2,[3]]])
assert isinstance(z, Array)
assert isinstance(z[1], Array)
assert isinstance(z[1][1], Array)

rawDescription: How to initialize recursively a class inheriting of list?

description: Initialize recursively a class inheriting of list


rawDescription: Set connection settings with Pyodbc + UnixODBC + FreeTDS


code: ['<a href="%s">%s' % (n, l) for (n, l) in zip(name, link)]

rawDescription: Python Join multiple lists into a string with %


code: prefixes = [your_list[:end] for end in xrange(1, len(your_list) + 1)]

rawDescription: Create all sequences from the first item within a list


rawDescription: using HttpResponseRedirect

description: Using HttpResponseRedirect


code: #!/usr/bin/env python3

rawDescription: How to make Python script portable to machines with interpreters in different locations?

description: Make Python script portable to machines with interpreters in different locations


code: r = redis.Redis(host=redisHost, port=redisPort, db=N)

rawDescription: How to prepare separate Database for redis with python?

description: Prepare separate Database for redis with python


code: o.autoexec.append('%logstart <option>')

rawDescription: How to configure ipy_user_conf.py to get IPython to start logging right away?

description: Configure ipy_user_conf.py to get IPython to start logging right away


code:
parser = argparse.ArgumentParser(prog='PROG')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-s', type=int)
parser.add_argument('-p', type=int)

def binary(value):
    # just test if the value is a valid binary string
    try:
        int(value, 2)
    except ValueError:
        raise argparse.ArgumentTypeError('{!r} is not a valid binary value'.format(value))
    return value

group.add_argument('-r', type=binary)

group.add_argument('-l', type=binary)

args = parser.parse_args()
if args.s and args.p is None:
    parser.error('You must use -p when -s is selected')

rawDescription: Optional keyword arguments - argparse

description: Optional keyword arguments - argparse


code:
data = dict()
for idx, num in enumerate(someList):
    data['record{}'.format(idx)] = SubElement(records, 'record')

rawDescription: Variable variables for use in Element Tree Python


code:
from datetime import strptime

# ... your code ...

date = strptime(date, "%Y-%m-%d %H:%M:%S %Z")

rawDescription: Date formatting in django

description: Date formatting in django


code:
from itertools import cycle, islice
myArray = ['a','b','c','d']
pool = cycle(myArray)

print(next(islice(pool, 5)))
a

rawDescription: index into a circular array

description: Index into a circular array


code:
today = datetime.today()
datem = datetime(today.year, today.month, 1)

rawDescription: Datetime current year and month python

description: Datetime current year and month python


code:
from google.appengine.api import app_identity
import cloudstorage as gcs

default_bucket = app_identity.get_default_gcs_bucket_name()
gcs_filename = '/%s/%s' % (default_bucket, image_file_name)
with gcs.open(gcs_filename, 'w', content_type='image/jpeg') as f:
    f.write(image_byte)

blob_key = blobstore.create_gs_key('/gs' + gcs_filename)
# and create a serving url

rawDescription: Migrating from App Engine Files API

description: Migrating from App Engine Files API


code:
# create the limiting polygon
vert_x = np.concatenate((SII, SIIs[::-1]))
vert_y = np.concatenate((log_OIII_Hb_SII(SII), stravinska_SII(SIIs[::-1])))

p = plt.Polygon(np.column_stack((vert_x, vert_y)), facecolor='gray', alpha=.45, edgecolor='none')

ax.add_artist(p)

rawDescription: Filling space between two functions in matplotlib: unsightly patch


code:
args = {}
for arg in shlex.split(cmdln_args):
    key, value = arg.split('=', 1)
    args[key] = value

rawDescription: Customized command line parsing in Python


code:
class Model(object):

    ...

    def __hash__(self):
        return hash(self._get_pk_val())

    ...

    def __eq__(self, other):
        return isinstance(other, self.__class__) and \
               self._get_pk_val() == other._get_pk_val()

rawDescription: Are Django Model instances Hashable?

description: Are Django Model instances Hashable


code:
class Foo(dict):
    def __init__(self):
        self['bar1'] = Bar1()
        self['bar2'] = Bar2()

class BarBase(object):
    @property
    def value(self):
        return self.compute_value()

class Bar1(BarBase):
    def compute_value(self):
        return 'I am bar1.'

class Bar2(BarBase):
    def compute_value(self):
        return 'I am bar2.'

foo = Foo()
print(foo['bar1'].value)
print(foo['bar2'].value)

rawDescription: Dynamic property needs to call __get__ explicitly (Python)


code:
from socket import *
from threading import Thread

clients = []

def clientHandler(c, addr):
    global clients
    print(addr, "is Connected")
    try:
        while True:
            data = c.recv(1024)
            if not data:
                break
            for client in clients:
                if addr != client:
                    c.sendto(data, client)
    except:
        print("Error. Data not sent to all clients.")

HOST = '' #localhost
PORT = 8000

s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)

print("Server is running on "+ str(PORT))

#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
trds = []

for i in range(5):
    c, addr = s.accept()
    clients.append(addr)
    t = Thread(target=clientHandler, args = (c, addr))
    trds.append(t)
    t.start()

for t in trds:
    t.join()

s.close()

rawDescription: Python 3: Socket server send to multiple clients with sendto() function


code: newMail.HTMLBody  = htmltext

rawDescription: Python - Send HTML-formatted email via Outlook 2007/2010 and win32com


rawDescription: Should you always use with when printing to files in python


code:
import urlparse
url = 'http://www.example.com/servlet/av/jd?ai=782&ji=2553120&sn=I'
query_string = urlparse.urlparse(url).query
query_dict = urlparse.parse_qs(query_string)
query_dict
int(query_dict['ji'])

rawDescription: How to collect only the required integers from a string by matching specific word in python

description: Collect only the required integers from a string by matching specific word in python


code:
i, l = 0, len(self.corpses)
while i < l:
    j = i + 1
    while j < l:
        if self.corpses[i].collides(self.corpses[j]):
            self.corpses[i] = self.corpses[i] + self.corpses[j]
            del self.corpses[j]
            l -= 1
        else:
            j += 1
    i += 1

rawDescription: Deleting element in a python list iterated by index


code:
import sys
import re
regex = re.compile(r'(\S+\s+){2,3}P\s.*')
with open(sys.argv[1]) as file:
    for line in file:
        line = line.strip() #Consider striping the line if it's necessary
        if regex.search(line):
            print(line)

rawDescription: Need some help to write a python script

description: Need some help to write a python script


code:
from collections import namedtuple

MyStruct = namedtuple('MyStruct', 'Mark nPackLen nFlag nGisIp nPort sData sEnd')

NodeList = []
Node = MyStruct(None, '', '', '', '',  -1, 0)
for id in range(4):
     NodeList.append(Node)

rawDescription: Edited : how to declare array of struct in Python


code:
from pylab import *

z = rand(10, 25)

c = pcolor(z)
set_cmap('hot')
colorbar()
c = pcolor(z, edgecolors='w', linewidths=1)
axis([0,25,0,10])
savefig('plt.png')
show()

rawDescription: Plotting eigenbehaviours with matplotlib


code:
user_did_something = Signal(providing_args=["data"])

class User(models.Model):
    identifier = models.CharField(max_length=32)
    def send_signal(self):
        user_did_something.send(sender=intern(self.example_field.encode('utf8')), data=self)

ADMIN_USER = intern('admin')
BIG_ADMIN_USER = intern(u'größer admin'.encode('utf8'))

user_did_something.connect(admin_behavior, sender=ADMIN_USER)
user_did_something.connect(big_admin_behavior, sender=BIG_ADMIN_USER)

rawDescription: using django encoded strings as a sender for django signals

description: Using django encoded strings as a sender for django signals


code: df = pd.concat([df, pd.get_dummies(df['YEAR'])], axis=1); df

rawDescription: Python Pandas add dummy columns to the original dataframe


code:
import Queue
changes = Queue.Queue()

rawDescription: Python - threaded pyinotify output. Better to write to file or to a string


code:
list_b = []
for x in list_a:
    i = iter(x)
    name = next(i)
    list_b.extend((name,) + t for t in zip(*(y.split(",") for y in i)))

rawDescription: How to uncollapse a list with coma separated columns in python?

description: Uncollapse a list with coma separated columns in python


code:
cur.execute('select * from table_name')
result = cur.fetchall()

# For details: http://www.python.org/dev/peps/pep-0249/#description
db_description = cur.description
columns = [col_desc[0] for col_desc in db_description]

# As the pandas' doc said, `coerce_float`: Attempt to convert values to non-string, non-numeric objects (like decimal.Decimal) to floating point
df = DataFrame(result, columns=columns, coerce_float=True)

# dealing the missing data
for column_name in df.columns:
    # Currently, calling function `fillna(np.nan) on a `datetime64[ns]` column will cause an exception
    if df[column_name].dtype.str != '<M8[ns]':
        df[column_name].fillna(np.nan)

# convert the type of columns which both have np.nan and datetime obj from 'object' to 'datetime64[ns]'(short as'<M8[ns]')
# find the table columns whose type is Date or Datetime
column_name_type_tuple = [column[:2] for column in db_description if column[1] in (10, 12)]
# check whose type is 'object'
columns_need_conv = [column_name for column_name, column_type in column_name_type_tuple if str(df[column_name].dtype) == 'object']

# do the type converting
for column_name in columns_need_conv:
    df[column_name] = Series(df[column_name].values, dtype='M8[ns]')

df = df.convert_objects()

rawDescription: Better solution when dealing with the missing data for those dataframe objs exported from related db


code:
libsvm.predict(
        X, self.support_, self.support_vectors_, self.n_support_,
        self.dual_coef_, self._intercept_,
        self.probA_, self.probB_, svm_type=svm_type, kernel=kernel,
        degree=self.degree, coef0=self.coef0, gamma=self._gamma,
        cache_size=self.cache_size)

rawDescription: Set the weights of decision functions through stdin in Sklearn


code:
import os
from collections import Counter
from sys import argv

# adjust your cut point
PERCENT_CUT = 0.9

# here we are going to save each file's entries, so we can sum them later
files_dict = {}

# total files seems to be the number you'll need to check against count
total_files  = 0;

# raw total entries, even duplicates
total_entries = 0;

unique_entries = 0;

# first argument is script name, so have the second one be the folder to search
search_dir = argv[1]

# list everything under search dir - ideally only your input files
# CHECK HOW TO READ ONLY SPECIFIC FILE types if you have something inside the same folder
files_list = os.listdir(search_dir)

total_files = len(files_list)

print('Files READ:')

# iterate over each file found at given folder
for file_name in files_list:
    print("    "+file_name)

    file_object = open(search_dir+file_name, 'r')

    # returns a list of entries with 'newline' stripped
    file_entries = map(lambda it: it.strip("\r\n"), file_object.readlines())

    # gotta count'em all
    total_entries += len(file_entries)

    # set doesn't allow duplicate entries
    entries_set = set(file_entries)

    #creates a dict from the set, set each key's value to 1.
    file_entries_dict = dict.fromkeys(entries_set, 1)

    # entries dict is now used differenty, each key will hold a COUNTER
    files_dict[file_name] = Counter(file_entries_dict)

    file_object.close();

print("\n\nALL ENTRIES COUNT: "+str(total_entries))

# now we create a dict that will hold each unique key's count so we can sum all dicts read from files
entries_dict = Counter({})

for file_dict_key, file_dict_value in files_dict.items():
    print(str(file_dict_key)+" - "+str(file_dict_value))
    entries_dict += file_dict_value

print("\nUNIQUE ENTRIES COUNT: "+str(len(entries_dict.keys())))

# print(entries_dict)

# 90% from your question
cut_line = total_files * PERCENT_CUT
print("\nNeeds at least "+str(int(cut_line))+" entries to be listed below")
#output dict is the final dict, where we put entries that were present in > 90%  of the files.
output_dict = {}
# this is PYTHON 3 - CHECK YOUR VERSION as older versions might use iteritems() instead of items() in the line belows
for entry, count in entries_dict.items():
    if count > cut_line:
        output_dict[entry] = count;

print(output_dict)

rawDescription: Search and output with Python

description: Search and output with Python


code:
import pyparsing as p
ope, clo, com = map(p.Suppress, '(),')
w = p.Word(p.alphas)
s = ope + w + com + w + com + ope + p.delimitedList(w) + clo + clo
x = '(xx,yyy,(aa,bb,cc))'
list(s.parseString(x))

rawDescription: extract parts of the string in python

description: Extract parts of the string in python


code:
from scipy.sparse import lil_matrix

positions = [[1, 2, 10], [], [5, 6, 2]]
data = [[1, 1, 1], [], [1, 1, 1]]

l = lil_matrix((3, 11))
l.rows = positions
l.data = data

c = l.tocsr()

rawDescription: How to convert generated id, list-of-index values tuple to a one hot encoded sparse matrix

description: Convert generated id, list-of-index values tuple to a one hot encoded sparse matrix


code:
[ quote for quote in
    (histRecordToQuote(securitiesDict = securitiesDict,
                       nameStr        = nameStr,
                       valueDate      = valueDate,
                       record         = record)
      for nameStr, nameData in dataTbl.iteritems()
        for valueDate, record in nameData.iteritems())
    if quote ]

rawDescription: Pythonic way to produce a list from nested dictionary


code:
import lifter

my_objects = MyModel.objects.all().order_by('-field', 'parent__field')

# ... manipulate my_objects ...

ObjModel = lifter.models.Model('MyModel')
manager = ObjModel.load(my_objects)

results = manager.order_by('-field', 'parent__field')

rawDescription: Can I use Django style order_by() to sort a list of existing model objects instead of QuerySet?

description: Use Django style order_by() to sort a list of existing model objects instead of QuerySet


code:
def make_linear_interpolator(x0, x1, y0, y1):
    """
    Return a function to convert x in (x0..x1) to y in (y0..y1)
    """
    dy_dx = (y1 - y0) / float(x1 - x0)
    def y(x):
        return y0 + (x - x0) * dy_dx
    return y

color_to_temp = make_linear_interpolator(0, 32, 44000, 3200)

color_to_temp(10)    # => 32150.0

rawDescription: Maths ratios in Python

description: Maths ratios in Python


code:
import numpy as np
my_list = [10,13,42,23,12,45,33,59,12]
np.cumsum(my_list) / np.arange(1, len(my_list)+1, dtype=np.float)

rawDescription: Calculating the averages iteratively and efficiently


code:
import ast
raw = r"r'\nasdf'"
ast.literal_eval(raw)
raw = r"'\nasdf'"
ast.literal_eval(raw)

rawDescription: Python convert string literals to strings


rawDescription: Appending to NumPy (Python) Array

description: Appending to NumPy (Python) Array


code:
import re

class PhpConfig:
    def __init__(self, config_filename):
        self.defines = {}
        with open(config_filename) as infile:
            for ln in infile:
                match = re.findall('^define\(\'([A-Za-z_0-9]+)\', ?\'(.*)\'', ln)
                if len(match):
                    self.defines[match[0][0]] = match[0][1]

php_config = PhpConfig('config.php')

# Printing define dictionary
print(php_config.defines)

# Accessing just DB_USER
print(php_config.defines['DB_USER'])

rawDescription: use file php in python and use or print variable config

description: Use file php in python and use or print variable config


code:
class Glowne(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent=parent)
        tekst = 'HELLO - position'
        font = wx.Font(18, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
        self.text = wx.StaticText(self, -1, tekst, (300, 55))  # Save for later use
        self.text.SetFont(font)

        btn = wx.Button(self, -1, "Change pos", (345, 100))
        btn.Bind(wx.EVT_BUTTON, self.change_pos)

    def change_pos(self, event):
        x, y = self.text.Position
        self.text.SetPosition((x, y + 10))

rawDescription: wxPython - modify a frame

description: WxPython - modify a frame


code:
import numpy as np
import time

# import mayavi's mlab API for scripting
from mayavi import mlab

###variable declarations
nx = 31
ny = 31
nt = 17
nu=.05
dx = 2.0/(nx-1)
dy = 2.0/(ny-1)
sigma = .25
dt = sigma*dx*dy/nu

x = np.linspace(0,2,nx)
y = np.linspace(0,2,ny)

u = np.ones((ny,nx)) ##create a 1xn vector of 1's
un = np.ones((ny,nx)) ##

###Assign initial conditions

u[.5/dy:1/dy+1,.5/dx:1/dx+1]=2 ##set hat function I.C. : u(.5<=x<=1 && .5<=y<=1 ) is 2
X,Y = np.meshgrid(x,y)

###Run through nt timesteps

u[.5/dy:1/dy+1,.5/dx:1/dx+1]=2

# create a surface from grid-shaped data
surf = mlab.mesh(X,Y,u[:])

t = time.time()
max_framerate = 10
for n in range(nt+1):
    un[:] = u[:]
    u[1:-1,1:-1]=un[1:-1,1:-1]+nu*dt/dx**2*(un[2:,1:-1]-2*un[1:-1,1:-1]+un[0:-2,1:-1])+nu*dt/dy**2*   (un[1:-1,2:]-2*un[1:-1,1:-1]+un[1:-1,0:-2])

    u[0,:]=1
    u[-1,:]=1

    u[:,0]=1
    u[:,-1]=1

    # the mlab_source attribute of surf represents the data we're plotting.
    # it has x, y and z attributes as you'd expect. here we only need to
    # update the z attribute
    surf.mlab_source.z = u

    # there's no need to call any equivalent to matplotlib's draw() or show()
    # functions - another draw event gets triggered automatically whenever
    # surf's data source gets modified

    # put a pause in here to control the maximum framerate
    while time.time() - t < (1./max_framerate):
        pass
    t = time.time()

rawDescription: How to create a 3D animation of a surface defined by 2 spatial coordinates using matplotlib/Mayavi?

description: Create a 3D animation of a surface defined by 2 spatial coordinates using matplotlib/Mayavi


code:
import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4, 5]
y = [1, 3, 2, 5, 3, 1]
plt.figure()
plt.plot(x,y,'b-')
plt.plot(x,y,'wo', markersize=25, markeredgecolor = 'w')
plt.plot(x,y,'bo', markersize=7, markeredgecolor = 'w')
plt.show()

rawDescription: Shortening line segments in Matplotlib plots


code:
f = open(localFilePath, 'w')
f.write(urlopen(remoteFilePath).read())
f.close()

rawDescription: How to write a python script for downloading?

description: Write a python script for downloading


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

nrows = 10
ncols = 10
a = np.random.rand(nrows, ncols)
pcm = plt.pcolormesh(a, cmap="Greys")

# Apparently need to render once in order to assign facecolors
# to the grid created by pcolormesh:
plt.draw()

fc = pcm.get_facecolors()
fc_grid = fc.reshape(nrows, ncols, -1)

alpha = 0.2
fc_grid[:, 3:6] = (1-alpha)*fc_grid[:, 3:6] + alpha*np.array([1.0, 0, 0, 1])
fc_grid[4:7, 7:] = (1-alpha)*fc_grid[4:7, 7:] + alpha*np.array([0, 1.0, 0, 1])

plt.show()

rawDescription: Pyplot exporting to .eps with alpha < 1

description: Pyplot exporting to .eps with alpha < 1


code:
import re

listA = ['a', 'b', 'a@b=c', 'a @ b = c', 'a@ =b', 'a@=b' 'a=b@c', 'a@b' ]
listB = [a for a in listA if not re.search('@\s*\w+\s*=', a)]

rawDescription: How to remove elements of a list containing specific patten with python?

description: Remove elements of a list containing specific patten with python


code: teams_list = list(itertools.combinations(teams, 2))

rawDescription: Itertools and customizing list

description: Itertools and customizing list


code:
reobj = re.compile('\d{4}-\d{2}-\d{2}')
for root, subs, files in os.walk('.'):
    for name in subs:
        if reobj.match(name):
            print(name)

rawDescription: Using fnmatch to locate all folders with name pattern


rawDescription: Why does my program reverse the list but then add lots of unnecessary punctuation?


code:
def thread_for_ident(ident):
    return threading._active.get(ident)

rawDescription: How can I get the name of the thread by knowing the thread id?

description: Get the name of the thread by knowing the thread id


code:
with open("business.xml", "rb") as inp:
    tree = etree.parse(inp)

rawDescription: How to decode file in Python-3.x?

description: Decode file in Python-3.x


code:
logger = logging.getLogger(__name__)

def my_fancy_function():
    logger.warning('test')

@patch('logging.Logger.warning')
def test_my_fancy_function(mock):
    my_fancy_function()
    mock.assert_called_with('test')

# if you insist on using with:
def test_my_fancy_function_with_with():
    with patch('logging.Logger.warning') as mock:
        my_fancy_function()
        mock.assert_called_with('test')

rawDescription: Assert that logging has been called with specific string


code: [all(any(x.startswith(y) for y in l) for x in sub) for sub in s]

rawDescription: find if a list of list has items from another list

description: Find if a list of list has items from another list


code:
from bottle import response, install
import time

def stopwatch(callback):
    def wrapper(*args, **kwargs):
        start = time.time()
        body = callback(*args, **kwargs)
        end = time.time()
        response.headers['X-Exec-Time'] = str(end - start)
        return body
    return wrapper

install(stopwatch)

rawDescription: Access the response object in a bottlepy after_request hook


code:
yield x if condition1 else None
yield y if condition2 else None

rawDescription: If/yield cascade - how to make more concise?


code: ['%s://%s' % (scheme, domain) for scheme in ('http', 'https') for domain in domains]

rawDescription: Reduce multiple list comprehesion into a single statement


code:
class MyBall(object):
    ...
    def update(self, dt):
        ...
        self.trajectory.append(self.position)

    def draw(self, surface):
        pygame.draw.lines(surface, somecolor, self.trajectory)

rawDescription: Pygame physics simulation

description: Pygame physics simulation


code:
def _col_seq_set(df, col_list, seq_list):
    ''' set dataframe 'df' col_list's sequence by seq_list '''
    col_not_in_col_list = [x for x in list(df.columns) if x not in col_list]
    for i in range(len(col_list)):
        col_not_in_col_list.insert(seq_list[i], col_list[i])

    return df[col_not_in_col_list]
DataFrame.col_seq_set = _col_seq_set

rawDescription: How to rearrange Pandas column sequence?

description: Rearrange Pandas column sequence


code:
def getTopicForQuery (question):
    temp = question.lower()
    for i in range(len(punctuation_string)):
        temp = temp.replace(punctuation_string[i], '')

    words = re.findall(r'\w+', temp, flags = re.UNICODE | re.LOCALE)

    important_words = []
    important_words = filter(lambda x: x not in stoplist, words)

    dictionary = corpora.Dictionary.load('questions.dict')

    ques_vec = []
    ques_vec = dictionary.doc2bow(important_words)

    topic_vec = []
    topic_vec = lda[ques_vec]

    word_count_array = numpy.empty((len(topic_vec), 2), dtype = numpy.object)
    for i in range(len(topic_vec)):
        word_count_array[i, 0] = topic_vec[i][0]
        word_count_array[i, 1] = topic_vec[i][1]

    idx = numpy.argsort(word_count_array[:, 1])
    idx = idx[::-1]
    word_count_array = word_count_array[idx]

    final = []
    final = lda.print_topic(word_count_array[0, 0], 1)

    question_topic = final.split('*') ## as format is like "probability * topic"

    return question_topic[1]

rawDescription: How to predict the topic of a new query using a trained LDA model using gensim?

description: Predict the topic of a new query using a trained LDA model using gensim


code:
from django.shortcuts import render

def some_handler(request):
    context_for_template = {}
    return render(request, 'template_name.html', context_for_template)

rawDescription: what's the alternative solution of tornado's "write" in django?

description: What's the alternative solution of tornado's "write" in django


code:
import pymysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock', user='root', passwd=None, db='mysql')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
for r in cur:
    print(r)
cur.close()
conn.close()

rawDescription: Python 3.2 script to connect to local MySQL database


code:
multiplicand,i = 50,2
result= multiplicand *i
max_len = 2

format = "%d\t*\t%d\t=\t%" +str(max_len)+ "d"
print (format % (multiplicand,i,result))

rawDescription: How to format ouput for a specified number of characters in python

description: Format ouput for a specified number of characters in python


code:
from time import sleep
# Assume proc is the Popen object
wait_time = 1 # 1 second, same delay as `tail -f`
while True: # Or whatever condition you need
    line = proc.stdout.readline()
    if line != '' and line != '\n':
        parse_line_do_stuff()

    sleep(wait_time)

rawDescription: Capture output from external C program with python GUI in realtime


code:
a = np.random.randint(10, size=(10,))
a
a > 3
np.where(a > 3)
np.nonzero(a > 3)

rawDescription: finding indicies of a list if they are outside a certain value. python, numpy

description: Finding indicies of a list if they are outside a certain value. python, numpy


code:
from itertools import imap
from operator import itemgetter
import heapq

def extract_timestamp(line):
    """Extract timestamp and convert to a form that gives the
    expected result in a comparison
    """
    return line.split()[1] # for example

with open("log1.txt") as f1, open("log2.txt") as f2:
    sources = [f1, f2]
    with open("merged.txt", "w") as dest:
        decorated = [
            ((extract_timestamp(line), line) for line in f)
            for f in sources]
        merged = heapq.merge(*decorated)
        undecorated = imap(itemgetter(-1), merged)
        dest.writelines(undecorated)

rawDescription: Merging pre-sorted files without reading everything into memory


code:
fig, axs = plt.subplots(2,1)

axs[0].plot(np.random.randn(100).cumsum())
axs[1].plot(np.random.randn(100).cumsum())

aspect = np.diff(axs[1].get_xlim()) / np.diff(axs[1].get_ylim())
axs[1].set_aspect(aspect)

rawDescription: How to resize box axes in matplotlib

description: Resize box axes in matplotlib


code:
class Data:
    def __init__(self, firstName, lastName, address):
        self.firstName = firstName
        self.lastName = lastName
        self.address = dict(address)

data = Data("first", "last", dict(state="pa", city="pittsburgh"))

rawDescription: accessing dictionary with classes

description: Accessing dictionary with classes


code:
import Tkinter
import os, signal

window1 = Tkinter.Tk()
window1.attributes('-fullscreen', True)
window1.bind("<Escape>", lambda e: e.widget.quit())

window2 = Tkinter.Label(window1)
window2.configure(bg = "blue")
window2.place(x=0, y=0, relwidth=1, relheight=1)

frame = Tkinter.Frame(window2, height=160)
frame.pack(anchor=Tkinter.SW,side=Tkinter.BOTTOM)

canvas=Tkinter.Canvas(frame,bg='black', width=5500, height=160)

hbar=Tkinter.Scrollbar(frame,orient=Tkinter.HORIZONTAL, bg='black', troughcolor='black')
hbar.pack(side=Tkinter.BOTTOM,fill=Tkinter.X)
hbar.config(command=canvas.xview)

canvas.config(xscrollcommand=hbar.set, xscrollincrement=4.5)
canvas.pack(side=Tkinter.LEFT, expand=True, fill=Tkinter.BOTH)
frm = Tkinter.Frame(canvas)
canvas.create_window(0, 0, window=frm, anchor='nw')

def quit():
    window1.quit()

count = 0
width = 0
while (count < 500):
    X = Tkinter.Button(frm, text=str(count), height=6, width=5, padx=0, pady=0, highlightcolor="blue", highlightthickness=3, command=quit)
    X.pack(side = "left")
    width += X.winfo_reqwidth()
    count = count + 1

canvas.config(scrollregion=(0, 0, width, 0))
window1.mainloop()

rawDescription: Tkinter, I cannot get my slider to show all buttons


code:
gameDisplay = pygame.display.set_mode((display_width, display_height)) #removed =
myFont = pygame.font.SysFont("monospace", 15)
pygame.display.set_caption("Catastrophee")
background = pygame.Surface(gameDisplay.get_size())
background = background.convert()

rawDescription: pygame error: Tuple has no attribute get_size()

description: Pygame error: Tuple has no attribute get_size()


code:
import re

def natural_sort(l):
    convert = lambda text: int(text) if text.isdigit() else text.lower()
    alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
    return sorted(l, key=alphanum_key)

rawDescription: Python natural sorting

description: Python natural sorting