code: import_transform: "lambda x: 'default A'"

rawDescription: appengine import_transform custom value

description: Appengine import_transform custom value


code: m =  re.search('(\d+(?:\s*\d+)*)\s*([\w]+)@([\w.]+)','Some garbage 13245 65798 username@hostname.com and others garbage texts.')

rawDescription: Can't delete white space in a substring thorugh regular expression in python 3x


code:
import pandas as pd

# option 1 - compare using python datetime.date objects
dates = pd.Series(pd.date_range('2015-01-01', '2016-12-31'))  # Timestamps
python_dates = pd.Series([x.date() for x in dates])           # datetime.date
today = pd.Timestamp('now').date()                            # datetime.date
print(python_dates[python_dates == today])

# option 2 -  compare pandas.Timestamp objects using Series.dt accessor
dates = pd.Series(pd.date_range('2015-01-01', '2016-12-31'))  # Timestamps
today = pd.Timestamp('now')                                   # Timestamp
print(dates[(dates.dt.year == today.year) &
    (dates.dt.month == today.month) &
    (dates.dt.day == today.day)])

rawDescription: pandas.tslib.Timestamp date matching

description: Pandas.tslib.Timestamp date matching


code:
from datetime import datetime
sorted(li, key=lambda x: datetime.strptime(x[1], '%a %b %d %Y'))

rawDescription: Sorting a dictionary by a key which is in timestamp format


code:
from test import *
__all__ = ['say']

rawDescription: 'help' function not showing info about imported functions


code: primslist=[getattr(mufprims, x) for x in dir(mufprims) if not primsfilter.match(x) ]

rawDescription: Get symbol for def in module in Python

description: Get symbol for def in module in Python


code: list(collections.deque((1, 2, 3)))

rawDescription: Converting a deque object into list

description: Converting a deque object into list


code:
import itertools

a = ["1"]
b = ["0"]
c = ["a","b","c"]
d = ["d","e","f"]

for item in itertools.product(a, b, c, d):
    print(item)

rawDescription: permutations of lists python

description: Permutations of lists python


code: list(itertools.product(*["01"] * 2))

rawDescription: Generate Binary Table with Itertools and Python


code: hasattr(mod1, "func1")

rawDescription: Check if modules offer required functions without executing them


code:
from django.db.models import Count
School.objects.filter(student__type='ug').annotate(
                      num_students=Count('student')
                     ).order_by('num_students')

rawDescription: How to order by aggregate with conditions on fields of a relation

description: Order by aggregate with conditions on fields of a relation


code:
result = [my_list[idx:idx + 3] for idx in range(0, len(my_list), 3)]
# [['text1', 'text1', 'text1'],
#           ['text2', 'text2', 'text2'], ['text3', 'text3', 'text3']]

rawDescription: Split a list into sub lists in python

description: Split a list into sub lists in python


code:
def fbest(A, X):
  ""
  KA_best = np.tensordot(A.sum(1)[:,None] * X, X, axes=[(0,), (0,)])
  KA_best += np.tensordot(A.sum(0)[:,None] * X, X, axes=[(0,), (0,)])
  KA_best -= np.tensordot(np.dot(A, X), X, axes=[(0,), (0,)])
  KA_best -= np.tensordot(X, np.dot(A, X), axes=[(0,), (0,)])
  return KA_best

rawDescription: NumPy tensordot MemoryError

description: NumPy tensordot MemoryError


code:
document = search.Document(
    doc_id = files[file_index],
    fields =
        [ search.TextField(name='name', value=my_name) ]
        + [ search.AtomField(name='category', value=c) for c in categories ]
    )

rawDescription: How to specify multiple search fields with the same name in Google App Engine Search API

description: Specify multiple search fields with the same name in Google App Engine Search API


code:
def add():
    x.set(x.get() + 1)

def subtract():
    x.set(x.get() - 5)

def trace_var(*args):
    if x.get() < 5:
        subtractB.configure(state=DISABLED)
    else:
        subtractB.configure(state=NORMAL)

main = Tk()

addB = Button(main, text="Add", command=add)
addB.pack()
subtractB = Button(main, text="Subtract", command=subtract)
subtractB.pack()

x = IntVar()
x.trace('w', trace_var)
x.set(0)
Label(main, textvariable=x).pack()

main.mainloop()

rawDescription: How to configure Tkinter widgets if certain conditions are met?

description: Configure Tkinter widgets if certain conditions are met


code:
connector = aiohttp.ProxyConnector(proxies={'http': 'http://proxyaddr:8118'})
response = yield from aiohttp.request('get', 'http://python.org/', connector=connector)

rawDescription: How do you utilize proxy support with the python aiohttp framework

description: Utilize proxy support with the python aiohttp framework


code:
import time, Image

import cv2
from livestreamer import Livestreamer

# change to a stream that is actually online
livestreamer = Livestreamer()
plugin = livestreamer.resolve_url("http://twitch.tv/flosd")
streams = plugin.get_streams()
stream = streams['mobile_High']

# download enough data to make sure the first frame is there
fd = stream.open()
data = ''
while len(data) < 3e5:
    data += fd.read()
    time.sleep(0.1)
fd.close()

fname = 'stream.bin'
open(fname, 'wb').write(data)
capture = cv2.VideoCapture(fname)
imgdata = capture.read()[1]
imgdata = imgdata[...,::-1] # BGR -> RGB
img = Image.fromarray(imgdata)
img.save('frame.png')
# img.show()

rawDescription: Downloading the first frame of a twitch.tv stream


code:
from urlparse import urlparse
url = "http://stackoverflow.com/questions/26351727/python-html-parsing-getting-site-top-level-hosts"
urlparse(url).netloc

rawDescription: Python HTML parsing: getting site top level hosts


code:
all_processes = [Process(...) for i in xrange(10)]
for p in all_processes:
  p.start()

for p in all_processes:
  p.join()

rawDescription: Wait for all python processes to finish

description: Wait for all python processes to finish


code:
class SomeModel(models.Model):
    user_id = models.IntegerField(max_length=10)

rawDescription: Django: Mock a field on a model

description: Django: Mock a field on a model


code:
from BeautifulSoup import BeautifulSoup
from os.path import basename, splitext
soup = BeautifulSoup(my_html_string)
for img in soup.findAll('img'):
    img['src'] = 'cid:' + splitext(basename(img['src']))[0]
my_html_string = str(soup)

rawDescription: Replace SRC of all IMG elements using Parser


code:
from scipy.stats import truncnorm

def my_norm(start, end, mean=0, sdev=1, size=None):
    a = (start - mean)/sdev
    b = (end - mean)/sdev
    rv = truncnorm(a, b)
    return rv.rvs(size)*sdev + mean

rawDescription: Random Distribution to fit an Average Python


code:
plt.gca().set_xticklabels(\
    ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']);

rawDescription: Change x-axis from 0-6 to Mon-Sun in matplotlib python


rawDescription: Make a "matrix" from Django query

description: Make a "matrix" from Django query


code:
import mmap, re

with open('somefile') as fin:
    mf = mmap.mmap(fin.fileno(), 0, access=mmap.ACCESS_READ)
    words = re.findall('\w{4,}', mf)

rawDescription: extract words of length >= 4 from 100k words

description: Extract words of length >= 4 from 100k words


code:
def handler(req):
    pkg_resources.require('Trac==%s' % VERSION)
    gateway = ModPythonGateway(req, req.get_options())

    from trac.web.main import dispatch_request
    import cProfile
    from datetime import datetime

    def profile_request(*args, **kwargs):
        p = cProfile.Profile()
        p.runcall(dispatch_request, *args, **kwargs)
        # log to a file
        timestamp = datetime.now().strftime('%Y-%m-%d_%H%M%S.%f')
        p.dump_stats('/var/log/trac_profile/%s' % timestamp)

    gateway.run(profile_request)
    return apache.OK

rawDescription: Performance Analysis of mod_python Trac instance


code:
import astropy.io.fits as fits
target_url = 'https://s3.amazonaws.com/bdnyc/spex_prism_U50171_0835%2B19_chiu06.fits'
dat = fits.open(target_url)
dat

rawDescription: How do I open a FITS file from a URL in astropy?

description: Open a FITS file from a URL in astropy


code:
import BaseHTTPServer
import SimpleHTTPServer

from CGIHTTPServer import CGIHTTPRequestHandler
from cStringIO import StringIO

class BufferedCGIHTTPRequestHandler(CGIHTTPRequestHandler):
    def setup(self):
        """
        Arrange for CGI response to be buffered in a StringIO rather than
        sent directly to the client.
        """
        CGIHTTPRequestHandler.setup(self)
        self.original_wfile = self.wfile
        self.wfile = StringIO()
        # prevent use of os.dup(self.wfile...) forces use of subprocess instead
        self.have_fork = False

    def run_cgi(self):
        """
        Post-process CGI script response before sending to client.
        Override HTTP status line with value of "Status:" header, if set.
        """
        CGIHTTPRequestHandler.run_cgi(self)
        self.wfile.seek(0)
        headers = []
        for line in self.wfile:
            headers.append(line)    # includes new line character
            if line.strip() == '':  # blank line signals end of headers
                body = self.wfile.read()
                break
            elif line.startswith('Status:'):
                # Use status header to override premature HTTP status line.
                # Header format is: "Status: code message"
                status = line.split(':')[1].strip()
                headers[0] = '%s %s' % (self.protocol_version, status)

        self.original_wfile.write(''.join(headers))
        self.original_wfile.write(body)

def test(HandlerClass = BufferedCGIHTTPRequestHandler,
         ServerClass = BaseHTTPServer.HTTPServer):
    SimpleHTTPServer.test(HandlerClass, ServerClass)

if __name__ == '__main__':
    test()

rawDescription: How to send response headers and status from CGI scripts

description: Send response headers and status from CGI scripts


code:
import re
with open(fileName,"r") as f:
   nums = re.findall("[0-9]+", f.read())
   sum(map(int,nums))

rawDescription: How add together all numbers from a file separated by a non digit


code:
from xml.etree import ElementTree
# you need a valid xml string
data = '<root>' + data + '</root>'
etree = ElementTree.fromstring(data)
if etree.findtext('abd') == 'zombiesattack':
    titleOfVideo = etree.findtext('title')

rawDescription: How to return a substring after it occurs after another string?

description: Return a substring after it occurs after another string


rawDescription: Recursive delete in google app engine

description: Recursive delete in google app engine


code:
import subprocess
params = ['convert', 'pdf_file', 'jpg:-']
image_data = subprocess.check_output(params)

rawDescription: Capture jpgs produced in subprocess in main script


code:
if len(cells) > 1:
    a = cells[1].find('a')
    href = a['href']

rawDescription: Finding field with BeautifulSoup

description: Finding field with BeautifulSoup


code:
from flask.ext.admin.contrib.sqla import ModelView

from my_app import app, db
from models import MyModel

class MyModelView(ModelView):
    ...

    def on_model_change(self, form, model, is_created):
        # Custom code to call URL
        # Custom code to save to DB
        ...

admin = Admin(app)
admin.add_view(MyModelViewView(MyModel, db.session))

rawDescription: How change button logic on Flask Admin?

description: How change button logic on Flask Admin


rawDescription: How to nicely handle [:-0] slicing?

description: Nicely handle [:-0] slicing


code: " ".join(["".join(item) for item in zip(randint[:6], randstr[:6])])

rawDescription: List with tuples inside to string in Python3


rawDescription: mutiple bars in python

description: Mutiple bars in python


rawDescription: How do I change directory back to my original working directory with Python?

description: Change directory back to my original working directory with Python


code:
from tkinter import *

class Prac:

    def autoAddWidget(self):
        self.entryField = Entry(self.frame,text="Entry Field")
        self.entryField.grid(row=self.x, column=0)
        self.x+=1

    def __init__(self, master):
        self.frame = Frame(master, width=60, height=50)
        self.frame.pack()

        self.x=1
        self.addWidgetButton = Button(self.frame, text="Add new widget", command=self.autoAddWidget)
        self.addWidgetButton.grid(row=0, column=0)

root = Tk()
app = Prac(root)
root.mainloop()

rawDescription: Python - Auto add widgets

description: Python - Auto add widgets


code:
enemies[:] = []
shots[:] = []

rawDescription: Python/Pygame: All Instances Still On Screen After Restart


code:
yield whatever
x = yield whatever

rawDescription: yield - statement or expression?

description: Yield - statement or expression


code:
import subprocess
subprocess.call(["C:\Program Files\Oracle\VirtualBox\VBoxManage.exe", "startvm", "WIN7"])

rawDescription: Starting a VirtualBox VM from a Python Script


code:
br.select_form(predicate=self.__form_with_fields("user", "password"))
br.form.set_all_readonly(False)
br['user']           = self.config['COMMON.USER']
br['password']       = self.config['COMMON.PASSWORD']
br.form["shortsite"] = self.config['COMMON.SITE']

zone1 = br.form.find_control("zone")

#Add drop down list value dynamically like the Javascript does
mechanize.Item(zone1, {"contents": "Hurray","value": "Hurray"})

#Choose the just added option
br.form["zone"] = ["Hurray"]

rawDescription: Perl's HTML::Form::ForceValue equivalent in Python


code: matrix = [[0 for y in range(3)] for x in range(3)]

rawDescription: Most pythonic game board representation for Tic-Tac-Toe?


code:
with open(os.devnull, 'w') as tempf:
    proc = Popen(cmd, stdout=tempf, stderr=tempf)
    proc.communicate()

rawDescription: how to hide stdout of subprocess on windows

description: Hide stdout of subprocess on windows


rawDescription: Applying arange for simultaneous computation of multiple ranges


code:
import scrapy

class StockSpider(scrapy.Spider):
    name = "ugaz"
    allowed_domains = ["nasdaq.com"]
    start_urls = ["http://www.nasdaq.com/symbol/ugaz/"]

    # Indent this block
    def parse(self, response):
        stock = StockItem()
        stock['quote'] = response.xpath('//*[@id="qwidget_lastsale"]/text()').extract()
        stock['time'] = response.xpath('//*[@id="qwidget_markettime"]/text()').extract()
        return stock

rawDescription: Scrapy returning zero results

description: Scrapy returning zero results


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

fig,ax=plt.subplots(1,subplot_kw={'aspect':'equal'})

# A small 3x3 sample array
imarray=np.array([
    [[255,0,0],[0,255,0],[0,0,255]],
    [[255,255,0],[0,255,255],[255,0,255]],
    [[255,255,255],[127,127,127],[0,0,0]]
    ])

# Normalise the data to between 0 and 1
imarray = imarray.astype('float')/255.

# plot the array
ax.imshow(imarray,interpolation='nearest')

plt.show()

rawDescription: How to transform a list (or numpy array or matrix) into an image?

description: Transform a list (or numpy array or matrix) into an image


code:
for i in df.index:
    df.loc[i].to_json("row{}.json".format(i))

rawDescription: Pandas row to json

description: Pandas row to json


code:
#!/usr/bin/env python

import string

s=string.Template("""
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

        "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>My page</title>
</head>
<body>
<p>$text</p>
</body>
</html>
""")

s.substitute(text='Hello World')

rawDescription: How python can help me to make my website?


code: print("Here is a phrase: " + phrase.encode('some_codec'))

rawDescription: Where is the unicode?

description: Where is the unicode


code:
def serve_forever(self, poll_interval=0.5):
    """Handle one request at a time until shutdown.

    Polls for shutdown every poll_interval seconds. Ignores
    self.timeout. If you need to do periodic tasks, do them in
    another thread.
    """
    self.__is_shut_down.clear()
    try:
        while not self.__shutdown_request:
            r, w, e = _eintr_retry(select.select, [self], [], [],
                                   poll_interval)
            if self in r:
                self._handle_request_noblock()
    finally:
        self.__shutdown_request = False
        self.__is_shut_down.set()

rawDescription: Stopping socketserver.ThreadingMixIn in python


code:
url = (
    "https://graph.facebook.com/{album_id}/"
    "photos?access_token={access_token}"
).format(
    album_id=MY_ALBUM_ID,
    access_token=MY_ACCESS_TOKEN
)

rawDescription: uploading image to facebook page's album

description: Uploading image to facebook page's album


code:
dataStore = {}

# Method to process an input line
def processLine(dateStr, val):
  if dateStr not in dataStore:
    dataStore[dateStr] = val
  else:
    dataStore[dateStr] += val

# Method to read input file line by line
def doStuff(inFile, outFile):
  with open(inFile, 'r') as fp:
    for line in fp:
      dateStr, val = line.split()

      # cast decimal value to integer
      val = int(val)

      # process the date string to only keep the month and year
      dateStr = dateStr.split('/')
      dateStr = "/".join((dateStr[1], dateStr[2]))

      processLine(dateStr, val)

  # once you are done reading file, generate output
  writeBuf = []
  for key in dataStore:
    writeBuf.append((key, dataStore[key]))
  writeBuf.sort()

  with open(outFile, 'wb') as fp:
    for tup in writeBuf:
      line = '01/'+tup[0]+' - 30/'+tup[0] + '  ' + str(tup[1]) + '\n'
      fp.write(line)

if __name__ == '__main__':
  inFile = 'data.txt'
  outFile = 'result.txt'

  doStuff(inFile, outFile)

rawDescription: Arranging the data in a text file using python


code:
def get_override(area_type, region_type):
    for area in bpy.context.screen.areas:
        if area.type == area_type:
            for region in area.regions:
                if region.type == region_type:
                    override = {'area': area, 'region': region}
                    return override
    #error message if the area or region wasn't found
    raise RuntimeError("Wasn't able to find", region_type," in area ", area_type,
                    "\n Make sure it's open while executing script.")

#we need to override the context of our operator
override = get_override( 'VIEW_3D', 'WINDOW' )
#rotate about the X-axis by 45 degrees
bpy.ops.transform.rotate(override, value=6.283/8, axis=(1,0,0))

rawDescription: Rotating a model in Blender Python exporter


code:
import scipy, scipy.stats
x = scipy.linspace(0,10,11)
pmf = scipy.stats.binom.pmf(x,10,0.1)
import pylab
pylab.plot(x,pmf)

rawDescription: How to draw probabilistic distributions with numpy/matplotlib?

description: Draw probabilistic distributions with numpy/matplotlib


code:
series1 = pd.Series([10,20,30,40], index=[0,1,2,3])
series2 = pd.Series([2,3,4,5], index=[1,2,3,4])
series1 = series1.reindex(series1.index.union(series2.index), fill_value=0)
print(series1.div(series2))
# 0        nan
# 1   10.00000
# 2   10.00000
# 3   10.00000
# 4    0.00000
# dtype: float64

rawDescription: Pandas divide fill with multiple values

description: Pandas divide fill with multiple values


code:
y = polyroots([int(row["scaleA"]), int(row["scaleB"]), int(row["scaleC"]), int(row["scaleD"])-value])
for root in y:
   if "j" not in str(root):
       value = root

rawDescription: Ignore imaginary roots in sympy

description: Ignore imaginary roots in sympy


code:
sentence = "Hello world how are you doing today world?".lower()
searchword = input("Enter word:  ").lower()

newsentence = ''

for character in sentence:
    if character.islower() or character == ' ': newsentence += character

answer = [position for position, word in enumerate(newsentence.split()) if searchword == word]

print(answer)

rawDescription: Getting the position of an item in a list from an input (Python)


rawDescription: numpy.extract and numpy.any functions, is it possible to make it simpler way?

description: Numpy.extract and numpy.any functions, is it possible to make it simpler way


code:
jar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))

rawDescription: Python Post to form with anti-scrape protection


code:
from __future__ import print_function
import sys

def print_flush(*args):
    print(*args)
    sys.stdout.flush()

rawDescription: Delay/discrepancy between expected and actual output to iPython output


code:
sols = solve([t1 + t2 + t3, eq1, eq2], [t1, t2, t3])
sols[0][t1] # This is t1 in the first solution

rawDescription: sympy: how to save solution from "solve" for reuse?

description: Sympy: how to save solution from "solve" for reuse


code:
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class MySpider(CrawlSpider):
    name = 'example.com'
    allowed_domains = ['example.com']
    start_urls = ['http://www.example.com']

    rules = (
        Rule(LinkExtractor(), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        filename = response.url.split("/")[-2] + '.html'
        with open(filename, 'wb') as f:
            f.write(response.body)

rawDescription: Get scrapy spider to crawl entire site

description: Get scrapy spider to crawl entire site


code:
df = pd.concat([df1, df2, df3])
criteria = df.D.isin((df.groupby('D').count() == 3).index)
df[criteria].groupby('D')[['G', 'K']].sum()

rawDescription: How to sum columns from three different dataframes with a common key

description: Sum columns from three different dataframes with a common key


code:
# for the Hash package
if sys.platfrom == 'cli':
    from IronPyCrypto import MD2, MD4, SHA256

rawDescription: How to create a package in c# for use in IronPython

description: Create a package in c# for use in IronPython


code:
from wand.image import Image
from wand.drawing import Drawing

with Image(filename='wizard:') as img:
    with Drawing() as context:
        context.font_family = 'monospace'
        context.font_size = 25
        metrics = context.get_font_metrics(img,
                                           "How BIG am I?",
                                           multiline=False)
        print(metrics)

#=> FontMetrics(character_width=25.0,
#               character_height=25.0,
#               ascender=23.0,
#               descender=-5.0,
#               text_width=170.0,
#               text_height=29.0,
#               maximum_horizontal_advance=50.0,
#               x1=0.0,
#               y1=0.0,
#               x2=19.21875,
#               y2=18.0,
#               x=170.0,
#               y=0.0)

rawDescription: Render text string to image to calculate length with Wand/ImagaMagick Python


code:
from django.template.defaultfilters import truncatechars_html

html = """
Look, I’m some HTML. You can truncate me
       with Django template filters
"""
truncated_value = truncatechars_html(html, 30)

rawDescription: "Read More" for Django WYSIWYG editor

description: "Read More" for Django WYSIWYG editor


rawDescription: How to remove trailer of the packet in python using scapy

description: Remove trailer of the packet in python using scapy


code:
from sqlalchemy import event
@event.listens_for(Person.home_addresses, 'append')
def receive_append(target, value, initiator):
    # set the address type to home
    value.type = 'home'
    return value

rawDescription: Automatically setting properties in SQLAlchemy declarative models


code:
import urllib.request
import urllib.parse
params = urllib.parse.urlencode({'Lang': 'en', 'login': 'blafoo', 'passwd': 'foobla'})
f = urllib.request.urlopen("http://x.x.x.x/index.cst?%s" % params)
f.read()

rawDescription: handle .cst file with python urllib/httplib

description: Handle .cst file with python urllib/httplib


code:
def update(ip_dict, ip_address, site_path, user_agent):
    if ip_address in ip_dict:
        ip_entry = ip_dict[ip_address]

        ip_entry['total_count'] += 1

        if site_path in ip_entry['site_paths']:
            ip_entry['site_paths'][site_path] += 1
        else:
            ip_entry['site_paths'][site_path] = 0

        if user_agent in ip_entry['user_agents']:
            ip_entry['user_agents'][user_agent] += 1
        else:
            ip_entry['user_agents'][user_agent] = 0
    else:
        ip_dict[ip_address] = {
            'total_count': 1,
            'site_paths': {site_path: 1},
            'user_agent': {user_agent: 1}
        }

# initialize the ip dict
ip_dict = {}

# read from your log file and for every entry, call
update(ip_dict, '1.2.3.4', site_path, user_agent)

rawDescription: How to access and modify complex list/dictionary data structure in Python?

description: Access and modify complex list/dictionary data structure in Python


code:
FROM = "my-username"
TO = ["recipients"]
SUBJECT = "Stereo log: %s" % today
fp = open(textfile, 'rb')
TEXT = MIMEText(fp.read())
fp.close()
TEXT['From'] = FROM
TEXT['To'] = ",".join(TO)
TEXT['Subject'] = SUBJECT
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('my-username','mypass')
server.sendmail(FROM, TO, TEXT.as_string)
server.close()

rawDescription: MIME Header in message when sending e-mail with Python


code:
# img is a 2D ndarray
# K is the size of sums to calculate using sliding window
row_sums = numpy.zeros_like(img)
for i in range( img.shape[0] ):
    if i > K:
        row_sums[i,:] = row_sums[i-1,:] - img[i-K-1,:] + img[i,:]
    elif i > 1:
        row_sums[i,:] = row_sums[i-1,:] + img[i,:]
    else: # i == 0
        row_sums[i,:] = img[i,:]

col_sums = numpy.zeros_like(img)
for j in range( img.shape[1] ):
    if j > K:
        col_sums[:,j] = col_sums[:,j-1] - row_sums[:,j-K-1] + row_sums[:,j]
    elif j > 1:
        col_sums[:,j] = col_sums[:,j-1] + row_sums[:,j]
    else: # j == 0
        col_sums[:,j] = row_sums[:,j]

# here col_sums[i,j] should be equal to numpy.sum(img[i-K:i, j-K:j]) if i >=K and j >= K
# first K rows and columns in col_sums contain partial sums and can be ignored

rawDescription: Efficient processing of pixel + neighborhood in numpy image


code:
for f in iter(md5.stdout.readline, ''):
    fc = f.rstrip("\n")
    sys.stdout.write("\rChecked " + fc)
    sys.stdout.flush()

rawDescription: python subprocess read stdout as it executes

description: Python subprocess read stdout as it executes


code: plt.yticks([1], ["A very long label\nbroken into 2 line"],linespacing=0.5)

rawDescription: Changing tick label line spacing in matplotlib


code:
def combine(a, b):
    alist = []
    if a == [] and b == []:
       return alist
    if a != [] and b == []:
       return alist + a
    if a == [] and b != []:
       return alist + b
    if a != [] and b != []:
       if a[0] <= b[0]:
          alist.append(a[0])
          alist = alist +  combine(a[1:], b)
       if a[0] > b[0]:
          alist.append(b[0])
          alist = alist +  combine(a, b[1:])
    return alist

rawDescription: How to define a recursive function to merge two sorted lists and return a new list with a increasing order in Python?

description: Define a recursive function to merge two sorted lists and return a new list with a increasing order in Python


code:
tag = False
f = open("mix.txt")
for line in f:
    if tag:
        nums = line.split()
        if int(nums[1]) > 13255:
            print("greater")
        else:
            print("lesser")
        break
    if '#comment' in line:
        tag = True

rawDescription: how to takeout and check the value of a number in a mixed(text+number) txt file using python

description: Takeout and check the value of a number in a mixed(text+number) txt file using python


code:
class Courses_list(models.Model):
    Abbreviation = models.CharField(max_length=100, unique=True)
    Course = models.CharField(max_length=100, unique=True)

    def save(self, force_insert=False, force_update=False):
        self.Abbreviation = self.Abbreviation.upper()
        super(Courses_list, self).save(force_insert, force_update)

    def __unicode__(self):
        return self.Abbreviation

    class Meta:
        verbose_name = 'Course'
        verbose_name_plural = 'Courses'

class Job_Posting(models.Model):
    Job_Position = models.CharField(max_length=30, null=True, unique=True)
    educational_requirement = models.ManyToManyField(Courses_list)

    def __unicode__(self):
        return self.Job_Position

    class Meta:
        verbose_name = 'Job Position'
        verbose_name_plural = 'Job Positions'

rawDescription: Django: modelchoicefield with multiple modelfields


code:
from pandas.compat import range, lrange, lmap, map, zip
from pandas.tools.plotting import _get_standard_colors
import pandas.core.common as com

def andrews_curves(data, class_column, ax=None, samples=200, colormap=None,
                   **kwds):
    """
    Parameters:
    -----------
    data : DataFrame
        Data to be plotted, preferably normalized to (0.0, 1.0)
    class_column : Name of the column containing class names
    ax : matplotlib axes object, default None
    samples : Number of points to plot in each curve
    colormap : str or matplotlib colormap object, default None
        Colormap to select colors from. If string, load colormap with that name
        from matplotlib.
    kwds : Optional plotting arguments to be passed to matplotlib

    Returns:
    --------
    ax: Matplotlib axis object

    """
    from math import sqrt, pi, sin, cos
    import matplotlib.pyplot as plt

    def function(amplitudes):
        def f(x):
            x1 = amplitudes[0]
            result = x1 / sqrt(2.0)
            harmonic = 1.0
            for x_even, x_odd in zip(amplitudes[1::2], amplitudes[2::2]):
                result += (x_even * sin(harmonic * x) +
                           x_odd * cos(harmonic * x))
                harmonic += 1.0
            if len(amplitudes) % 2 != 0:
                result += amplitudes[-1] * sin(harmonic * x)
            return result
        return f

    n = len(data)
    class_col = data[class_column]
    uniq_class = class_col.drop_duplicates()
    columns = [data[col] for col in data.columns if (col != class_column)]
    x = [-pi + 2.0 * pi * (t / float(samples)) for t in range(samples)]
    used_legends = set([])

    colors = _get_standard_colors(num_colors=len(uniq_class), colormap=colormap,
                                  color_type='random', color=kwds.get('color'))
    col_dict = dict([(klass, col) for klass, col in zip(uniq_class, colors)])
    if ax is None:
        ax = plt.gca(xlim=(-pi, pi))
    for i in range(n):
        row = [columns[c][i] for c in range(len(columns))]
        f = function(row)
        y = [f(t) for t in x]
        label = None
        if com.pprint_thing(class_col[i]) not in used_legends:
            label = com.pprint_thing(class_col[i])
            used_legends.add(label)
            ax.plot(x, y, color=col_dict[class_col[i]], label=label, **kwds)
        else:
            ax.plot(x, y, color=col_dict[class_col[i]], **kwds)

    ax.legend(loc='upper right')
    ax.grid()
    return ax

rawDescription: Colors in Andrews Curves

description: Colors in Andrews Curves


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

def drawSphere(xCenter, yCenter, zCenter, r):
    #draw sphere
    u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
    x=np.cos(u)*np.sin(v)
    y=np.sin(u)*np.sin(v)
    z=np.cos(v)
    # shift and scale sphere
    x = r*x + xCenter
    y = r*y + yCenter
    z = r*z + zCenter
    return (x,y,z)

x = 10*np.random.rand(20)
y = 10*np.random.rand(20)
z = 10*np.random.rand(20)
r = np.random.rand(20)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# draw a sphere for each data point
for (xi,yi,zi,ri) in zip(x,y,z,r):
    (xs,ys,zs) = drawSphere(xi,yi,zi,ri)
    ax.plot_wireframe(xs, ys, zs, color="r")

plt.show()

rawDescription: Scatter Plot 3D with labels and spheres

description: Scatter Plot 3D with labels and spheres


code:
from datetime import datetime, timedelta

def getLastCommitURL():
    encrypted = 'mypassword'
    g = Github('myusername', naiveDecrypt(encrypted))
    org = g.get_organization('mycompany')
    code = org.get_repo('therepo')
    # limit to commits in past 24 hours
    since = datetime.now() - timedelta(days=1)
    commits = code.get_commits(since=since)
    last = commits[0]
    return last.html_url

rawDescription: Get Latest Commit URL from PyGithub Efficiently


code:
[ x for x in adict.keys() ]
[ adict[x] for x in adict.keys() ]
[ adict[x]['avalue'] for x in adict.keys() ]
sum([ adict[x]['avalue'] for x in adict.keys() ])

rawDescription: using functions on values of common key names

description: Using functions on values of common key names


code:
from scipy.optimize import fsolve
func = lambda r : (1./2.)*((CF**2)/(r))+CT*r**(gamma)+bm/(2.*muo) - CM
# assign some numeric values to CF, CT, gamma, bm, muo, CM
sol = fsolve(func, 1)   # 1 is the initial guess for the solver

rawDescription: Sympy solve will not return an answer

description: Sympy solve will not return an answer


code:
import matplotlib
import matplotlib.pyplot as plt
from datetime import datetime

x_orig = ['2015-12-29 15:01:25', '2015-12-29 15:02:08', '2015-12-29 15:02:13', '2015-12-29 15:04:18']
x = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in x_orig]
y = ['7.1', '7.4', '9.4', '10.2']

xs = matplotlib.dates.date2num(x)
hfmt = matplotlib.dates.DateFormatter('%Y-%m-%d\n%H:%M:%S')

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.patch.set_facecolor('lightgrey')
ax.xaxis.set_major_formatter(hfmt)
ax.set_title('Titel des Reports')
ax.set_xlabel('datum')
ax.set_ylabel('2MTemperatur')
plt.setp(ax.get_xticklabels(), size=8)
ax.plot(xs, y, linewidth=2)
ax.scatter(xs, y)
plt.grid()
plt.show()

rawDescription: Matplotlib and Python: How to format datetime from given string?


rawDescription: Speeding up multinomial random sample in Python/NumPy


code:
def find_stripped(soup, what):
  found = soup.find(what)
  if found != None:
    return found.text.strip()
  # maybe:
  # return ""

rawDescription: Elegant way to safely .text.strip() in BeautifulSoup?


rawDescription: How to pass in multiple parameters to web.py's render

description: Pass in multiple parameters to web.py's render


code:
def hideEvent(self, event):
    self.hide()
    if ph.is_windows():
        self.hidden = True
        self.setWindowFlags(Qt.ToolTip)
def showEvent(self, event):
    if ph.is_windows() and self.hidden:
        self.setWindowFlags(Qt.Window)
        self.hidden = False
    self.show()

rawDescription: Hide window from taskbar

description: Hide window from taskbar


code:
from collections import defaultdict

combined = defaultdict(list)

for d in dicts:
    for key, value in d.items():
        combined[key].append(value)

rawDescription: Checking a series of dictionaries for a common key


code:
with open("score.txt", "r") as imp, open("score_report.txt", "w") as out:
    n, class_sum = 0, 0
    for lime in imp:
        items = line.split()
        if not len(items) % 2:
            raise ValueError('line has even number of items')
        it = iter(items)
        name = next(it)  # cannot fail because odd number of items
        wt_score = 0
        for wt in it:
            wt_score += wt * next(it)  # ditto
        out.write(name, wt_score)  # plus grade
        n += 1
        class_sum += score
    # out.write( <class summary>)

rawDescription: File IO - Calculate Grades

description: File IO - Calculate Grades


code:
bytes = f.read(self.chunksize)
if bytes:
    bytes = bytes.ljust(self.chunksize, '\0')

rawDescription: Python - What is the most efficient way to generate padding?


code:
students = [lloyd, alice, tyler]

def print_student(student):
    print("""
        Student's name: {name}
        Student's homework: {homework}
        Student's quizzes: {quizzes}
        Student's tests: {tests}
    """.format(**student)) # unpack the dictionary

for std in students:
    print_student(std)

rawDescription: Looping through a list that contains dicts and displaying it a certain way


code:
db = QSqlDatabase.addDatabase('QODBC')
#TODO: Add support for trusted connections.
#("Driver={SQLServer};Server=Your_Server_Name;Database=Your_Database_Name;Trusted_Connection=yes;")
db.setDatabaseName('DRIVER={SQL Server};SERVER=%s;DATABASE=%s;UID=%s;PWD=%s;'
                        % (hostname,
                           databasename,
                           username,
                           password))
db.open()

rawDescription: pyQT and MySQL or MSSQL Connectivity

description: PyQT and MySQL or MSSQL Connectivity


code:
data = p4obj.run('describe -S ' + str(changelist))[0]

files = []
i = 0
while data.has_key('depotFile'+str(i)):
    files.append((data['depotFile'+str(i)],data['rev'+str(i)],data['action'+str(i)]))
    i += 1
for f in files:
    name = f[0]
    oldRev = str(int(f[1]))
    oldFile = tempfile.mktemp()
    oldFilespec = '%s#%s' % (name, oldRev)
    p4.runinteractive('print -q %s > %s' %(oldFilespec, oldFile))
    editedFile = tempfile.mktemp()
    editedFilespec = '%s@=%s'%(name, changelist)
    p4.runinteractive('print -q %s > %s' %(editedFilespec, editedFile))
    DiffTwoFiles(oldFile, editedFile, label1=oldFilespec, label2=editedFilespec)

rawDescription: P4 Python - describe shelved file changes


code:
self.temp_pw = user.generate_password()
user.set_password(self.temp_pw)

rawDescription: Django non persistent model field

description: Django non persistent model field


code:
import os
import time

def getOldDirs(self, dirPath, olderThanDays):
    """
    return a list of all subfolders under dirPath older than olderThanDays
    """
    olderThanDays *= 86400 # convert days to seconds
    present = time.time()
    for root, dirs, files in os.walk(dirPath, topdown=False):
        for name in dirs:
            subDirPath = os.path.join(root, name)
            if (present - os.path.getmtime(subDirPath)) > olderThanDays:
                yield subDirPath

rawDescription: get all folders (os.walk) that are older than x days, delete

description: Get all folders (os.walk) that are older than x days, delete


rawDescription: How to force all "or"

description: Force all "or"


code:
def distance(p1, p2):
    total = 0
    for i, (a, b) in enumerate(zip(p1, p2)):
        delta = abs(b - a)
        if delta > dimension[i] - delta:
            delta = dimension[i] - delta
        total += delta ** 2
    return total ** 0.5

rawDescription: check euclidean distance across periodic boundaries

description: Check euclidean distance across periodic boundaries


code: out = [[coord + float(y) - float(x) for v in V] for x,y in zip(x_coord, y_coord)]

rawDescription: looping through list of lists

description: Looping through list of lists


code:
from itertools import combinations
lis = [1,2,3,4]

rawDescription: Python - get all permutation of a list w/o repetitions


code:
import os
import re

for _file in os.listdir('.'):
    if re.search('\d.*\.jpg$', _file):
        print(_file)

rawDescription: Delete files in python that contain a number anywhere in the file name


code:
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

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

rawDescription: How do I make a web server to make timed multiple choice tests?

description: Make a web server to make timed multiple choice tests


code: np.where((arrayA >= 5) & (arrayB >= 5), 'type1', 'type2')

rawDescription: Python: create category based on values in two arrays


code:
f = figure()

ax1 = f.add_axes([0.1,0.1,0.8,0.8], zorder=0)
ax1.patch.set_facecolor('green')

ax2 = f.add_axes([0.3,0.2,0.5,0.4], zorder=1)
ax2.patch.set_facecolor('gray')

ax2.plot([0,1], [0,3], color='red')

ax3 = f.add_axes([0.1,0.1,0.8,0.8], zorder=2)
ax3.patch.set_alpha(0)
ax3.plot([0,1], [0,1], color='blue')

rawDescription: Matplotlib: Overplot a line above another axes panel


rawDescription: Psycopg2 query returning Decimal('value')


code: query = session.query(Post).filter(~Post.tags.any(Tag.name.in_(['dont', 'want', 'these'])))

rawDescription: sqlalchemy, select using reverse-inclusive (not in) list of child column values

description: Sqlalchemy, select using reverse-inclusive (not in) list of child column values


code:
import re

l = ['iter1apple', 'iter2banana', 'iter3carrot', 'iter4apple', 'iter5orange', 'iter6banana', 'iter7mango']
duplicates = []
lnew = []
for item in l:
    match = re.match("^iter\d+(\w+)$", item)
    if match and not match.group(1) in duplicates:
        duplicates.append(match.group(1))
        lnew.append(item)

# lnew = ['iter1apple','iter2banana','iter3carrot','iter5orange','iter7mango']

rawDescription: Remove near-duplicate elements in Python list while preserving variables


rawDescription: Floating point precision variation in Python 2.7.5


code:
myTable = QtGui.QTableWidget()
myTable.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)

rawDescription: QTableWidget Force Single Item Selection


code: mahotas.imread('d:/normal.jpg', as_grey = True)

rawDescription: python mahotas.imread reads a 2d image as 3d

description: Python mahotas.imread reads a 2d image as 3d


code:
import csv
def makeFile(textSorted, newFile) :
    from collections import Counter
    with open(newFile, "w") as f:
        wr = csv.writer(f,delimiter=":")
        wr.writerows(Counter(textSorted).items())

rawDescription: How to save a dictionary to a file with key values one per line?

description: Save a dictionary to a file with key values one per line


code:
long_list = list(long_sentence)
for end, repstr in indices:
    long_list[end-len(repstr):end] = ['.'] * len(repstr)
new_sentence = ''.join(long_list)

rawDescription: What is an efficient way to erase substrings?


code:
L = [(i,x) for i,x in enumerate(bigL) if cond(x)]
indlist,L = zip(*L) # split up index and value lists
# ... modify L ...
for i,x in zip(indlist, L):
    L[i] = x

rawDescription: Manipulating a sublist in Python

description: Manipulating a sublist in Python


code:
r2 = np.ones_like(numel, dtype=float)
num_mask = (numel != 0)
den_mask = (denel != 0)
mask = num_mask & den_mask
r2[mask] = 1 - numel[mask]/denel[mask]
mask = ~den_mask & num_mask
r2[mask] = 0

rawDescription: Numpy method of returning values based on two different arrays


text:
My wife took me here on my birthday for breakfast and it was excellent.  It looked like the place fills up pretty quickly so the earlier you get here the better.

Do yourself a favor and get their Bloody Mary. It came with 2 pieces of their griddled bread with was amazing and it absolutely made the meal complete.  It was the best "toast" I've ever had.

Anyway, I can't wait to go back!

type: review

text: I have no idea why some people give bad reviews about this place. It goes to show you, you can please everyone. They are probably griping about something that their own fault... but they said we'll be seated when the girl comes back from seating someone else. So, everything was great and not like these bad reviewers. That goes to show you that  you have to try these things yourself because all these bad reviewers have some serious issues.

rawDescription: The loading issue for json file in python


code:
def all_paths(r, c):
    current = triangle[r][c]
    if r < len(triangle) - 1:
        below_paths = all_paths(r+1, c) + all_paths(r+1, c+1)
        return [[current] + path for path in below_paths]
    else:
        return [[current]]

rawDescription: Project Euler #18 - how to brute force all possible paths in tree-like structure using Python?


code:
import tkinter as tk
from tkinter import ttk

class dictionary(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.fields = []
        self.createWidgets()
        self.grid(column=0, sticky="NEWS")

    def createWidgets(self):
        self.add_field()
        self.add_lang = ttk.Button(self, text="add language", command=self.add_field)
        self.add_lang.bind("<Return>", self.add_field)
        self.add_lang.grid(row=len(self.fields), column=3, padx=4, pady=6, sticky="W")

    def add_field(self):
        self.fields.append({})
        n = len(self.fields)-1
        self.fields[n]['var'] = tk.StringVar(self)
        self.fields[n]['field'] = ttk.Entry(self, textvariable=self.fields[n]['var'])
        self.fields[n]['field'].grid(row=n, column=0, columnspan=2, padx=4, pady=6, sticky="NEWS")
        if n:
            self.add_lang.grid(row=n + 1, column=3, padx=4, pady=6, sticky="W")

if __name__ == '__main__':
    root = tk.Tk()
    app = dictionary(master=root)
    app.mainloop()

rawDescription: Python tkinter add new field by a button


code:
queryset = Thing.object.filter(**{'%s__startswith' % criteria: word})

if criteria_requires_distinct:
    queryset = queryset.distinct()

rawDescription: Dynamic object filter

description: Dynamic object filter


code:
try:
    main()
except KeyboardInterrupt:
    stop()

def stop():
    for t in threads:
        t.my_stop_function()
    # wait for threads to stop here...

class MyThread(threading.Thread):
    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self, *args, **kwargs)
        self.stop = False

    def my_stop_function(self):
        self.stop = True

    def run(self):
        while not self.stop:
            scrape()

rawDescription: Safely interrupt a program with threaded downloading


code:
#!/usr/bin/python3

def main():

    # read file

    all_rows = [[float(i) for i in line.split(',')] for line in open("Alpha.txt")]

    # table size

    rows_number = len(all_rows)
    cols_number = len(all_rows[0])

    print("size (rows x cols): {0}x{1}".format(rows_number,cols_number))
    print()

    # create columns (indexed by numbers)

    all_columns = []

    for col_index in range(cols_number):

        all_columns.append([])

        for row_index in range(rows_number):
            all_columns[col_index].append(all_rows[row_index][col_index])

    # print rows

    print("rows")

    for i,row in enumerate(all_rows):
        print(i+1, ":", " , ".join(str(num) for num in row))

    print()

    # print cols

    print("cols")

    for i, col in enumerate(all_columns):
        print(chr(ord('A')+i), ":", " , ".join(str(num) for num in col))

    print()

    # main loop

    end = False

    while not end:
        usrnput = input("Enter a row or column (or 'Q' for quit): ").upper()

        if usrnput in ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'):
            index = ord(usrnput)-ord('A')
            if index < cols_number:
                print("min", all_columns[index], "=", min(all_columns[index]))
        elif usrnput in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'):
            index = int(usrnput)-1
            if index < rows_number:
                print("min", all_rows[index], "=", min(all_rows[index]))
        elif usrnput in ('Q'):
            end = True

main()

rawDescription: Troubles interpreting steps to create program


code:
from matplotlib import pyplot as PLT
import numpy as NP
import StringIO
import PIL
from django.http import HttpResponse

def display_image(request) :
    # next 5 lines just create a matplotlib plot
    t = NP.arange(-1., 1., 100)
    s = NP.sin(NP.pi*x)
    fig = PLT.figure()
    ax1 = fig.add_subplot(111)
    ax1.plot(t, s, 'b.')

    buffer = StringIO.StringIO()
    canvas = PLT.get_current_fig_manager().canvas
    canvas.draw()
    pil_image = PIL.Image.fromstring('RGB', canvas.get_width_height(),
                 canvas.tostring_rgb())
    pil_image.save(buffer, 'PNG')
    PLT.close()
    # Django's HttpResponse reads the buffer and extracts the image
    return HttpResponse(buffer.getvalue(), mimetype='image/png')

rawDescription: Python save matplotlib figure on an PIL Image object


code:
import sys
sys.foo = 3

rawDescription: Understanding what sort of objects can be dictionary keys


code:
def read_files(files_df, parameters):
    idx = []
    for key in parameters.keys():
        if len(idx) == 0:
            idx = (files_df[key] == parameters[key])
        else:
            idx = idx & (files_df[key] == parameters[key])
    idx = idx & files_df['Notes'].isnull()
    files = files_df.loc[idx]

    return files

rawDescription: Locate data from parameter-string in dataframe


code:
parser.addoption ('--count', default=1, type='int', metavar='count', help='Run each test the specified number of times')

def pytest_generate_tests (metafunc):
    for i in range (metafunc.config.option.count):
        metafunc.addcall()

rawDescription: How can I repeat each test multiple times in a py.test run?

description: Repeat each test multiple times in a py.test run


code:
def __init__(self, *args, **kwargs):
   super(MyForm, self).__init__(*args, **kwargs)
   self.fields['year'].choices = self.get_years()

rawDescription: Cache problem with Django forms

description: Cache problem with Django forms


code:
while True:
    my_input = input("> ")
    if my_input == "Hesitate":
        hesitate()
        break
    elif my_input == "Walk":
        walk()
        break
    else:
        print("INVALID")

rawDescription: Text Game - if text input isnot "Var1" or "Var2" then - Python 3


code: AmpDataFrame['Sample'] = (AmpDataFrame['Sample'].str.split(' ').str[0].astype(float) * CurrentShunt_mVtoAmp).astype(str)

rawDescription: How do alter a pandas dataframe column with foreach?


code:
compiled = re.compile(combined_regex)
results = compiled.findall(your_string)

rawDescription: Python: How can I find all strings matching any of the multiple patterns given


code:
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_yticks([0,1,2])
ax1.set_yticklabels(['red','red', 'blue'], color='blue')
colors=['red','red','blue']
for color,tick in zip(colors,ax1.yaxis.get_major_ticks()):
    tick.label1.set_color(color) #set the color property

plt.show()

rawDescription: Different colors for each label on an axis of a matplotlib chart?


code:
from project.common.client import BaseClient

class ConcreteApp1Client(BaseClient):
  pass

rawDescription: Using Python Objects in Django Applications


code:
# for example
body='SMILE_LAUGH_SOMESTRING_WHTATEVER'
if len(something) >= 1 and any(s in body for s in ('SMILE', 'LAUGH', 'LOVE', 'CHEER')):
     print("i'm still happy")

rawDescription: if statement containing not in

description: If statement containing not in


code:
import MySQLdb
import os
import time
from stat import ST_MTIME

TIME_TO_SLEEP = 1          # to avoid CPU burning

mydb = MySQLdb.connect(host="IP_add", user="uname", passwd="pass", db="DB_name")
cursor = mydb.cursor()
last_date = 0
while True:                        # or what you want as stop condition
    time.sleep(TIME_TO_SLEEP)
    stat = os.stat(filename)
    if stat[ST_MTIME] > last_date: # check the last modification date
        last_date = stat[ST_MTIME] # if more recent, store the last date
        with open(filename) as f:   # open the file
            sql = f.read()         # put the content in the sql data base
            if sql:
                cursor.execute(sql)
                mydb.commit()

mydb.close()

rawDescription: Running a Python Script to read info. from a new .txt file being generated at a known location every 1 sec


code:
import argparse, numpy as np

class Store_as_array(argparse._StoreAction):
    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, np.array(values))
                                     # ^ conversion here.

parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('-foo', action=Store_as_array, type=int, nargs='+')
                                  # ^ specify as the action
args = parser.parse_args(['-foo', '1', '2'])

assert isinstance(args.foo, np.ndarray)

rawDescription: ArgumentParser for numpy array

description: ArgumentParser for numpy array


code:
from django.template.defaultfilters import date as defaultfilters_date, time as defaultfilters_time

# FORCE {{...|date}} to be equivalent to {{...|date:"DATE_FORMAT"}} so it localizes properly, ditto for time and TIME_FORMAT

@register.filter(name="date")
def date_localized(val, arg=None):
    return defaultfilters_date(val, arg or "DATE_FORMAT")

@register.filter(name="time")
def time_localized(val, arg=None):
    return defaultfilters_time(val, arg or "TIME_FORMAT")

rawDescription: Why does Django's time filter not pickup the TIME_FORMAT by default?


code:
import os
from subprocess import check_call

cmd = 'echo *' # some shell command that may have `*`
for dirname in filter(os.path.isdir, os.listdir(os.curdir)):
    check_call(cmd, shell=True, cwd=dirname)

rawDescription: subprocess a bash command with *

description: Subprocess a bash command with *


code:
def app(mylist):
    mylist = mylist + [4]
    return mylist

rawDescription: Modifying Local Within Function Changes Global Passed to Function in Python


rawDescription: Two different week numbers evaluated to same date


code:
from skimage import img_as_ubyte
img = img_as_ubyte(tf.warp(img,tform))

rawDescription: Skimage SimilarityTransform spoils image


code:
from flask import render_template, Markup
from app import app
from config import POSTS_PER_PAGE
from models import Announcement, VideoAnnouncement

@app.route('/')
@app.route('/index')
@app.route('/index/<int:page>')
def index(page = 1):
    loggedOut = True
    query = Announcement.query.order_by(Announcement.id.desc())
    announcements = query.paginate(page, POSTS_PER_PAGE, True)
    videoAnnounce = VideoAnnouncement.query.all()
    return render_template("index.html", announcements = announcements, videoAnnouncements = videoAnnounce , loggedOut = loggedOut)

rawDescription: Sorting A List In Descending Order Jinja


code:
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
fig = plt.figure()
ax = fig.add_subplot(111)
x = [10,24,23,23,3]
y = [12,2,3,4,2]
line = Line2D(x, y)
ax.add_line(line)
ax.set_xlim(min(x), max(x))
ax.set_ylim(min(y), max(y))
plt.show()

rawDescription: Use Line2D to plot line in python

description: Use Line2D to plot line in python


code:
from collections import Mapping, Sequence
from unittest import TestCase, main
from json import dumps

def round_floats(o):
    if isinstance(o, float):
        return round(o, 4)
    elif isinstance(o, basestring):
        return o
    elif isinstance(o, Sequence):
        return [round_floats(item) for item in o]
    elif isinstance(o, Mapping):
        return dict((key, round_floats(value)) for key, value in o.iteritems())
    else:
        return o

class TestFoo(TestCase):
    def test_it(self):
        for val, res in ((.00123456, '0.0012'),
                         (.00009, '0.0001'),
                         (0.99999, '1.0'),
                         ({'hello': 1.00001, 'world': [True, 1.00009]},
                          '{"world": [true, 1.0001], "hello": 1.0}')):
            untrusted = dumps(round_floats(val))
            self.assertEqual(untrusted, res)

if __name__ == '__main__':
    main()

rawDescription: Creating custom JSONEncoder

description: Creating custom JSONEncoder


code:
import matplotlib as mpl
import matplotlib.pyplot as plt
import os

mpl.rcParams['axes.labelsize'] = 10
mpl.rcParams['xtick.labelsize'] = 10
mpl.rcParams['ytick.labelsize'] = 10
mpl.rcParams['legend.fontsize'] = 10
mpl.rcParams['font.family'] = ['sans-serif']
mpl.rcParams['font.sans-serif'] = ['Arial']
mpl.rcParams['text.usetex'] = False
mpl.rcParams['svg.fonttype'] = 'none'

fig = plt.figure(figsize=(4,1))
for pos,ts in enumerate(range(8,16)):
    plt.text(pos,0.5,ts, fontsize=ts)
plt.plot([-1,pos+1],[0.5,0.5])
plt.gca().yaxis.set_visible(False)
plt.gca().xaxis.set_visible(False)

# save as svg and pdf
plt.title('svg')
fig.savefig('figure.svg',dpi=300, bbox_inches='tight',transparent=True)
plt.title('pdf')
fig.savefig('figure.pdf',dpi=300, bbox_inches='tight',transparent=True)

# use inkscape to convert svg to pdf
os.system("inkscape --export-area-page --export-dpi=300 " \
        "--export-pdf=figure2.pdf -f=figure.svg")

# concatenate pdfs for comparison and make png
os.system("pdfnup --nup 1x2 -o output.pdf figure.pdf figure2.pdf")
os.system("convert -density 300 output.pdf output.png")

rawDescription: Change of the fontsize when saving an svg from matplotlib


code:
#!/usr/bin/env python
import itertools
import subprocess
from multiprocessing.dummy import Pool # use threads

def run(combo):
    cmd = ["command", combo[0], combo[1]]
    return combo, subprocess.call(cmd)

def main():
    p = Pool(60) # 60 subprocesses at a time
    for combo, rc in p.imap_unordered(run, itertools.combinations(files, 2)):
        print("%s exited with %s" % (combo, rc))
    p.close()
    p.join()

if __name__ == "__main__":
    main()

rawDescription: Run x number of commands at a time

description: Run x number of commands at a time


code:
from Tkinter import *
##from sys import exit

class Timer:
    def __init__(self, master):
        self.master=master
        buttonstart = Button(master, text = "Start", fg = "blue", command = self.start)
        buttonstart.grid(row = 1, column = 0)

        buttonquit = Button(master, text = "Quit", fg = "blue", command=self.quitit)
        buttonquit.grid(row = 1, column = 2)

        self.timertext = DoubleVar()
        self.timertext.set(0)
        display = Label(master, textvariable = self.timertext)
        display.grid(row = 0, column = 0)
##        timertext.set(timertext)  ## Huh!!
        self.timeit=False

    def increment_timer(self):
        ctr=int(self.timertext.get())
        self.timertext.set(ctr+1)
        if self.timeit:
            self.master.after(500, self.increment_timer)

    def start(self):
        self.timeit=True
        self.increment_timer()

    def quitit(self):
        self.timeit=False

root = Tk()
app = Timer(root)
root.mainloop()

rawDescription: Interrupting Loops in a tkinter GUI via a button.


code:
import boto.s3.connection

AWS_S3_CALLING_FORMAT = boto.s3.connection.VHostCallingFormat()

rawDescription: Django and S3 - static URL won't change

description: Django and S3 - static URL won't change


code:
from itertools import tee
from types import GeneratorType

Tee = tee([], 1)[0].__class__

def memoized(f):
    cache={}
    def ret(*args):
        if args not in cache:
            cache[args]=f(*args)
        if isinstance(cache[args], (GeneratorType, Tee)):
            # the original can't be used any more,
            # so we need to change the cache as well
            cache[args], r = tee(cache[args])
            return r
        return cache[args]
    return ret

rawDescription: Can I memoize a Python generator?

description: Memoize a Python generator


rawDescription: getting a particular value in pandas data frame

description: Getting a particular value in pandas data frame


code:
class Article(models.Model):
    hits              = models.IntegerField(help_text = 'Visits count')
    answer_to_article = models.ForeignKey('self', blank = True, null = True)
    slug              = models.SlugField(unique = True, help_text = 'Address')
    meta_keywords     = models.CharField(max_length = 512)
    title             = models.CharField(max_length = 256)
    content           = models.TextField(verbose_name = 'Article contents', help_text = 'Article contents')
    similar_articles  = models.ManyToMany('self')

    def get_similar_articles_from_meta_and_relation(self, phrase, offset = 0, limit = 10):
        return self.similar_articles.filter(meta_keywords=phrase)[offset:limit]

    class Meta:
        db_table = 'article'

rawDescription: Django models - two tables filter

description: Django models - two tables filter


code:
from subprocess import check_call
def deauth(mac_roteur,mac_victime,essid):
    check_call(['sudo', 'aireplay-ng','-0', '0', '-b', mac_roteur, '-c',  mac_victime, '-e',  essid, '--ignore-negative-one','mon0'])

rawDescription: Invalid BSSID (AP MAC address)

description: Invalid BSSID (AP MAC address)


code: np.einsum('ij,ij->i', a_vec, b_vec)

rawDescription: Numpy and dot products of multiple vector pairs: how can it be done?


code:
class MyAdmin(admin.ModelAdmin):
    ...
    save_as = True

rawDescription: Django Admin Save and add another preselected fields


code:
import csv, re
from pyparsing import Empty, FollowedBy, Group, LineEnd, Literal, \
                      OneOrMore, Optional, Regex, SkipTo, Word
from pyparsing import alphanums, alphas, nums

def section(header, other):
    return Literal('-'+header+'-').suppress() + other

def tc(header, next_item):
    # <header> <number> - <name>
    begin = Literal(header).suppress()
    number = Word(nums)\
             .setResultsName('number')\
             .setParseAction(compress_whitespace)
    dash = Literal('-').suppress()
    name = SkipTo(Literal(next_item))\
           .setResultsName('name')\
           .setParseAction(compress_whitespace)
    return begin + number + dash + name

def compress_whitespace(s, loc, toks):
    return [re.sub(r'\s+', ' ', tok).strip() for tok in toks]

def parse(data):
    # should match anything that looks like a header
    header = Regex(re.compile(r'-[A-Z0-9]+-'))

    # -CITE- (ignore)
    citation = SkipTo('-EXPCITE-').suppress()
    cite_section = section('CITE', citation)

        # -EXPCITE- (parse)
    # grab title number, title name, chapter number, chapter name
    title = Group(tc('TITLE', 'CHAPTER'))\
            .setResultsName('title')
    chapter = Group(tc('CHAPTER', '-HEAD-'))\
              .setResultsName('chapter')
    expcite_section = section('EXPCITE', title + chapter)

    # -HEAD- (parse)
    # two possible forms of section number:
    # > Sec. 1. <head_text>
    # > CHAPTER 1 - <head_text>
    sec_number1 = Literal("Sec.").suppress() \
                  + Regex(r'\d+\w?.')\
                    .setResultsName('section')\
                    .setParseAction(lambda s, loc, toks: toks[0][:-1])
    sec_number2 = Literal("CHAPTER").suppress() \
                  + Word(nums)\
                    .setResultsName('section') \
                  + Literal("-")
    sec_number = sec_number1 | sec_number2
    head_text = SkipTo(header)\
                .setResultsName('head')\
                .setParseAction(compress_whitespace)
    head = sec_number + head_text
    head_section = section('HEAD', head)

    # -STATUTE- (parse)
    statute = SkipTo(header)\
              .setResultsName('statute')\
              .setParseAction(compress_whitespace)
    statute_section = section('STATUTE', statute)

    # -End- (ignore)
    end_section = SkipTo('-End-', include=True)

    # do parsing
    parser = OneOrMore(Group(cite_section \
                             + expcite_section \
                             + head_section \
                             + Optional(statute_section) \
                             + end_section))
    result = parser.parseString(data)

    return result

def write_to_csv(parsed_data, filename):
    with open(filename, 'w') as f:
        writer = csv.writer(f, lineterminator='\n')
        for item in parsed_data:
            if 'statute' not in item:
                continue
            row = [item['title']['number'],
                   item['title']['name'],
                   item['chapter']['number'],
                   item['chapter']['name'],
                   item['section'],
                   item['head'],
                   item['statute']]
            writer.writerow(row)

# your data is assumed to be in <source.txt>
with open('source.txt', 'r') as f:
    data = f.read()
result = parse(data)
write_to_csv(result, 'output.txt')

rawDescription: Extracting data from a text file and writing it to csv or flat file


rawDescription: Adding dots between every char. What is the most Pythonic way?


code:
import pymongo
c = pymongo.MongoClient()
c['admin'].command('serverStatus', workingSet=True)['workingSet']

rawDescription: MongoDB workingSet by pymongo

description: MongoDB workingSet by pymongo


code:
conditions=[1]*5 # initialize conditions as you wish
for line in input_file:
    for i,condition in enumerate(conditions):
        if condition:
            conditions[i]=My_Function(A_tuple[i],B_tuple[i])

rawDescription: How to rewrite the code more elegantly

description: Rewrite the code more elegantly


code:
sobelx = cv2.Sobel(smoothed,cv2.CV_64F,1,0,ksize=-1)
sobely = cv2.Sobel(smoothed,cv2.CV_64F,0,1,ksize=-1)

self.gradientmap = numpy.sqrt (sobelx ** 2 + sobely ** 2)
self.gradientmap[self.gradientmap> 255] = 255

rawDescription: Python: using function on 2 elements of different 2d numpy arrays


code:
import datetime
strdate = '14:45:35:233 08.05.2016'
dt = datetime.datetime.strptime(strdate, '%H:%M:%S:233 %d.%m.%Y')
dt.strftime('%Y-%m-%d')

rawDescription: Date and time with numbers in python?

description: Date and time with numbers in python


code:
#!/usr/local/cpython-3.3/bin/python

with open('numeric.data', 'r') as infile, open ('filteredNumeric.data', 'w') as outfile:

    list_ = [ float(line) for line in infile ]
    list_.sort()

    outfile.writelines('{}\n'.format(element) for element in list_)

rawDescription: sorting list of integers in data file

description: Sorting list of integers in data file


code:
class ListOfStrings(object):
    def __init__(self, *strings):
        self.strings = strings

    def _repr_html_(self):
        return ''.join( [
           "%s" % s
           for s in self.strings
           ])

display(ListOfStrings("hi", "hello", "hello there"))

rawDescription: IPython Notebook: how to display() multiple objects without newline


code:
import urllib

class AHandler(webapp2.RequestHandler):
  def get(self):
    name = 'Some name'
    redirect('b?%s' % urllib.urlencode({'name': name}))

class BHandler(webapp2.RequestHandler):
  def get(self):
    name = self.request.get('name')
    # do something with name

rawDescription: Python AppEngine, how to take parameters to another page


rawDescription: Django ORM Left Join With GROUP BY and SUM


code: soup.select("div#VideoID img")

rawDescription: Detecting Image Tag in html

description: Detecting Image Tag in html


code:
from mod_python import Cookie
ID = Cookie.get_cookie(req, 'ID')
if ID:
    ID.expires = time.time() + 60*120
    Cookie.add_cookie(req, ID)
    ID = ID.value
else:
    ID = None

rawDescription: set post data python apache

description: Set post data python apache


code:
import threading

namespace_lock = threading.Lock()
namespace = {}
counters = {}

def aquire_lock(value):
    with namespace_lock:
        if value in namespace:
            counters[value] += 1
        else:
            namespace[value] = threading.Lock()
            counters[value] = 1

    namespace[value].acquire()

def release_lock(value):
    with namespace_lock:
        if counters[value] == 1:
            del counters[value]
            lock = namespace.pop(value)
        else:
            counters[value] -= 1
            lock = namespace[value]

    lock.release()

# sample usage
def foo(bar):
    aquire_lock(bar)
    # Code block ALPHA (two threads with equivalent bar should not be in here)
    release_lock(bar)

rawDescription: value based thread lock

description: Value based thread lock


code:
import matplotlib.pyplot as plt
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot([1,2,3],[5,6,7],'gs-')
plt.subplots_adjust(top=0.99, right=0.99)
plt.show()

rawDescription: How to remove space only at the top of the plot - matplotlib

description: Remove space only at the top of the plot - matplotlib


code:
import shlex
testPopen = subprocess.Popen(shlex.split('bash -c "time {a}"'.format(a = app)),
    stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=False)
out,err = testPopen.communicate()
print(err)

rawDescription: processing output of time command in a python script

description: Processing output of time command in a python script


code:
probs_from_cdf = np.diff(stats.chi2.cdf(np.arange(nbins+1), 10))
probs_from_sf = np.diff(stats.chi2.sf(np.arange(nbins+1)[::-1], 10))[::-1]
probs_from_sf[:4]
probs_from_cdf[:4]
probs_from_cdf[-5:]
probs_from_sf[-5:]

rawDescription: Precision of cdf in scipy.stats

description: Precision of cdf in scipy.stats


rawDescription: How to allow all characters in a url in Django?

description: Allow all characters in a url in Django


code:
import importlib
mod = importlib.import_module('sys')
mod

rawDescription: String variable as import module specifier


rawDescription: What is a efficient way to order chunks of numpy array by one column?


code:
from random import randint

start_urls = ["http://www.modcloth.com/shop/bedding?sorting=loved"
              "&page={0}".format(randint(1,50))]

rawDescription: Scrapy random number in single start_url


code:
t=np.linspace(0, np.pi, num=x)
p=np.linspace(-np.pi,np.pi,num=x)
[T,P]=np.meshgrid(t,p)
F_c=0.0
F_s=0.0

for i in xrange(n):
    F_c+=F_c_F_s.F_c(theta[i],phi[i],T,P)
    F_s+=F_c_F_s.F_s(theta[i],phi[i],T,P)
mod_F=(np.log10((np.power(F_c,2)+np.power(F_s,2))))

rawDescription: Spherical polar surface plot in python

description: Spherical polar surface plot in python


code:
import datetime
time_string = "17:48:12,98"
t = datetime.datetime.strptime(time_string, "%H:%M:%S,%f")
seconds = 60 * t.minute * t.hour

print (seconds, t.microsecond)

rawDescription: how to convert timecode into seconds:fractions_of_a_second?

description: Convert timecode into seconds:fractions_of_a_second


code: empty_spots = cells.count(' ')

rawDescription: in python, using in, get specific elements

description: In python, using in, get specific elements


code:
import wave
CHUNK_SIZE=1024
wf = wave.open('filename.wav')
data = wf.readframes(CHUNK_SIZE)
while data != '':
    do_something(data)
    data = wf.readframes(CHUNK_SIZE)

rawDescription: How do I sample audio for real-time processing?

description: Sample audio for real-time processing


code:
def make_method(methname):
    def method(self, *args):
        err = -1
        y = None
        try:
            x = AnOutsideClass(self.arg)     # Creates a class instance of an imported class
            y = getattr(x, methname)(*args)  # Calls an instance method that returns another different class instance
        except MyException1:
            x.dosomething() # Needed to handle error
        except MyException2:
            err = 0
        finally:
            del x
        return y, err
    return method

class MyClass(object):
    def __init__(self):
        self.arg = 'foo'
    method1 = make_method('outsideclassmethod1')
    method2 = make_method('outsideclassmethod2')

rawDescription: In python 2.7, how can I wrap a class instance method or decorate it with a try/except block?


rawDescription: Using regular expressions to modify a string


code:
Username =forms.CharField(max_length=35,
                          required=True,
                          widget=forms.TextInput(attrs={'placeholder': 'Username'}))

rawDescription: Is there a way in Django to make it so that when a form with initial text is clicked the text disappears?


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

df = pd.DataFrame(np.random.random((10,10,)))

fig, axn = plt.subplots(2, 2, sharex=True, sharey=True)
cbar_ax = fig.add_axes([.91, .3, .03, .4])

for i, ax in enumerate(axn.flat):
    sns.heatmap(df, ax=ax,
                cbar=i == 0,
                vmin=0, vmax=1,
                cbar_ax=None if i else cbar_ax)

fig.tight_layout(rect=[0, 0, .9, 1])

rawDescription: One colorbar for seaborn heatmaps in subplot


code: h2 = QuotedString("==")

rawDescription: How to use pyparsing to parse and hash strings enclosed by special characters?

description: Use pyparsing to parse and hash strings enclosed by special characters


code:
def not_self_validator(value):
  #is checks for same address(pointer) whereas == will call the equality method
  if value._my_entity is value:
    logging.warn('attempted to set object to itself')
    raise ValueError('Unable to set an object to itself')

rawDescription: appengine python validator make use of self

description: Appengine python validator make use of self


code:
class test():
    _name = None
    def __init__(self, name):
        self._name = name

    def __unicode__(self):
        english_string = get_string()
        params = {}
        params = deepcopy(english_string)
        var = force_text(params['patch_text'][self._name])
        return unicode(var )

class patchTable(tables.Table):

    release_version = tables.Column(verbose_name=test('release_version'),orderable=False)
    patch_version = tables.Column(verbose_name=test('patch_version'),orderable=False)
    release_date = tables.Column(verbose_name=test('release_date'),orderable=False)
    upload_date = tables.Column(verbose_name=test('upload_date'),orderable=False)
    apply_status = tables.Column(verbose_name=test('status'),orderable=False)
    installation_date = tables.Column(verbose_name=test('installation_date'),orderable=False)
    class Meta:
        attrs = {"class": "paleblue", "id":"patch_details", "style":"cursor: pointer;"}
        orderable = False

rawDescription: How to localize django_tables2 column names?

description: Localize django_tables2 column names


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

def fmt(x, y):
    return 'x: {x:0.2f}\ny: {y:0.2f}'.format(x=x, y=y)

class FollowDotCursor(object):
    """Display the x,y location of the nearest data point.
    """
    def __init__(self, ax, x, y, tolerance=5, formatter=fmt, offsets=(-20, 20)):
        try:
            x = np.asarray(x, dtype='float')
        except (TypeError, ValueError):
            x = np.asarray(mdates.date2num(x), dtype='float')
        y = np.asarray(y, dtype='float')
        self._points = np.column_stack((x, y))
        self.offsets = offsets
        self.scale = x.ptp()
        self.scale = y.ptp() / self.scale if self.scale else 1
        self.tree = spatial.cKDTree(self.scaled(self._points))
        self.formatter = formatter
        self.tolerance = tolerance
        self.ax = ax
        self.fig = ax.figure
        self.ax.xaxis.set_label_position('top')
        self.dot = ax.scatter(
            [x.min()], [y.min()], s=130, color='green', alpha=0.7)
        self.annotation = self.setup_annotation()
        plt.connect('motion_notify_event', self)

    def scaled(self, points):
        points = np.asarray(points)
        return points * (self.scale, 1)

    def __call__(self, event):
        ax = self.ax
        # event.inaxes is always the current axis. If you use twinx, ax could be
        # a different axis.
        if event.inaxes == ax:
            x, y = event.xdata, event.ydata
        elif event.inaxes is None:
            return
        else:
            inv = ax.transData.inverted()
            x, y = inv.transform([(event.x, event.y)]).ravel()
        annotation = self.annotation
        x, y = self.snap(x, y)
        annotation.xy = x, y
        annotation.set_text(self.formatter(x, y))
        self.dot.set_offsets((x, y))
        bbox = ax.viewLim
        event.canvas.draw()

    def setup_annotation(self):
        """Draw and hide the annotation box."""
        annotation = self.ax.annotate(
            '', xy=(0, 0), ha = 'right',
            xytext = self.offsets, textcoords = 'offset points', va = 'bottom',
            bbox = dict(
                boxstyle='round,pad=0.5', fc='yellow', alpha=0.75),
            arrowprops = dict(
                arrowstyle='->', connectionstyle='arc3,rad=0'))
        return annotation

    def snap(self, x, y):
        """Return the value in self.tree closest to x, y."""
        dist, idx = self.tree.query(self.scaled((x, y)), k=1, p=1)
        try:
            return self._points[idx]
        except IndexError:
            # IndexError: index out of bounds
            return self._points[0]

x = np.random.normal(0,1.0,100)
y = np.random.normal(0,1.0,100)
fig, ax = plt.subplots()

cursor = FollowDotCursor(ax, x, y, formatter=fmt, tolerance=20)
scatter_plot = plt.scatter(x, y, facecolor="b", marker="o")

#update the colour
new_facecolors = ["r","g"]*50
scatter_plot.set_facecolors(new_facecolors)

plt.show()

rawDescription: Updating marker style in scatter plot with matplotlib


code:
import numpy as np

class Foo: pass

arr=np.empty(2,dtype=object)
arr[:]=[Foo(),Foo()]
print(arr)
# [<__main__.Foo instance at 0xb7827d0c>
#  <__main__.Foo instance at 0xb748b5ac>]

print(arr.dtype)
# object

rawDescription: Python 3 with NumPy and object references


code:
def pjax(template, pjax_block='pjax_content', **kwargs):
    if "X-PJAX" in flask.request.headers:
        app = flask.current_app
        app.update_template_context(kwargs)
        template = app.jinja_env.get_template(template)
        block = template.blocks[pjax_block]
        context = template.new_context(kwargs)
        return u''.join(block(context))
    else:
        return flask.render_template(template, **kwargs)

rawDescription: How to render only given block using Jinja2 with Flask and Pjax

description: Render only given block using Jinja2 with Flask and Pjax


code:
list=[4,29,36,45,70,95,100,111,115,140,150,151,152,153,169]
with open('output.txt', 'w') as outfile:
    with open('results.txt', 'r') as infile:
        for line in infile:
            iter = 0
            prev_position = 0
            position = list[iter]
            temp = []
            while position < len(line) and iter + 1 < len(list):
                iter += 1
                temp.append(line[prev_position:position])
                prev_position = position
                position = list[iter]
            temp.append(line[prev_position:])

            temp_str = ''.join(x + "|" for x in temp)
            temp_str = temp_str[:-1]

            outfile.write(temp_str)

rawDescription: add delimiter to fixed-width text file

description: Add delimiter to fixed-width text file


code: self.users.update({"user_id": event['userid']}, {'$addToSet': {'campaigns': UserCampaigns[i]}})

rawDescription: Push an element to an array if it is not present (no duplicates)


code:
if any(add[0] != elem[0] for elem in list1):
    list1.append(add)

rawDescription: Python: compare first element of lists effectively


code:
...
form = UserCreationForm(request.POST)
if form.is_valid():
   user = form.save()
...

rawDescription: How to use django UserCreationForm correctly

description: Use django UserCreationForm correctly


code:
cur = g.db.execute(''''
    SELECT * from Recipe_tbl
    ORDER BY some_column DESC
    LIMIT 30
    ''')

rawDescription: Reverse database records flask

description: Reverse database records flask


code:
import urllib2, socket, urlparse

# set up your request as before, then:
data = urllib2.urlopen(request)
addr = socket.gethostbyname(urlparse.urlparse(data.geturl()).hostname)

rawDescription: How to determine the IP address of the server after connecting with urllib2?

description: Determine the IP address of the server after connecting with urllib2


code:
#!/usr/bin/python

import os, sys

from time import sleep

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

app = QApplication( sys.argv )

def copyFile() :
    cpBtn.setDisabled( True )
    for i in range( 0, 100 ) :
        # File Copy Code
        # sleep( 0.1 ) is instead of the file copy code
        sleep( 0.1 )
        pb.setValue( i + 1 )
        qApp.processEvents()

    cpBtn.setEnabled( True )
    pb.reset()

fcpDlg = QDialog()

cpBtn = QPushButton( fcpDlg )
cpBtn.setText( "&Copy" )
cpBtn.clicked.connect( copyFile )
cpBtn.setFixedWidth( 72 )

pb = QProgressBar()
pb.setMinimumWidth( 300 )
pb.setRange( 0, 100 )

lyt = QVBoxLayout( fcpDlg )
lyt.addWidget( pb )
lyt.addWidget( cpBtn )

fcpDlg.setLayout( lyt )

fcpDlg.show()

sys.exit( app.exec_() )

rawDescription: How do you connect a QProgressBar with a function?

description: Connect a QProgressBar with a function


code:
class Client():
    def __init__(self, form):
        self.Nome = form.nome.data
        self.Morada = form.morada.data
        self.Zona = form.zona.data
        self.Pais = form.pais.data

client = Client(form)

rawDescription: Automate large number of parameters in OOP


code:
entries = [entry for entry in request.GET]
Contact.objects.filter(lists__name__in=entries).distinct()

rawDescription: Remove duplicates

description: Remove duplicates


code:
def getSumOfLastDigits(numList):
  return sum(x % 10 for x in numList)

rawDescription: Python function to sum digits

description: Python function to sum digits


code:
# declare your app ids as globals ...
APPID_LIVE = 'awesomeapp'
APPID_DEV = 'awesomeapp-dev'
APPID_PILOT = 'awesomeapp-pilot'

# create a dictionary mapping the app_ids to the filepaths ...
client_secrets_map = {APPID_LIVE:'client_secrets_live.json',
                      APPID_DEV:'client_secrets_dev.json',
                      APPID_PILOT:'client_secrets_pilot.json'}

# get the filename based on the current app_id ...
client_secrets_filename = client_secrets_map.get(
    app_identity.get_application_id(),
    APPID_DEV # fall back to dev
    )

# use the filename to construct the flow ...
flow = flow_from_clientsecrets(filename=client_secrets_filename,
                               scope=scope,
                               redirect_uri=redirect_uri)

# or, you could load up the json file manually if you need more control ...
f = open(client_secrets_filename, 'r')
client_secrets = json.loads(f.read())
f.close()

rawDescription: Securely storing environment variables in GAE with app.yaml


code:
def after(s1, s2):
    index = s1.find(s2)
    # return None if s2 is not part of s1
    # or if there are no characters behind s2 in s1
    if index != -1 and index + len(s2) < len(s1):
        return s1[index + len(s2):]
    else:
        return None

s1 = "abcdefghijk"
s2 = "cdefghij"

print(after(s1, s2))

rawDescription: Python: compare two strings retain difference from one end


code:
for arr in mydict.values():
    for i, s in enumerate(arr):
        if s == 'example':
            arr[i] = 'someotherword'

rawDescription: Replacing multiple occurrences in nested arrays


code:
from glob import glob
import numpy as np

for path in glob(r"F:\Thermal Motion\*.txt"):
    t, x, y = np.loadtxt(path, unpack=True)
    use_the_arrays_here(x, y, t) # <--  use mathematical functions here

rawDescription: writing multiple text files into arrays python

description: Writing multiple text files into arrays python


code:
class LinkedList:
    def __init__(self):
        self._head = None
        self._tail = None
        self._size = 0

    def append(self, item):
        if self._tail is None:
            self.prepend(item)
        else:
            self._tail.next = Node(item, None)
            self._tail = self._tail.next

    def prepend(self, item):
        if self._head is None:
            self._tail = Node(item, None)
            self._head = self._tail
        else:
            self._head = Node(item, self._head)
        self._size += 1

rawDescription: Linked List and manipulation

description: Linked List and manipulation


rawDescription: program to extract every alternate letters from a string in python?

description: Program to extract every alternate letters from a string in python


code: b = a.replace('1', '@temp_replace@').replace('2', '1').replace('@temp_replace@', '2')

rawDescription: Replace string content with each others

description: Replace string content with each others


code:
df
df_transposed = df.transpose()
df_transposed

rawDescription: Pivot Pandas DataFrame switching Index and Column Names


rawDescription: python: parsing strings from serial.read()

description: Python: parsing strings from serial.read()


code:
from django.forms import ModelForm, Textarea

class PostModelForm(ModelForm):
    class Meta:
        model = Post
        widgets = {
            'content': Textarea(attrs={'cols': 80, 'rows': 20}),
        }

rawDescription: How can I get a textarea from model+ModelForm?

description: Get a textarea from model+ModelForm


code:
xml_tag = dom.getElementsByTagName('person')[0]
xml_data = [elem.nodeValue for elem in dom.getElementsByTagName('name')]

rawDescription: Python: get all content of specific XML tags


code:
min_position = numbers.index(min(numbers))
max_position = numbers.index(max(numbers))

del numbers[min_position]
del numbers[max_position]

rawDescription: How to exclude one min and one max number?

description: Exclude one min and one max number


rawDescription: How do I "force" pixel-registerd grid for plotting x,y,z,s on 3d surface?


code:
table_name = "TABLE 1"

table = soup.find(text=lambda x: x and table_name in x).find_parent('table')

rawDescription: extract table from html by position using Python

description: Extract table from html by position using Python


code: os.system("example.py arg")

rawDescription: Script to open another python file

description: Script to open another python file


rawDescription: beginners issue with using of lists in python

description: Beginners issue with using of lists in python


rawDescription: Is there a better way to find duplicate rows _including_ the first/last?


code: c.execute("SELECT id, message FROM tasks WHERE date <= NOW() AND done = 0;")

rawDescription: Problems with "commit" after SQL INSERT with Python and SQL


code:
import pkg_resources
my_data = pkg_resources.resource_string(__name__, "config.yml")

rawDescription: python open config file located inside the package

description: Python open config file located inside the package


code:
j = len(array) - 1
for i in range(len(array)):
    # diagonal from top left to bottom right
    count += array[i][i]
    # diagonal from bottom left to top right
    count += array[j][i]
    j -= 1

rawDescription: Python 3 Adding Diagonals in an Array

description: Python 3 Adding Diagonals in an Array


code:
def main():
    name = input("What would you like to name your character?")
    print("Your character has been created!")
    play = Player(name)
    choice = None
    while choice != "0":
        print(""" Character Menu
            0 - Quit
            1 - Character Information
            2 - Inventory
            3 - Add an item
            4 - Drop an item""")
        choice = input("What would you like to do?")
        #Exit
        if choice == "0":
            print("See you later!")
        #Character Information
        elif choice == "1":
            play.charInfo()
        #Inventory
        elif choice == "2":
            play.inventory()
        #Add an item
        elif choice == "3":
            add_item = input("What would you like to add to your inventory?")
            add_item = add_item.lower()
            play.take(add_item)
        #Drop an item
        elif choice == "4":
            drop_item = input("What item would you like to drop?")
            drop_item = drop_item.lower()
            play.drop(drop_item)

class Player():
    """A game player"""

    def __init__(self, name):
        self.__name = name
        self.__items = []
        self.__max_items = 7

    def __str__(self):
        return self.__name

    def charInfo(self):
        print("This is your character's name:", self.__name)

    def inventory(self):
        if len(self.__items) > 7:
            print ("Your iventory is:")
            print (self.__items)
        else:
            print("There's nothing in your inventory.")

    def take(self, add_item):
        if len(self.__items) <= self.__max_items:
            self.__items.append(add_item)
        else:
            print("You already have the max items in your inventory,sorry")

    def drop(self, drop_item):
        if drop_item not in self.__items:
            print("That item isn't in your inventory.")
        else:
            self.__items.remove(drop_item)

main()

input("\nPress enter to exit.")

rawDescription: OOP in python programming, I keep getting an error message about defining main()


code:
from meliae import scanner # [[source](http://www.vrplumber.com/programming/runsnakerun/)]
scanner.dump_all_objects( filename ) # you can pass a file-handle if you prefer

rawDescription: Finding Memory Usage, CPU utilization, Execution time for running a python script


code:
from scipy import interpolate
tck,u=interpolate.splprep([x,y],s=0.0)
x_i,y_i= interpolate.splev(np.linspace(0,1,100),tck)

rawDescription: scipy: Interpolating trajectory

description: Scipy: Interpolating trajectory


code:
from datetime import datetime, timedelta
x = datetime.now() + timedelta(seconds=3)
x += timedelta(seconds=3)

rawDescription: How to add seconds on a datetime value in Python?

description: Add seconds on a datetime value in Python


code:
template = Template(
            "{{ name }} ;"
            "{{ ' 'if age }}{{age if age }}{{' 'if age}};"
            "{{ ' ' if email}};{{ email if email}}{{ ' ' if email}};")

for item in mylist:
    people_tag =template.render(
                    name= item['name'],
                    age = item.get('age'),
                    email= item.get('email'))

rawDescription: concatenate string and number using jinja2 in python

description: Concatenate string and number using jinja2 in python


code:
df_big['group'] = [i // 10 for i in range(len(df_big))]  # Python 2 truncation.
df_big.groupby('group').mean()

rawDescription: Python: Alternative to looping through 60000 rows


code:
from sklearn.feature_extraction.text import CountVectorizer
corpus = ['I like my coffee with a shot of rum.']
vec = CountVectorizer()
vec.fit(corpus)
vec.vocabulary_
vec = CountVectorizer(token_pattern='(?u)\\b\\w+\\b')
vec.fit(corpus)
vec.vocabulary_

rawDescription: Unwanted removal of some stopwords in scikitlearn


code:
import tkinter as tk

def startgame():

    pass

mw = tk.Tk()

#If you have a large number of widgets, like it looks like you will for your
#game you can specify the attributes for all widgets simply like this.
mw.option_add("*Button.Background", "black")
mw.option_add("*Button.Foreground", "red")

mw.title('The game')
#You can set the geometry attribute to change the root windows size
mw.geometry("500x500") #You want the size of the app to be 500x500
mw.resizable(0, 0) #Don't allow resizing in the x or y direction

back = tk.Frame(master=mw,bg='black')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window

#Changed variables so you don't have these set to None from .pack()
go = tk.Button(master=back, text='Start Game', command=startgame)
go.pack()
close = tk.Button(master=back, text='Quit', command=mw.destroy)
close.pack()
info = tk.Label(master=back, text='Made by me!', bg='red', fg='black')
info.pack()

mw.mainloop()

rawDescription: How to set a tkinter window to a constant size

description: Set a tkinter window to a constant size


code:
# Converts a decimal number to hexadecimal.
# Executes a zero-fill for up to six digits.
# This is used for correct conversion back
# to the instruction format. See zero_fill().
# @param  dec  Decimal representation of instruction
# @return  Zero-filled hexadecimal instruction.
def convert(dec):
# BEGIN convert()
    hex = "%X" % dec
    return zero_fill(hex, 6)
# END convert()

# Prepends zeros until the specified
# length is reached. Works recursively.
# @param  n  Number to fill
# @param  length  Length to reach
# @return  Zero-filled number
def zero_fill(n, length):
# BEGIN zero_fill()
    # Check if length requirement is met
    if len(n) != length:
        # Requirement not met, run function again with
        # n having one prepended zero.
        return zero_fill('0'+n, length)
    else:
        # Requirement met, return n.
        return n
# END zero_fill()

rawDescription: python recursively convert decimal to hex

description: Python recursively convert decimal to hex


code:
items = 102
boxsize = 10
num_boxes = (items + boxsize - 1) // boxsize

rawDescription: How to perform ceiling-division in integer arithmetic?

description: Perform ceiling-division in integer arithmetic


code:
from itertools import chain
import csv

_header_translate = {
    'StartPoint': ('start1', 'start2', 'start3'),
    'EndPoint': ('end1', 'end2', 'end3')
}

def header(col):
    header = col.strip('{}').split('::', 1)[0]
    return _header_translate.get(header, (header,))

def cleancolumn(col):
    col = col.strip('{}').split('::', 1)[1]
    return col.split('[%2C]')

def chainedmap(func, row):
    return list(chain.from_iterable(map(func, row)))

with open('input.txt', 'rb') as fin, open('output.csv', 'wb') as fout:
    reader = csv.reader(fin)
    writer = csv.writer(fout)
    for i, row in enumerate(reader):
        if not i:  # first row, write header first
            writer.writerow(chainedmap(header, row))
        writer.writerow(chainedmap(cleancolumn, row))

rawDescription: parsing text file with JSON-like object into CSV

description: Parsing text file with JSON-like object into CSV


code:
import ast
ast.literal_eval('[1,2,3]')

rawDescription: Pythonic way of converting a list embedded in a string to a list


code:
import os
os.listdir("path") # returns list

rawDescription: How can I list the contents of a directory in Python?

description: List the contents of a directory in Python


code:
from django.db import models

class Base(models.Model):
    class Meta:
        abstract = True
        app_label = "someApp"

class Something(Base):
    # ...
    class Meta(Base.Meta):
        ordering = ('created',)

rawDescription: Correct syntax to inherit a models meta class?


code:
"""
this is a quick and dirty script to send HTML email - emphasis on dirty :)
python emailpage.py http://www.sente.cc
made to answer: http://stackoverflow.com/questions/9226719/sending-a-html-file-via-python
Stuart Powers
"""
import lxml.html
import smtplib
import sys
import os

page = sys.argv[1]  #the webpage to send

root = lxml.html.parse(page).getroot()
root.make_links_absolute()

content = lxml.html.tostring(root)

message = """From: Stuart Powers <stuart.powers@gmail.com>
To: Stuart Powers <stuart.powers@gmail.com>
MIME-Version: 1.0
Content-type: text/html
Subject: %s

%s""" %(page, content)

smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.starttls()
smtpserver.login("stuart.powers@gmail.com",os.environ["GPASS"])
smtpserver.sendmail('stuart.powers@gmail.com', ['stuart.powers@gmail.com'], message)

rawDescription: Sending a Html file via python

description: Sending a Html file via python


code: limit = reduce(operator.or_, (Q(**condition) for condition in model_list))

rawDescription: How to generate a combined Q object from a list?

description: Generate a combined Q object from a list


code:
import os
os.path.join('app', 'subdir', 'dir', 'filename.foo')

rawDescription: Platform-independent file paths?

description: Platform-independent file paths


code: X = np.array((4,1), dtype="float32")

rawDescription: How to keep Numpy array from converting floats to ints when building array?

description: Keep Numpy array from converting floats to ints when building array


code:
class HotelController(Controller):
    """ Controller to handle requests to Hotels """

    def index(self):
        """ Handle the index page here """
        pass

    def addNewHotel(self):
        """ Register a new hotel here """
        pass

    def lookup(self, state_name, *remainder):
        """ Read the state, create a new StateController and dispatch """
        state_dispatch = StateController(state_name)
        return state_dispatch, remainder

class StateController(object):
    """ Controller used to dispatch """

    def __init__(self, state_name):
        # do your work on the state here
        pass

    def create(self, state_name):
        """ Create a new state here """

    def lookup(self, city_name, *remainder):
        """ keep on dispatching to other controllers """
        city_dispatch = CityController(city_name)
        return city_dispatch, remainder

rawDescription: Dealing with dynamic urls

description: Dealing with dynamic urls


code:
#!/usr/bin/env python3

import matplotlib.pyplot as plt

# a 4x4 box (counterclockwise)
ext_x = [2, -2, -2, 2, 2]
ext_y = [2, 2, -2, -2, 2]

# a 2x2 hole in the box (clockwise)
int_x = [item/2.0 for item in ext_x][::-1]
int_y = [item/2.0 for item in ext_y][::-1]

# if you don't specify a color, you will see a seam
plt.fill(ext_x+int_x, ext_y+int_y, color='blue')

plt.show()

rawDescription: How to plot a complex polygon?

description: Plot a complex polygon


code:
from bokeh.plotting import figure
from bokeh.models import LinearAxis, Range1d, CustomJS
from bokeh.io import output_notebook, show
output_notebook()

jscode="""
        range.set('start', parseInt(%s));
        range.set('end', parseInt(%s));
    """

s1=figure(width=250, plot_height=250, title=None, tools="pan, wheel_zoom")
s1.line([1, 2, 3], [300, 300, 400], color="navy", alpha=0.5)
s1.extra_y_ranges = {"foo": Range1d(start=1, end=9)}
s1.add_layout(LinearAxis(y_range_name="foo"), 'right')
s1.line([1, 2, 3], [4, 4, 1], color="firebrick", alpha=0.5, y_range_name="foo")

s1.extra_y_ranges['foo'].callback = CustomJS(
        args=dict(range=s1.extra_y_ranges['foo']),
                    code=jscode % (s1.extra_y_ranges['foo'].start,
                                   s1.extra_y_ranges['foo'].end)
            )

show(s1)

rawDescription: bokeh, two y axis, disable one axis for zoom/ panning

description: Bokeh, two y axis, disable one axis for zoom/ panning


rawDescription: Printing a timeline, logistic issue

description: Printing a timeline, logistic issue


code:
from zope.interface import implementer
from twisted.internet.interfaces import IReadDescriptor

@implementer(IReadDescriptor)
class InputDescriptor(object):
    def __init__(self, reactor, inputDevice, eventReceiver):
        self._reactor = reactor
        self._dev = inputDevice
        self._receiver = eventReceiver

    def fileno(self):
        return self._dev.fileno()

    def logPrefix(self):
        return "Input Device: " + repr(self._dev)

    def doRead(self):
        evt = self._dev.read_one()
        try:
            self._receiver.eventReceived(evt)
        finally:
            pass

    def connectionLost(self, reason):
        self.stop()
        self._receiver.connectionLost(reason)

    def start(self):
        self._dev.grab()
        self._reactor.addReader(self)

    def stop(self):
        self._reactor.removeReader(self)
        self._dev.ungrab()

from evdev import InputDevice, categorize, ecodes, list_devices

devices = [InputDevice(fn) for fn in list_devices()]
for dev in devices:
   print(dev.fn, dev.name, dev.phys)

dev = InputDevice('/dev/input/event0')

class KeyReceiver(object):
    def eventReceived(self, event):
        if event.type == ecodes.EV_KEY:
            print(categorize(event))

    def connectionLost(self, reason):
        print("Event device lost!!", reason)

from twisted.internet import reactor
InputDescriptor(reactor, dev, KeyReceiver()).start()
reactor.run()

rawDescription: Integrating HID access with evdev on linux with Python twisted