code: form = MyForm ('Title A', 'Description A')

rawDescription: How do I add plain text info to forms in a formset in Django?

description: Add plain text info to forms in a formset in Django


code:
def f(self=f):
    return self.x

rawDescription: how can python function access its own attributes?

description: How can python function access its own attributes


code:
l= MyWords.upper().split()
l.remove(SpamWords[SpamCheckRange])
# l is ['YES']

rawDescription: Python String Method Conundrum

description: Python String Method Conundrum


code:
#!/usr/bin/python3

import warnings

def warning_on_one_line(message, category, filename, lineno, file=None, line=None):
    return '%s:%s: %s: %s\n' % (filename, lineno, category.__name__, message)

warnings.formatwarning = warning_on_one_line

warnings.warn('Run Forest run!', stacklevel=2)
warnings.warn('Run Forest run!')

rawDescription: Make Python's `warnings.warn()` not mention itself


code: all_dates = [thread['data'] for thread in data['threads'].values()]

rawDescription: How do I navigate through a dictionary like this?

description: Navigate through a dictionary like this


code:
from collections import Counter
[i for i,j in Counter(a).items() if j>1]

rawDescription: Testing whether a string has repeated characters


code:
equations = [sy.Eq(sy.symbols(variable), sy.sympify(expr))
             for variable, expr in formulas.items()]

rawDescription: How to evaluate an expression-tree in sympy?

description: Evaluate an expression-tree in sympy


rawDescription: Limiting the number of combinations /permutations in python


code:
@classmethod
def from_words(cls, words):
    wfd, wildfd = (FreqDist(),)*2
    bfd, tfd ,fofd = (FreqDist(),)*3

    for w1,w2,w3,w4,w5 in ingrams(words,5,pad_right=True):
      wfd.inc(w1)

      if w2 is None:
        continue
      bfd.inc((w1,w2))

      if w3 is None:
        continue
      wildfd.inc((w1,w3))
      tfd.inc((w1,w2,w3))

      if w4 is None:
        continue
      wildfd.inc((w1,w4))
      wildfd.inc((w2,w4))
      wildfd.inc((w3,w4))
      wildfd.inc((w1,w3))
      wildfd.inc((w2,w3))
      wildfd.inc((w1,w2))
      ffd.inc((w1,w2,w3,w4))

    return cls(wfd, bfd, wildfd, tfd, ffd)

rawDescription: How to get n-gram collocations and association in python nltk?

description: Get n-gram collocations and association in python nltk


code:
from mysite.core.views.create_update import update_object_as_child

@update_object_as_child(Animal)
def edit_animal(request, object_id):
  pass

rawDescription: In Django, how could one use Django's update_object generic view to edit forms of inherited models?


code:
import timeit
timeit.Timer("'A' in l", "l = list('AEIOU')").timeit(999999)
timeit.Timer("'A' in s", "s = set('AEIOU')").timeit(999999)
timeit.Timer("'A' in s", "s = 'AEIOU'").timeit(999999)

rawDescription: Why is string search fastest as compared to list search and set search?


rawDescription: Scraping data with BeautifulSoup issue

description: Scraping data with BeautifulSoup issue


code:
def get_names(fle):
    with open(fle,"a") as f:
        inp = input("Enter names separated by a space :")
        f.writelines(("{}\n".format(n) for n in inp.split()))

def read_names(fle):
    with open(fle) as f:
        for name in f:
            print(name)

rawDescription: Python 3.3 - Formatting Issue

description: Python 3.3 - Formatting Issue


code:
AtomicJobParams = namedtuple('AtomicJobParams', ['a', 'b', 'c', 'd'])

jobparams = AtomicJobParams(a, b, c, d)
_do_atomic_job(jobparams)                # Returns AtomicJobResult

rawDescription: Overriding an inner function of a method in python


code:
@app.route("/")
def view_data():
    # Removed from above and placed here
    # The connection is made to the database for each request
    conn = connect_to_mysql()
    # This is only executed on every request
    data = conn.execute("SELECT * FROM MySemiRegularlyUpdatedTable")
    return render_template("view_data.html", data=data)

rawDescription: Updating the webpage using Flask based on MySQL database.


code:
from mongoengine import connect

db = connect('test')
db.drop_database('test')

rawDescription: Dropping all collections in Mongoengine

description: Dropping all collections in Mongoengine


code:
#!/usr/bin/env python

from PIL import Image, ImageChops, ImageOps

def makeThumb(f_in, f_out, size=(80,80), pad=False):

    image = Image.open(f_in)
    image.thumbnail(size, Image.ANTIALIAS)
    image_size = image.size

    if pad:
        thumb = image.crop( (0, 0, size[0], size[1]) )

        offset_x = max( (size[0] - image_size[0]) / 2, 0 )
        offset_y = max( (size[1] - image_size[1]) / 2, 0 )

        thumb = ImageChops.offset(thumb, offset_x, offset_y)

    else:
        thumb = ImageOps.fit(image, size, Image.ANTIALIAS, (0.5, 0.5))

    thumb.save(f_out)

source = "/path/to/source/image.JPG"

makeThumb(source, "/path/to/source/image_padded.JPG", pad=True)
makeThumb(source, "/path/to/source/image_centerCropped.JPG", pad=False)

rawDescription: Resize image maintaining aspect ratio AND making portrait and landscape images exact same size?


code:
from lxml import etree

root = etree.parse("test.xml")

for element in root.iter("title"):
    print("%s - %s" % (element.tag, element.text))

rawDescription: How to make a function repeat itself

description: Make a function repeat itself


code: #!/usr/bin/env python -u

rawDescription: Asynchronous stdin read in Python

description: Asynchronous stdin read in Python


code:
import scipy.ndimage.morphology as m
import numpy as np
import cv2

def skeletonize(img):
    h1 = np.array([[0, 0, 0],[0, 1, 0],[1, 1, 1]])
    m1 = np.array([[1, 1, 1],[0, 0, 0],[0, 0, 0]])
    h2 = np.array([[0, 0, 0],[1, 1, 0],[0, 1, 0]])
    m2 = np.array([[0, 1, 1],[0, 0, 1],[0, 0, 0]])
    hit_list = []
    miss_list = []
    for k in range(4):
        hit_list.append(np.rot90(h1, k))
        hit_list.append(np.rot90(h2, k))
        miss_list.append(np.rot90(m1, k))
        miss_list.append(np.rot90(m2, k))
    img = img.copy()
    while True:
        last = img
        for hit, miss in zip(hit_list, miss_list):
            hm = m.binary_hit_or_miss(img, hit, miss)
            img = np.logical_and(img, np.logical_not(hm))
        if np.all(img == last):
            break
    return img

img = cv2.imread("e_5.jpg",0)
ret,img = cv2.threshold(img,127,255,0)
element = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
img = 255 - img
img = cv2.dilate(img, element, iterations=3)

skel = skeletonize(img)
imshow(skel, cmap="gray", interpolation="nearest")

rawDescription: Problems during Skeletonization image for extracting contours


code: inflam = StringVar(master = new_window_entry)

rawDescription: Tkinter getting data from an entry box and sending it to other functions


code:
if _data is None:
  _data = ...

rawDescription: OOP in python (related to scrapy)

description: OOP in python (related to scrapy)


rawDescription: How to interpret "description" as restructured text in sphinx argparse or autoprogram?

description: Interpret "description" as restructured text in sphinx argparse or autoprogram


rawDescription: Python strptime takes weekday name and returns tm_mday = 1 regardless of actual mday


code:
from collections import defaultdict

dataset = [('121', set(['NY'])), ('132', set(['CA', 'NY'])), ('198', set(['NY'])), ('676', set(['NY'])), ('89', set(['NY', 'CA']))]
output = defaultdict(list)
for value, key in dataset:
    output[tuple(sorted(key))].append(value)

rawDescription: How do I convert a list of tuples with sets to a dictionary?

description: Convert a list of tuples with sets to a dictionary


code:
s = df.stack()
s[s].index.tolist()

rawDescription: Filtering out only true values from Pandas DataFrame, return tuples of (Row,Col)


code: ';'.join(encode(i) for i in message.split('.'))

rawDescription: Iterating through a list in Python

description: Iterating through a list in Python


code: plt.subplots_adjust(top=0.85) # use a lower number to make more vertical space

rawDescription: my matplotlib title gets cropped

description: My matplotlib title gets cropped


code:
self._action_group.add_actions([("ExamplePy", None, _("Clear document"),
        None, _("Clear the document"),
        self.on_clear_document_activate)])

rawDescription: How to add keyboard shortcuts / accelerator keys for a menu item created by a Gedit plugin

description: Add keyboard shortcuts / accelerator keys for a menu item created by a Gedit plugin


code: [c + '\0' for c in S]

rawDescription: Add null character to string in python

description: Add null character to string in python


code:
no_gil()
echo_guard()
times_two()
~echo_guard()
~no_gil()
42

rawDescription: Boost.Python: Wrap functions to release the GIL


code: #define _PATH_HOST_CONFIG_FILE      SSHDIR "/ssh_config"

rawDescription: Specify SSH configuration file at run time in Ansible 1.9


rawDescription: Pandas create time series from day counts


code: chars

rawDescription: Python string comparison whilst in loop

description: Python string comparison whilst in loop


code:
nodes = dom.getElementsByTagName('IntDir') + dom.getElementsByTagName('Outputs')
for node in nodes:
    ...

rawDescription: getElementsByTagName code optimization

description: GetElementsByTagName code optimization


code:
temp = values[0]  # store the first value cause it'll be overwritten in loop
for index in range(len(values) - 1):
    values[index] = values[index + 1]  # shift values to the left
values[len(values) - 1] = temp  # write former first to last

rawDescription: Making list of number with integers and moving them Python 2.7


code:
import numpy as np

pvt = pd.pivot_table(df, values=['duration'],index=['project_id','resource'], columns=['activity'], aggfunc=np.sum,margins=True, fill_value=0)
pvt.to_html('result2.html')

rawDescription: List of dictionary in python as HTML Table format


code:
def get_longest_trip(self, board, processed_countries = list()):
    # see http://stackoverflow.com/questions/576988/python-specific-antipatterns-and-bad-practices/577198#577198
    processed_countries = list(processed_countries)
    processed_countries.append(self)

    longest_trip = list()
    if self.get_connections(board):
        possible_trips = list()
        for card in self.get_connections(board):
            if card not in processed_countries:
                possible_trips.append(card.get_longest_trip(board,
                                                            processed_countries))
        if possible_trips:
            longest_trip = max(possible_trips, key=len)
            longest_trip.append(self)

    if not longest_trip:
        longest_trip.append(self)
    return longest_trip

rawDescription: Help finding longest non-repeating path through connected nodes - Python


code:
soup = BeautifulSoup(html_doc, "xml")
soup.head
soup.HEAD

rawDescription: Can we convert all XML tags to lowercase in Beautifulsoup


code:
def __init__(self):
    self.win = GraphWin('Demo2', 800, 600) # give title and dimensions
    self.th = threading.Thread(target=self.FlashThread)

    self.correctMessage = Text(Point(self.win.getWidth()/2, 20), 'Correct!')
    self.incorrectMessage = Text(Point(self.win.getWidth()/2, 20), 'Incorrect,Try Again')

rawDescription: Need help trying to get information to display correctly using graphics


code: json.loads('{$and: [{filename: {$regex: "\\.part_of_my_name"} }, {bases: {$gt: 10000 }}]}')

rawDescription: Python / PyMongo - How to convert a MongoDB find() query to a PyMongo dictionary


code:
class Container(orderedset, RemovalAPI):
  # inheriting __iter__, remove from parent
  def insert(self, item):
    self.add(item)
    # do whatever post-processing I need
    # ...

rawDescription: Generalized reference that allows efficient deletion from a variety of containers


rawDescription: searching for shapefile within a directory

description: Searching for shapefile within a directory


code: distances = np.sqrt(((P_centered - P_projected) ** 2).sum(axis=1))

rawDescription: Finding the distance of points to an axis


code:
def load_tests(loader, standard_tests, pattern):
    return MyTest((
        loader.loadTestsFromTestCase(MySpecificTestCase),
        loader.loadTestsFromTestCase(MyFirstComponentTestCase),
        loader.loadTestsFromTestCase(MySecondComponentTestCase)
    ))

rawDescription: python unittest multiple mixins

description: Python unittest multiple mixins


code:
from itertools import product

for a,b,c,d in product([0,1], repeat=4):
    e = a ^ b ^ d
    f = a ^ c ^ d
    g = a ^ b ^ c ^ d
    h = c ^ d
    i = b ^ (1-d)
    print(a,b,c,d,e,f,g,h,i)

rawDescription: Minimize the sum of solution of linear equation


rawDescription: Construct list of numbers of occurrences in list


code: ipython -pylab

rawDescription: Dendrogram generated by scipy-cluster does not show


code:
soup = BeautifulSoup(_html)

a_tags = soup.select("#yfncsumtab a")
from pprint import pprint as pp
paired = dict((a.text, a["href"]) for a in a_tags)
pp(paired)

rawDescription: Python: searching through html file grabbing <a> tags with the href and text content


code:
for item in lst:
   do_something_to(item)
else:
   do_something_extra_special_to_last(item)

rawDescription: Iterate through Python list and do something on last element


code:
from operator import attrgetter

max(a, b, c, key=attrgetter('distance'))

rawDescription: How to choose the attribute of a user-defined class that will be evaluated for built-in min() and max() functions?

description: Choose the attribute of a user-defined class that will be evaluated for built-in min() and max() functions


code: {{ list|join('<br>'|safe) }}

rawDescription: Flask Jinja Template '<br>'.join

description: Flask Jinja Template '<br>'.join


rawDescription: Numpy rewriting operation using einsum

description: Numpy rewriting operation using einsum


code: d['Subject']

rawDescription: Get Value of a key from List of dictionary


code:
f = open('foo', 'r')
foo = Foo.load(f)
f.close()

rawDescription: Problematic function pickling

description: Problematic function pickling


code:
import pypdftk
pypdftk.fill_form('filled.pdf', out_file='flattened.pdf', flatten=True)

rawDescription: Generate flattened PDF with Python

description: Generate flattened PDF with Python


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

data = np.arange(6)
x = np.array([0.4, 0.6, 0.8, 1.5, 1.8, 2.2])
y = np.array([0.4, 0.8, 2.3, 2.5, 2.7, 2.9])

NX, NY = 4, 4
statistic, xedges, yedges, binnumber = stats.binned_statistic_2d(
    x, y, values=data, statistic='mean',
    bins=[np.arange(NX), np.arange(NY)])
print(statistic)

rawDescription: Rebin irregularly gridded data to regular (2D) grid in Python, using mean/median


code:
for item in items:
    csv_writer.writerow([item['name'], item['total_price']])
    csv_writer.writerows(['', p] for p in item['price'])

rawDescription: how to format csv with some sub items

description: Format csv with some sub items


code:
from folder_name import models
from models import model_to_import

rawDescription: Django include models.py from project to multiple apps


code:
def test_foo(someobj):
    assert isinstance(someobj, SomeObj)

rawDescription: How to share object from fixture to all tests using pytest?

description: Share object from fixture to all tests using pytest


code:
from selenium import webdriver
dr = webdriver.PhantomJS()
dr.get("http://www.zillow.com/homedetails/1630-Amalfi-Dr-Pacific-Palisades-CA-90272/20546602_zpid/")
span = dr.find_element_by_css_selector('div.main-row.home-summary-row span')
print(span.text)

rawDescription: Unable to retrieve element of desired XPATH using BeautifulSoup


code:
result_df = df.loc[(df.index.get_level_values('A') > 1.7) & (df.index.get_level_values('B') < 666)]
result_df

rawDescription: How to query MultiIndex index columns values in pandas

description: Query MultiIndex index columns values in pandas


code: result, a, b = show(x)

rawDescription: Python return true - false and value

description: Python return true - false and value


code:
import numpy as np
idxLsts = np.array([[1, 2], [0,2,4]], dtype = object)
idx = 99
f = np.frompyfunc(lambda x: x.append(idx), 1, 1)
f(idxLsts)
print(idxLsts)

rawDescription: Why is numpy vectorized function apparently called an extra time?


code:
from decimal import Decimal, ROUND_UP
Decimal(1.2345).quantize(Decimal(".1"), rounding=ROUND_UP)

rawDescription: Round up floats to first decimal point

description: Round up floats to first decimal point


code:
info = psutil.swap_memory()
used, free = info.used, info.free

rawDescription: When calling a function from a module can you say what is returned? (Python)


rawDescription: Resample withing a specified interval in Pandas?


code:
n1 = 0
n2 = 1
while n1 != n2:
    n1 = my_random_function()
    n2 = my_random_function()

rawDescription: (PYTHON) Until a == b

description: (PYTHON) Until a == b


simple_string: i encode easily

complex: this is a test

rawDescription: Is there a Python JSON encoder which JUST works?


rawDescription: Calculate two dimensional pairwise distance on a large numpy three dimensional array


code:
#/usr/bin/env python

import ruamel.yaml

def list_elements(fp, depth=0):
    buffer = None
    in_header = True
    list_element_match = ' ' * depth + '- '
    for line in fp:
        if line.startswith('---'):
            in_header = False
            continue
        if in_header:
            continue
        if line.startswith(list_element_match):
            if buffer is None:
                buffer = line
                continue
            yield ruamel.yaml.load(buffer)[0]
            buffer = line
            continue
        buffer += line
    if buffer:
       yield ruamel.yaml.load(buffer)[0]

with open("foobar.yaml") as fp:
   for element in list_elements(fp):
       print(str(element))

rawDescription: YAML list -> Python generator?

description: YAML list -> Python generator


code:
#!/usr/bin/env python3
from time import monotonic as timer

input("Press Enter to start timer") # wait for the first Enter from the user
start = timer()
input("Press Enter to stop timer")
elapsed = timer() - start
print("Speed {speed:f} m/s".format(speed=100 / elapsed))

rawDescription: How do you use a button as an input in python

description: Use a button as an input in python


code:
dict = {}
for i in range(10):
    dict["file" + str(i)] = "value for this var"

rawDescription: setting variables in a for loop python

description: Setting variables in a for loop python


rawDescription: Compare 2d numpy array to itself to form 3d array


code:
(ends - starts) + 1
array([3, 2, 1])

rawDescription: Longest prefix of array equal to a value


code:
_jssocket.setCallBack(event, callback);
_jssocket.connect(ip,port);
_jssocket.write(message);
_jssocket.disconnect();

rawDescription: connecting python to javascript for two-direction communication

description: Connecting python to javascript for two-direction communication


code:
from itertools import izip_longest, imap
from struct import unpack, calcsize

fmt_s = '=5i'
fmt_spec = '=256i'
size_s = calcsize(fmt_s)
size = size_s + calcsize(fmt_spec)

def chunked(iterable, n, fillvalue=''):
    args = [iter(iterable)] * n
    return imap(''.join, izip_longest(*args, fillvalue=fillvalue))

data = [unpack(fmt_s, section[:size_s]) + (unpack(fmt_spec, section[size_s:]),)
    for section in chunked(bytes, size)]

rawDescription: Reading a binary file into a struct in Python


code: whatever, mobilityhelper = wifi.add(h1, return_mobilityhelper=True)

rawDescription: How to add a variable of a method of a class in aonther program in python?

description: Add a variable of a method of a class in aonther program in python


code:
def union(a,b):
    a.append(b)
    result = []
    for item in a:
        result.append(a)
    return result

rawDescription: Python: Why "return" won´t print out all list elements in a simple for loop and "print" will do it?


code:
...
raw_html = r.text.encode("utf-8")
soup = BeautifulSoup(raw_html)
...

rawDescription: Python - retrieved different result when using curl and requests library


code:
char_generator = (pair for pair in enumerate(sequence) if pair[1] in subsequence)
for combo in itertools.combinations(char_generator, len(subsequence)):
    ...

rawDescription: Python: Sub sequence search

description: Python: Sub sequence search


code:
def writefile(lines):
    with open("myFile.txt", "w") as f:
        f.writelines(lines)

rawDescription: How can I split a file into seperate lines in python?

description: Split a file into seperate lines in python


code:
import example
assert(isinstance(example.make_spam(True), example.Spam))
assert(example.make_spam(False) is None)

rawDescription: How to wrap a C++ function that returns boost::optional<T>?

description: Wrap a C++ function that returns boost::optional<T>


code:
@app.route('/')
def index():
  content = """
     teste
   """
  user = "Hero"
  return render_template('index.html', **locals())

rawDescription: How to return multiple values in render_template in Flask

description: Return multiple values in render_template in Flask


code:
for word in words:
   print(word)

rawDescription: Return list of words from a list of lines with regexp


code:
a = []
for x in d:
    if x not in a:
        a.append(x)

rawDescription: element that appear more that once in the list in Python

description: Element that appear more that once in the list in Python


code:
from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage

string = """
square <- function(x) {
    return(x^2)
}

cube <- function(x) {
    return(x^3)
}
"""

powerpack = SignatureTranslatedAnonymousPackage(string, "powerpack")

rawDescription: Wrap R function in python

description: Wrap R function in python


code:
relations(a=...)
relations(b=...)

rawDescription: What’s the most Pythonic way of handling different, mutually-exclusive function inputs?


rawDescription: How to find specific video html tag using beautiful soup?

description: Find specific video html tag using beautiful soup


code:
def myParser(line):
    try:
        # do something
        return [result] # where result is the value you want to return
    except:
        return []

sc.textFile('path_to_file').flatMap(myParser)

rawDescription: Remove elements from Spark RDD

description: Remove elements from Spark RDD


code:
import inspect
def change_type(my_var):
    try:
        if float(my_var) > 0:
            my_var = float(my_var)
            inspect.stack()[1][0].f_locals['some_var'] = my_var
    except ValueError:
        pass

some_var = '0.5'
change_type(some_var)
print(type(some_var))

rawDescription: Change the type of a python function argument without rebinding


code:
#!/usr/local/bin/pypy

# -*- coding: utf-8 -*-
import re
import sys

from IPython import start_ipython

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
    sys.exit(start_ipython())

rawDescription: Is it possible to run a pypy kernel in the Jupyter notebook?


code:
from __future__ import print_function
import __builtin__

def print(*args, **kwargs):
    __builtin__.print('Foo:', *args, **kwargs)
print('Hi')

rawDescription: Overwrite built-in function

description: Overwrite built-in function


code:
IMC.special = A.thingy()
IMC.important_global_constant = 0x0001

rawDescription: Python namespaces: How to make unique objects accessible in other modules?


code:
q1 = session.query(Product).filter(Product.last_time_parsed < since) # filter-out those rows with less than 24 hours, right?
q2 = session.query(Product).filter(Product.last_time_parsed == None) # I'm interested on those products with no time stamp yet, too.
q3 = q1.union(q2).order_by(Product.id) # aaaaand, done!

rawDescription: SqlAlchemy filter by time difference

description: SqlAlchemy filter by time difference


rawDescription: Sort tuples based on second parameter

description: Sort tuples based on second parameter


code: sortedGroups = sorted({frozenset(g) for g in ugDict.values()})

rawDescription: Sorting rows into groups based on shared values


code:
df = pd.DataFrame([0, -1, -1, -1, 0 , 0, 0, 1, 0])
df.columns = ['A']
df['B'] = df['A']

# loop here
for i in range(1,len(df)):
     if df.A[i] == 0 and df.B[i-1] == -1:
             df.B[i] = -1
     else:
             df.B[i] = df.A[i]

rawDescription: conditional replace based off prior value in same column of pandas dataframe python

description: Conditional replace based off prior value in same column of pandas dataframe python


code:
from twisted.application.internet import TimerService

counter = 0

def foo():
    global counter
    if counter == 1:
        from twisted.internet import reactor
        reactor.stop()
    else:
        counter += 1

from twisted.application.service import Application

application = Application("timer stop")
TimerService(3, foo).setServiceParent(application)

rawDescription: How to stop a TimerService from within the LoopingCall

description: Stop a TimerService from within the LoopingCall


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

x = np.linspace(0, 10, 1000)
y = 0.000001*np.sin(10*x)

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

ax.plot(x, y)

def y_fmt(x, y):
    return '{:2.2e}'.format(x).replace('e', 'x10^')

ax.yaxis.set_major_formatter(tick.FuncFormatter(y_fmt))

plt.show()

rawDescription: Matplotlib pyplot axes formatter

description: Matplotlib pyplot axes formatter


code:
import os

R.f.seek(0, os.SEEK_END)
n = R.f.tell()
R.f.seek(0)

while R.f.tell() < n:
    line = R.f.readline()
    print(line)
    print("Not at EOF")
print("At EOF")

rawDescription: Find out if file pointer is at EOF in Python


code: {'mycode': ['1', '2', 'firstname', 'Lastname']}

rawDescription: extract a dictionary key value from a string

description: Extract a dictionary key value from a string


rawDescription: How to read a dictionary from a file in Python 2.7?

description: Read a dictionary from a file in Python 2.7


rawDescription: Why is my object properly removed from a list when __eq__ isn't being called?


code: cursor = db.channels.find({},{'_id':0, 'postcode': 1, 'upline': 1, 'cit_state': 1, 'contact_person': 1, 'contact_no': 1,'nominal_level': 1, 'credit': 1, 'level': 1, 'account_holder': 1, 'merchantid': 1, 'email': 1, 'bank': 1, 'reg_date': 1 ,'address': 1,'acc_no': 1,'company_name': 1})

rawDescription: Writing Data Into CSV Format File

description: Writing Data Into CSV Format File


rawDescription: Correlating vector data with numpy

description: Correlating vector data with numpy


code:
from reportlab.pdfgen import canvas

c = canvas.Canvas("test.pdf")
c.drawString(100, 100, u'\u2022 First sentence')
c.save()

rawDescription: Producing pdf report from python with bullet points


code:
def g(var1, var2):
    return 'qwe', var2

def h(var1, var2):
    return var1, 'asd'

def f(var1, var2, var3):
    var1, var2 = g(var1, var2)
    var1, var2 = h(var1, var2)  # h here sees "updated" values

# use as
f(var1, var2, var3)

rawDescription: How to safely divide code into functions without global vars in python

description: Safely divide code into functions without global vars in python


code:
self.clipboard = gtk.Clipboard()
self.clipboard.connect("owner-change", self.renderText)

rawDescription: Get notified on clipboard change via D-Bus


rawDescription: Rolling Mean of Rolling Correlation dataframe in Python?


code:
def mCount(L):
    count=1

    maxCount=0
    for i in range(len(L)-1):
        if L[i+1] >= L[i]:
            count +=1
        else:

            count =1
        if maxCount<count:
            maxCount=count
    return maxCount

rawDescription: Python-How to find length of the longest run of monotonically increasing numbers?


code:
#...in SpellFactory:
def setQuery(self, query):
    self.query = query

#...and in SpellClient:
def connectionMade(self):
    self.transport.write(self.factory.query)

rawDescription: Python Twisted Client

description: Python Twisted Client


rawDescription: column-wise normalization (scaling) of arrays

description: Column-wise normalization (scaling) of arrays


code:
(Rectangle(1, 10), Rectangle(2, 20), Rectangle(3, 30))
(Rectangle(1, 10), Rectangle(2, 20), Rectangle(30, 3))
(Rectangle(1, 10), Rectangle(20, 2), Rectangle(3, 30))
(Rectangle(1, 10), Rectangle(20, 2), Rectangle(30, 3))
(Rectangle(10, 1), Rectangle(2, 20), Rectangle(3, 30))
(Rectangle(10, 1), Rectangle(2, 20), Rectangle(30, 3))
(Rectangle(10, 1), Rectangle(20, 2), Rectangle(3, 30))
(Rectangle(10, 1), Rectangle(20, 2), Rectangle(30, 3))

rawDescription: Python list of objects, get all 'orientations' of attributes


code: [int(s.replace('[', '').replace(']', '')) for s in qtyList]

rawDescription: Splitting or pulling only integers in an array - python


rawDescription: Pandas: Dict of data frames to unbalanced Panel


rawDescription: Alternatives to cartesian in Spark?

description: Alternatives to cartesian in Spark


code:
test_array = np.arange(10)
test_array+test_array2

rawDescription: Numpy apply_along_axis function

description: Numpy apply_along_axis function


code:
import pandas as pd
df1 = pd.read_csv(r'd:\temp\data1.csv')
df2 = pd.read_csv(r'd:\temp\data2.csv')
df3 = pd.merge(df1,df2, on= 'reference', how='inner')
df3.to_csv('outpt.csv')

rawDescription: Python CSVkit compare CSV files

description: Python CSVkit compare CSV files


rawDescription: How to convert this list into a dictionary

description: Convert this list into a dictionary


code:
def square_param(param):
    def func_decorator(func):
        def func_caller(*args,**kwargs):
            kwargs[param] = kwargs[param] * kwargs[param]
            return func(*args,**kwargs)
        return func_caller
    return func_decorator

rawDescription: How can I treat positional arguments as keyword arguments in Python 2

description: Treat positional arguments as keyword arguments in Python 2


code: first_two = {c: w[:2] for c, w in d.items()}

rawDescription: python get list element according to alphabet

description: Python get list element according to alphabet


code:
for elem in iterable:
    self[elem] = self_get(elem, 0) + 1

rawDescription: How does collections.Counter achieve fast sort time?


code:
def myfunction(list_a, list_b):
   dict1 = dict(zip(list_a, list_b))
   return copy.deepcopy(dict1)

my_dict = myfunction(some_list_a, some_list_b)

rawDescription: Is it possible to create a dictionary inside a function using python?


code:
amounts = bond.to_cash_flows().amounts.append(Series)
print('SERIES', amounts)

rawDescription: Appending to a Series dynamically

description: Appending to a Series dynamically


code:
import operator, itertools
def differ(w1, w2):
    it = itertools.imap(operator.ne, w1, w2)
    return len(w1) == len(w2) and any(it) and not any(it)

rawDescription: Comparing characters in a string

description: Comparing characters in a string


code:
TokenInfo(type=54 (COMMENT), string='# Comment 1', start=(2, 0), end=(2, 11), line='# Comment 1\n')
TokenInfo(type=54 (COMMENT), string='##### Comment 2 #####', start=(4, 0), end=(4, 21), line='##### Comment 2 #####\n')

rawDescription: Is there a tool to extract all comments from python source, preserving source line/col info?


code: re.search(r"DeltaE =\s+(\S+).* TDMI\^2 =\s+(\S+).* Intensity =\s+(\S+)", line)

rawDescription: Python: re.search not working

description: Python: re.search not working


code:
class FakeFieldStorage(object):
  def __init__(self, filename, value):
    self.filename = filename
    self.value = value

rawDescription: Simulating a Google App Engine File Upload in Python


code:
from pyspark.ml.feature import VectorAssembler

assembler = VectorAssembler(
    inputCols=["your", "independent", "variables"],
    outputCol="features")

transformed = assembler.transform(parsedData)

rawDescription: Create labeledPoints from Spark DataFrame in Python


code:
import re
data = '@#%%.Hol$a.A.$%'
pattern = r'[\w.].*[\w.]'
print(re.search(pattern, data).group(0))
# Output: .Hol$a.A.

rawDescription: Strip punctuation with regular expression - python


code:
ID
value
unqID,idx,IDsums = np.unique(ID,return_counts=True,return_inverse=True)
{i:(IDsums[itr],value_sums[itr]) for itr,i in enumerate(unqID)}

rawDescription: Summing data from array based on other array in Numpy


code: set(yourString) & set(badChars)  # extensionally equivalent, slower

rawDescription: Find which lines in a file contain certain characters


code:
df_p.columns = ['_'.join(c[::-1]) for c in df_p.columns]
df_p

rawDescription: create column names by joining two labels of different levels with pandas

description: Create column names by joining two labels of different levels with pandas


code:
from scrapy.http import Request
from eScraper.items import EscraperItem
from scrapy.selector import HtmlXPathSelector

#------------------------------------------------------------------------------
from scrapy.spider import BaseSpider

class ESpider(BaseSpider):
    name = "atisundarSpider"

    allowed_domains = ["atisundar.com"]

    URLSList = []

    for n in range (1,20):

        URLSList.append('http://atisundar.com/collections/sarees?page=' + str(n))
        URLSList.append('http://atisundar.com/collections/salwar-suits?page=' + str(n))

    start_urls = URLSList

def parse(self, response):
    item = EscraperItem()
    hxs = HtmlXPathSelector(response)
    sites = hxs.select('//div[@class="block product size-medium"]')
    for site in sites:
        item = EscraperItem()
        item['productDesc'] = ""
        item['productSite'] = ["http://atisundar.com/"]
        item['productTitle'] = site.select('.//div[@class="main"]/a/@title').extract()
        item['productURL'] = ["http://atisundar.com" + site.select('.//div[@class="main"]/a/@href').extract()[0].encode('utf-8')]
        item['productPrice'] = site.select('.//p[@class="pricearea"]//span[@class="was-price"]/text()').extract() + site.select('.//p[@class="pricearea"]//span[@class="price"]/text()').extract()
        item['productImage'] = [site.select('.//div[@class="main"]/a/img/@src').extract()[0].split('?')[0]] + [site.select('.//div[@class="main"]/a/img/@src').extract()[0].split('?')[0].replace("medium","grande")]
        item['image_urls'] = item['productImage']
        secondURL = "http://admin.atisundar.com/store/skuDetails?product_id=" + site.select('.//div[@class="main"]/a/text()').extract()[1].strip().split("#")[-1]
        request = Request(secondURL,
                  callback=self.parse_page2)
        request.meta['item'] = item
        yield request

def parse_page2(self, response):

    item = response.request.meta['item']
    #item['other_url'] = response.url
    return item

rawDescription: How to call Parse_page2 method for every item

description: Call Parse_page2 method for every item


code:
yDiffs = [0] + list(valueLst[i][1] - valueLst[i-1][1]
                    for i in range(1, len(valueLst)))
bestZVal = valueLst[yDiffs.index(max(yDiffs))][2]

rawDescription: Cumulative style calculations of entries in a data table using class initialisation in Python


code: order_items = OrderItem.objects.filter(**all_or_filter_args(request, 'provider'))

rawDescription: Django wildcard query

description: Django wildcard query


code:
angle = np.arctan2(x, y)
order = np.argsort(angle)
x = x[order]
y = y[order]

fig, ax = pl.subplots()
ax.set_aspect(1.0)
x2 = np.r_[x, x[0]]
y2 = np.r_[y, y[0]]
ax.plot(x, y, "o")
ax.plot(x2, y2, "r", lw=2)

rawDescription: How to draw circle by data with matplotlib + python?

description: Draw circle by data with matplotlib + python


code:
def t1( iterable ):
    for piece in iterable:
        more_data = transform1( piece )
        yield NewNamedTuple( piece, more_data )

rawDescription: Sharing data between processes in Python


code:
from bs4 import BeautifulSoup
data = """

Employee Count

331,000

"""

soup = BeautifulSoup(data)
soup.find('div', text='Employee Count').find_next_sibling().text

rawDescription: BeautifulSoup/Python/HTML - Return the div class right after a specific div class


code:
for a in range(10):
    data.append(myList2)

rawDescription: Mutation algorithm python

description: Mutation algorithm python


code:
for menu in soup.select('div.menu'):
    author = menu.find('span', class_='author').get_text()
    time = menu.find('span', class_='smaller').get_text()
    data = menu.find('br').next_sibling

rawDescription: Getting text from br tags in BeautifulSoup


code: 1.0 / i + sum_of_reciprocals(i-1)

rawDescription: Python 3 Recursion - Maximum Depth Exceeded


code:
import string
string.ascii_letters

rawDescription: Trouble converting certain special characters from Ascii in Python


code: ax.fill_betweenx(mass, inner_edge, outer_edge, facecolor='b')

rawDescription: Using fill_between for a band

description: Using fill_between for a band


code:
N=10; A1 = np.random.rand(N,8,8)+1j*np.random.rand(N,8,8)
np.linalg.norm(A1,ord=2,axis=(1,2))

rawDescription: Computing the spectral norms of ~1m Hermitian matrices: `numpy.linalg.norm` is too slow


code:
values = mygenerator()
unique_values = set(values)

rawDescription: python generators duplicates

description: Python generators duplicates


code: swelling

rawDescription: Use BeautifulSoup to Iterate over XML to pull specific tags and store in variable


code: reduce(lambda x, y: x + y, [int(x) for x in str(reduce(lambda x, y: x * y, range(1, 11)))])

rawDescription: How do I turn a string of digits into a list of one-digit integers?

description: Turn a string of digits into a list of one-digit integers


code:
while True:
    last = my_string[-1]
    my_string = my_string[:-1]
    if last == '+':
        break

rawDescription: Python: Iterate over string with while loop


code:
def access(time_object, max_lvl, lvl):
    tmp = time_object
    while(lvl < max_lvl):
        tmp = time_object[0]
    return tmp

rawDescription: Accessing item in a nested list: creating dependency between items, saving memory


rawDescription: Python append dictionary to dictionary

description: Python append dictionary to dictionary


code:
for line in f:
    tokens = line.split(" ")
    current_state, input_val, next_state = int(tokens[0]), tokens[1], int(tokens[2])

rawDescription: Python graceful fail on int() call?

description: Python graceful fail on int() call


code:
import regex
test1 = "url#123"
test2 = "url"
regex.sub(r"url(#[0-9]+)?", r"new_url\1", test1)
regex.sub(r"url(#[0-9]+)?", r"new_url\1", test2)

rawDescription: How to re.sub() a optional matching group using regex in Python?

description: Re.sub() a optional matching group using regex in Python


code: d

rawDescription: Creating an alternating dictionary with a loop in Python


code:
master
tempdb
model
msdb
myDb

rawDescription: List names of all available MS SQL databases on server using python


code:
Code
from collections import defaultdict
my_list = [('tag_A', 100), ('tag_A', 200), ('tag_A', 300), ('tag_A', 400), ('tag_B', 400), ('tag_B', 600)]

d = defaultdict(list)
for tag, num in my_list:
    d[tag].append(num)

rawDescription: Python list_of_tuples: sum second val of each tuple, only if first val of tuple == something


code:
import csv
import operator
import tabulate

with open('path/to/file.txt') as inf:
    reader = sorted(csv.reader(inf), key=operator.itemgetter(1))
    headers = next(reader)
    print(tabulate([(row[0], row[1], row[2]-row[3],
                     "{:>2} : {:2}".format(row[2], row[3])) for row in reader],
                   headers=headers))

rawDescription: Print csv input file into a table of columns/rows


code:
def getSize(self,fileobject):
  fileobject.seek(0,2) # move the cursor to the end of the file
  size = fileobject.tell()
  return size

f = self.request.POST.get('fname').file

media = gdata.data.MediaSource(file_handle=f.read(), content_type=gdata.docs.service.SUPPORTED_FILETYPES[ext], content_length=self.getSize(self.request.POST.get('fname').file))

rawDescription: Using Google App Engine how to upload document in google docs (python)


code:
REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)
}

rawDescription: How to add search parameters to GET request in Django REST Framework?

description: Add search parameters to GET request in Django REST Framework


code:
Example
print(majority_element("A A A C C B B C C C B C C".split()))
print(majority_element("A A A A C B C C C B C C".split()))

rawDescription: Python Find Majority Number in O(n) time and O(1) memory


code:
import re

t= '         <Layer DisplayName="Parcels (7-1-2010)" FeatureDescription="Owner Name: {OWNER_NAME}
Property Address: {PROP_ADDR}
Tax Name: {TAX_NAME}
Tax Address 1: {TAX_ADD_L1}
Tax Address 2: {TAX_ADD_L2}
Land Use: {USE1_DESC}
View Property Information

" FeatureLabel="Parcel ID: {PID_NO}" IconUri="{RestVirtualDirectoryUrl}/Images/Parcel.png" Identifiable="true" IncludeInLayerList="true" IncludeInLegend="true" Name="Parcels" Searchable="true" ShowMapTips="true" UnconfiguredFieldsSearchable="true" UnconfiguredFieldsVisible="true" Visible="true">'

rawDescription: Python look for pattern in string

description: Python look for pattern in string


rawDescription: Python coverting list to dictionary

description: Python coverting list to dictionary


rawDescription: Python curve_fit with multiple independent variables


code: myReader = CSVReader(FileName='C:\foo.csv', guiName='foo.csv')

rawDescription: How do I use ParaView's CSVReader in a Python Script?

description: Use ParaView's CSVReader in a Python Script


rawDescription: Entry.get() returns nothing tkinter - python 3.4


rawDescription: How to directly access class instances through class dictionary in Python

description: Directly access class instances through class dictionary in Python


code:
def no_event(func):
    @functools.wraps(func)
    def wrapper(event):
        return func()
    return wrapper

rawDescription: How can I prevent Tkinter from passing the event object in a binding? Is there any workaround to do this?

description: Prevent Tkinter from passing the event object in a binding? Is there any workaround to do this


code:
x,y=np.meshgrid(np.arange(10),np.arange(8))
z=x+y
f=interpolate.Rbf(x,y,z,kind='linear')
x.shape

rawDescription: 2 d interpolation with the arrays with different dimensions in python


code:
prices = response.xpath('//span[@class="local nsg-font-family--base"]/text()').extract()
print(prices[1])

rawDescription: not able to output specific row from xpath response

description: Not able to output specific row from xpath response


code: filter_data = {'horsepower': horsepower, 'voltage': voltage, 'rpm': rpm}

rawDescription: Remove objects from query if None or Null


code:
if l < 3:
    lst = line.split()
    print(lst)
    iname = input('enter indexes that for elements of name: ')     # use raw_input in py2k
    idegr = input('enter indexes that for elements of degree: ')

rawDescription: How to strip variable spaces in each line of a text file based on special condition - one-liner in Python?

description: Strip variable spaces in each line of a text file based on special condition - one-liner in Python


code:
while somelist and somelist[-1][1] == 0:
    somelist.pop()

rawDescription: Filter elements from the end of a list

description: Filter elements from the end of a list


code:
# Note: schema inference from dictionaries has been deprecated
# don't use this in practice
df = sc.parallelize([{"stuff": [{"a": 1, "b": 2, "c": 3}]}]).toDF()
df.registerTempTable("df")

df.printSchema()
## root
##  |-- stuff: array (nullable = true)
##  |    |-- element: map (containsNull = true)
##  |    |    |-- key: string
##  |    |    |-- value: long (valueContainsNull = true)

sqlContext.sql("SELECT stuff[0]['a'] FROM df").show()
## +---+
## |_c0|
## +---+
## |  1|
## +---+

rawDescription: SparkSQL sql syntax for nth item in array


code:
import numpy
import matplotlib.pyplot as plt
n=200 #Grid size, 4 times my visualized output in order to be able to truncate some circles
empty_lattice=numpy.zeros((n,n)) #The empty 2D grid
radius=int(numpy.random.uniform(30,90)) #Radius
xc=int(numpy.random.uniform(0,n-radius)) #X center
yc=int(numpy.random.uniform(0,n-radius)) #Y center
r2 = radius ** 2
for dx in range(0, radius):
    dx2 = dx ** 2
    for dy in range(0, dx + 1):
        dy2 = dy ** 2
        if (dx2 + dy2 <= r2):
            empty_lattice[xc+dx][yc+dy]=1 #1st octant
            empty_lattice[xc-dx][yc+dy]=1 #2nd octant
            empty_lattice[xc+dx][yc-dy]=1 #3rd octant
            empty_lattice[xc-dx][yc-dy]=1 #4th octant
            empty_lattice[xc+dy][yc+dx]=1 #5th octant
            empty_lattice[xc-dy][yc+dx]=1 #6th octant
            empty_lattice[xc+dy][yc-dx]=1 #7th octant
            empty_lattice[xc-dy][yc-dx]=1 #8th octant

plt.imshow(empty_lattice)
plt.show()

rawDescription: How to "translate" the Midpoint Circle Algorithm into matplotlib?


rawDescription: Python reverse function

description: Python reverse function


rawDescription: Python binary operators and word splitting


rawDescription: how do I find out how many arguments a lambda function needs

description: Find out how many arguments a lambda function needs


code:
Simple
repos.git.add(submodule.path)
repos.index.commit("updated submodule to 'wanted commit'")

rawDescription: GitPython: how to commit updated submodule


code:
from collections import OrderedDict
class Example(OrderedDict):
    def reinit(self, d):
        self.clear()
        OrderedDict.__init__(self, d)

d=Example([(1,1),(2,2)])
d.reinit([(2,20),(1,10)])
print(d)

rawDescription: OrderedDict reinitialisation: order is lost


rawDescription: xpath for capturing hover css property from selenium webelement in python

description: Xpath for capturing hover css property from selenium webelement in python


rawDescription: Storing a dict with np.savez gives unexpected result?


code:
class A(Base):
    __tablename__ = 'as'

    id = Column(Integer, primary_key=True)
    name = Column(Unicode, nullable=False, unique=True)
    comments = relationship("Comment",
                    primaryjoin="and_(A.id==Comment.id, "
                        "Comment.model=='A')")

    def __init__(self, name):
        self.name = name

class Comment(Base):
    __tablename__ = 'comments'

    id = Column(Integer, primary_key=True)
    text = Column(UnicodeText, nullable=False)
    model = Column(String(50), nullable=False)

    def __init__(self, text):
        self.text = text

rawDescription: How to construct different-type-ones-to-many relationship?

description: Construct different-type-ones-to-many relationship


rawDescription: Is it possible to alter the values in a dictionary, keeping the key value constant?


rawDescription: How to Delete Rows CSV in python

description: Delete Rows CSV in python


code:
g1, g2, g3, g4 = result.groups()
for keyvalue in g4.split(): # split on whitespace
    key, value = keyvalue.split('=')
    # do something with them

rawDescription: Capture a Repeating Group in Python using RegEx (see example)


code: import ipdb; ipdb.set_trace()

rawDescription: Is there a way of using breakpoints in python?


code:
projections = do_projections(actdf)
projections.aname

rawDescription: Create a summary Pandas DataFrame using concat/append via a for loop


code:
TranMatrix = zero(3,3)
TranMatrix[0][0]=1
TranMatrix[0][2]=Tx
TranMatrix[1][1]=1
TranMatrix[1][2]=Ty
TranMatrix[2][2]=1

translated=mult(TranMatrix, original)

rawDescription: Rotation, scale and translate function for python


code:
df['index'] = df['date'].apply(lambda x:x.day)
df

rawDescription: Find Unique Dates in Numpy Datetime Array


code:
import urllib2
user_agent = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3'
headers = { 'User-Agent' : user_agent }
req = urllib2.Request('http://www.google.com', None, headers)
response = urllib2.urlopen(req)
page = response.read()
response.close() # its always safe to close an open connection

rawDescription: Python http download page source

description: Python http download page source


code:
# Choose a particular curve and prime.  We assume that p > 3.
p = 15733
a = 1
b = 3

def valid(P):
    """
    Determine whether we have a valid representation of a point
    on our curve.  We assume that the x and y coordinates
    are always reduced modulo p, so that we can compare
    two points for equality with a simple ==.
    """
    if P == O:
        return True
    else:
        return (
            (P.y**2 - (P.x**3 + a*P.x + b)) % p == 0 and
            0 <= P.x < p and 0 <= P.y < p)

rawDescription: Elliptic curve point addition over a finite field in Python


code:
from nltk.tokenize import WhitespaceTokenizer
s = "Good muffins cost $3.88\nin New York."
span_generator = WhitespaceTokenizer().span_tokenize(s)
spans = [span for span in span_generator]
print(spans)

rawDescription: get indices of original text from nltk word_tokenize

description: Get indices of original text from nltk word_tokenize


rawDescription: Function called when using binary operators, python


code:
dnew = divide_dictionaries(d)
import pprint
pprint.pprint(dnew)

rawDescription: Dividing dictionary into nested dictionaries, based on the key's name on Python 3.4


code:
p = P.objects.get(name="x")
p.delete() # all t's that link to p will be deleted.

rawDescription: Django admin delete != Model.delete()

description: Django admin delete != Model.delete()


code:
import numpy as np

items = np.array([1,1,1,9])
sizeLimit = len(items)
P = np.zeros((len(items),len(items)))

for i in range(sizeLimit-1, -1, -1):
  for j in range(sizeLimit-1, i-1, -1):
    if i == sizeLimit-1:
        P[i,j] = items[i]
    else:
        if j > i:
            P[i,j] = P[i+1,j] + [j-i]
        elif j == i:
            P[i,j] = items[i] + P[j+1, (j+1):].min()

rawDescription: Dynamic programming in Python

description: Dynamic programming in Python


rawDescription: Aggregating over timestamps in pandas

description: Aggregating over timestamps in pandas


code:
d2=type2.descr
d2

rawDescription: Best Way to Resize Numpy Dtype for Structured data


code:
df.set_index(['Symbol', 'TimeStamp'])
df.set_index(['Symbol', 'TimeStamp']).sortlevel(0)

rawDescription: Pandas DataFrame - desired index has duplicate values


code: map(lambda x: x if x[0] == 'A' else "A" + x, y)

rawDescription: How to minimize string-appending to one line in Python?

description: Minimize string-appending to one line in Python


code:
f2 = MyFighters()
f2.foo_bar_func()

rawDescription: Python: multi level inheritance

description: Python: multi level inheritance


code:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

pdf_files = {}
for group_name, group in df.groupby(['Allotment', 'Date']):
    allotment, date = group_name
    if allotment not in pdf_files:
        pdf_files[allotment] = PdfPages('C:\\' + allotment + '.pdf')
    plot=group.plot(x='Value', y='NDVI', title=str(group_name)).get_figure()
    pdf_files[allotment].savefig(plot)
    plt.close(plot)

for key in pdf_files:
    pdf_files[key].close()

rawDescription: Plotting to seperate pdf files based on groupby


code:
@app.route("/result")
def calculate_result():
    s, t = request.args.get("s"), request.args.get("t")
    # Calculate result with s and t
    session["result"] = result
    return redirect(url_for(".display_results", result=result))

@app.route("/final/abcd")
def display_results():
    result = session.get("result")
    return render_template("results.html", result=result)

rawDescription: Routing view to another URL based on parameters


code:
import time
import itertools
import concurrent.futures
from concurrent.futures import ProcessPoolExecutor as Pool

def call_ws_1(group_id):
    return list(range(10000))

def call_ws_2(hosts):  # This worker now works on a list of hosts
    host_results = []
    for host in hosts:
        host_results.append(( host, "{} property".format(host)))  # returns a list of (host, property) tuples
    return host_results

def chunk_list(l):
    chunksize = len(l) // 16  # Break the list into smaller pieces
    it = [iter(l)] * chunksize
    for item in itertools.zip_longest(*it):
        yield tuple(filter(None, item))

def fetch_property(hosts):
    with Pool(max_workers=4) as executor:
        futs = []
        for chunk in chunk_list(hosts):
            futs.append(concurrent.futures.submit(call_ws_2, chunk))
        for future in concurrent.futures.as_completed(futs):
            try:
                 results = future.result()
            except Exception as exp:
                print("Got %s" % exp)
            else:
                for result in results:
                    host, property = result
                    # Save host and property to DB

def fetch_hosts(group_ids):
    with Pool(max_workers=4) as executor:
        future_to_grp_id = {executor.submit(call_ws_1, group_id): group_id for group_id in group_ids}
        for future in concurrent.futures.as_completed(future_to_grp_id):
            group_id = future_to_grp_id[future]
            try:
                hosts = future.result()#this is a list
            except Exception as exp:
                print("Got %s" % exp)
            else:
                print("Fetching hosts for {}".format(group_id))
                fetch_property(hosts)

if __name__ == "__main__":
    start = time.time()
    fetch_hosts(['a', 'b', 'c', 'd', 'e'])
    end = time.time()
    print("Total time: {}".format(end-start))

rawDescription: Python : efficiency concerns in parallel async calls to fetch data from web services


code:
results = []
for obj in input:
    results.append( func(obj) )

rawDescription: Map Function to Dictionary of Objects

description: Map Function to Dictionary of Objects


code:
curr_angle = 0
angle_step = (math.pi*2)/shots

rawDescription: Python - Pygame - Handling angles and speeds of animations


code:
from collections import Counter

a=['1','2']
b=['1','2','3']

a.extend(b)

[k for k,v in Counter(a).items() if v == 1]

rawDescription: restoring list from unified_diff output

description: Restoring list from unified_diff output


rawDescription: python pandas to drop lines and substitute values in specific columns of a csv file

description: Python pandas to drop lines and substitute values in specific columns of a csv file


code:
data = open('data.csv', 'r')
reader = csv.reader(data)

print(next(reader))               # Parse the first line
[next(data) for _ in range(5)]    # Skip the next 5 lines on the underlying iterator
print(next(reader))               # This will be the 7'th line in data
print(reader.line_num)            # reader thinks this is the 2nd line
data.seek(0)                      # Go back to the beginning of the file
print(next(reader))               # gives first line again

data = ['1,2,3', '4,5,6', '7,8,9']
reader = csv.reader(data)         # works fine on lists of strings too
print(next(reader))               # ['1', '2', '3']

rawDescription: Don't understand Python's csv.reader object


code: res = res.extend(B)

rawDescription: Recursive Python function to produce a list of anagrams


code:
if any(search in sublist for sublist in data):
    print ("there")
else:
    print("not there")

rawDescription: Python Search within Lists within Lists

description: Python Search within Lists within Lists


code:
import MySQLdb
import MySQLdb.cursors as cursors
import threading
import logging
import config

logger = logging.getLogger(__name__)
query = 'SELECT * FROM huge_table LIMIT 200'

def oursql_conn():
    import oursql
    conn = oursql.connect(
        host=config.HOST, user=config.USER, passwd=config.PASS,
        db=config.MYDB)
    return conn

def mysqldb_conn():
    conn = MySQLdb.connect(
        host=config.HOST, user=config.USER,
        passwd=config.PASS, db=config.MYDB,
        cursorclass=cursors.SSCursor)
    return conn

def two_cursors_one_conn():
    """Two SSCursors can not use one connection concurrently"""
    def worker(conn):
        cursor = conn.cursor()
        cursor.execute(query)
        for row in cursor:
            logger.info(row)

    conn = mysqldb_conn()
    threads = [threading.Thread(target=worker, args=(conn, ))
               for n in range(2)]
    for t in threads:
        t.daemon = True
        t.start()
        # Second thread may hang or raise OperationalError:
        # File "/usr/lib/pymodules/python2.7/MySQLdb/cursors.py", line 289, in _fetch_row
        #   return self._result.fetch_row(size, self._fetch_type)
        # OperationalError: (2013, 'Lost connection to MySQL server during query')

    for t in threads:
        t.join()

def two_cursors_two_conn():
    """Two SSCursors from independent connections can use the same table concurrently"""
    def worker():
        conn = mysqldb_conn()
        cursor = conn.cursor()
        cursor.execute(query)
        for row in cursor:
            logger.info(row)

    threads = [threading.Thread(target=worker) for n in range(2)]
    for t in threads:
        t.daemon = True
        t.start()
    for t in threads:
        t.join()

logging.basicConfig(level=logging.DEBUG,
                    format='[%(asctime)s %(threadName)s] %(message)s',
                    datefmt='%H:%M:%S')
two_cursors_one_conn()
two_cursors_two_conn()

rawDescription: SQLAlchemy memory hog on select statement


rawDescription: Common elements between two lists of lists (intersection of nested lists)


code:
from django.forms.models import inlineformset_factory
BookFormSet = inlineformset_factory(Author, Book)
author = Author.objects.get(name=u'Mike Royko')
formset = BookFormSet(instance=author)

rawDescription: How can I have the equivalent of django's admin inlines in a modelform?

description: Have the equivalent of django's admin inlines in a modelform


code:
from geopy import distance
_, ne = g.geocode('Newport, RI')
_, cl = g.geocode('Cleveland, OH')
distance.distance(ne, cl).miles

rawDescription: Using GeopositionField to find closest database entries


code:
helper_dict = {k: v for v, x in myDict.items() for k in x}
with open("input.txt") as f:
    for line in f:
        fields = line.split("\t")
        key = fields[0]
        if key in helper_dict:
            newdict[helper_dict[key]] = len(myDict[helper_dict[key]])

rawDescription: searching a value in a list and outputting its key

description: Searching a value in a list and outputting its key


code: [item[1] for item in sorted(by_index)]

rawDescription: Python argmin/argmax: Finding the index of the value which is the min or max


code:
start_stop = []
for c, start, stop in a:
    start_stop.append(slice(start, stop))

rawDescription: Writing python chunking loops with reference to another txt


code:
wait = WebDriverWait(driver, 10)
wait.until(wait_for_class((By.ID, 'select-1'), "ui-state-error"))

rawDescription: How can I wait until an element gains or loses a class?

description: Wait until an element gains or loses a class


code:
from itertools import dropwhile

line = next(dropwhile(lambda x: x[0]==line_number, enumerate(file)))[1]

rawDescription: Reading specific lines from a file in a loop (optimization)


code:
info = ['apple: 1', 'orange: 2', 'grape: 3']
info = {fruit:num for fruit, num in (line.split(': ') for line in info)}

rawDescription: Python: creating dictionary from a bunch of "key: value" strings?


code:
resdict = dict((r['country'].upper(), r['count']) for r in result)
mainRes = dict( (abbrev, resdict.get(country,0)) for country, abbrev in firstDict.items())

rawDescription: Python:Comparing Two Dictionaries

description: Python:Comparing Two Dictionaries


code:
import pandas as pd

df = pd.DataFrame(["foo bar" , "foo", "bar barf"],columns=["name"])
from operator import itemgetter

df['first_name'], df['last_name'] = zip(*df['name'].apply(lambda x: itemgetter(0,2)(x.partition(' '))))

rawDescription: ValueError: need more than 1 value to unpack, how can I make my code more robust?


rawDescription: How to calculate CRC32 with Python to match online results?

description: Calculate CRC32 with Python to match online results


rawDescription: python string formatting function

description: Python string formatting function


rawDescription: Item Loaders not working properly in scrapy


code:
import numpy as np
a = np.array(quantized)
blockLengthX = np.argmin(a[0]==a[0,0])
blockLengthY = np.argmin(a[:,0]==a[0,0])

rawDescription: convert image to value matrix

description: Convert image to value matrix


code: sum(samples[i - n + 1:i + 1])

rawDescription: Python: Why is list comprehension slower than for loop


code:
QtCore.QObject.connect(a, QtCore.SIGNAL("QtSig()"), pyFunction) #function-style
QtCore.QObject.connect(a, QtCore.SIGNAL("QtSig()"), pyClass.pyMethod) #method-style

rawDescription: In PyQt, how can signals and slots be used to connect a dropdownlist to a function?


rawDescription: Parse list to other list

description: Parse list to other list


code:
def conjoin(*fns):
    def conjoined(x):
        for fn in fns:
            if not fn(x): return False
        return True
    return conjoined

rawDescription: Concise way to call ifilter with multiple predicates in python


rawDescription: rounding a variable to 2 dp whilst adding a 0 to the end og 1dp values

description: Rounding a variable to 2 dp whilst adding a 0 to the end og 1dp values


code:
class test(multiprocessing.Process):
    ...
    def handle(self,sig,fem):
        ...

    def run(self):
        signal.signal(signal.SIGALRM, self.handle)
        ...

...
test_1.start()
time.sleep(2)

os.kill(test_1.pid, signal.SIGALRM)

rawDescription: signal handler in mulitprocess.process class , can't get class's val

description: Signal handler in mulitprocess.process class , can't get class's val


rawDescription: MultiIndex from product of unique values of two indexes


code:
from glob import glob
import fileinput
with open('output.csv', 'w') as out:
    out.writelines(line for line in fileinput.input(glob('*.log')) if 'KEYWORD' in line)

rawDescription: Copy select lines from many text files and paste to new file


code:
class User(db.Model):
  username = db.StringProperty()

class Group(db.Model):
  users = db.ListProperty(db.Key)

rawDescription: GQL - Select all parents where specific child is not in children


rawDescription: Python list slice

description: Python list slice


code: line_objects = plt.plot(x, y[0], x, y[1], x, y[2])

rawDescription: Drawing dynamically n plots

description: Drawing dynamically n plots


rawDescription: Python - eliminating common elements from two lists


code:
domain = 'ab-test-db-dev.0002-colo1-vm234.abc.domain.com'
hostname = domain
while '-' in domain:
    domain = domain.partition('.')[-1]

hostname[:-len(domain) - 1]
domain = 'ab-test-db-dev.0002-colo1-vm234.abc.domain.com'
hostname = domain
while True:
    first, _, end = hostname.rpartition('.')
    if '-' in end:
        break
    hostname = first

hostname
import re
re.sub(r'\.[a-z.]+$', '', domain)

rawDescription: python split a string when a keyword comes after a pattern

description: Python split a string when a keyword comes after a pattern


rawDescription: Tokenize and label text

description: Tokenize and label text


code:
from datetime import datetime

def a_view(request):
    return render_to_response("a_template.html", {
        'time':datetime.now(),
        }, context_instance=RequestContext(request))

rawDescription: Django Want to print the date & time for today


code:
from flask import Blueprint,session,render_template
from form import Test
our = Blueprint('our',__name__)
@our.route('/')
def index():
    form = Test()
    #session['name'] = 'hedi'
    if session.get('name').lower() == "morteza":
        form.name.choices = ((1,'mori'),(2,'hedi'))
    else:
        form.name.choices = ((1,'you'))
    return render_template('index.html',form=form)
    #return str(session.get('name'))

rawDescription: Access to session in flask_wtf

description: Access to session in flask_wtf


code:
import os
os.system('"C:/Temp/a b c/Notepad.exe"')

rawDescription: Using python to issue command prompts

description: Using python to issue command prompts


code: date = datetime.strptime(year+julian, "%Y%j").strftime("%Y-%d-%m")

rawDescription: Python parsing for MySQL import

description: Python parsing for MySQL import


code: {u'vrfs': {u'default': {u'routes': {u'2.2.2.2/32': {u'vias': [{u'interface': u'Ethernet4'}]}}}}}

rawDescription: Looping through a dictionary and tracking key depth


code:
for stock in stocklist:
    data = web.DataReader(stock, 'google', start, end)
    data.insert(0, 'Time', [ts.time() for ts in data.index])
    data.reset_index(inplace=True)    # make Date a proper column
    data.insert(0, 'Stock', stock)
    data.to_csv('{}.csv'.format(stock), index=False)

rawDescription: prepend a header to .csv file with python

description: Prepend a header to .csv file with python


code:
import pylab
import imageio
filename = '/tmp/file.mp4'
vid = imageio.get_reader(filename,  'ffmpeg')
nums = [10, 287]
for num in nums:
    image = vid.get_data(num)
    fig = pylab.figure()
    fig.suptitle('image #{}'.format(num), fontsize=20)
    pylab.imshow(image)
pylab.show()

rawDescription: How to read mp4 video to be processed by scikit-image?

description: Read mp4 video to be processed by scikit-image


rawDescription: How to set the screen resolution in pythoncard

description: Set the screen resolution in pythoncard


rawDescription: Couple of matplotlib newbie doubts

description: Couple of matplotlib newbie doubts


rawDescription: converting list to dictionary in Python using zip or dict function

description: Converting list to dictionary in Python using zip or dict function


code:
RDFNS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
root = lxml.etree.Element('{%s}RDF' % RDFNS, nsmap={'rdf': RDFNS})
rdf_description = lxml.etree.SubElement(
    root,
    '{%s}Description' % RDFNS,
    {"{%s}about" % RDFNS: "http://purl.org/NET/FOO"})

rawDescription: python 2.7 XML lxml namespace prefix attribute issues

description: Python 2.7 XML lxml namespace prefix attribute issues


code:
from __future__ import division, print_function

import numpy as np
import datetime as dt

# build numpy array
s = np.random.rand(90000)
l = np.random.rand(2.5E6)

# sort
s.sort()
l.sort()

# searchsorted finds where values in array2 should be inserted in array1 to
# maintain the "sortedness" of a new list
# define index locations where "s" should be inserted in "l"
indices = np.searchsorted(l,s)

# build dummy list to store "s2"
# this is faster than repeatedly resizing an array
s2 = s*0

# using "indices" determine which adjacent value is the nearest match
# need to be careful here since we cannot look "below" the first index
# nor can we look "above" the last value

d1 = dt.datetime.now()
for r in np.arange(s.shape[0]):
    ix = indices[r]

    if indices[r]==0:
        s2[ix] = l[0]
    elif indices[r]==l.shape[0]:
        s2[ix] = l[r-1]
    else:
        tmp = l[ix:ix+2]
        s2[r] = tmp[ np.abs(s[r]-tmp)==np.min(np.abs(s[r]-tmp)) ]

print('Execution time: ',dt.datetime.now()-d1)

rawDescription: python: how to find a subset of one set that is closest to another

description: Python: how to find a subset of one set that is closest to another


code: c = [a_item + [b_item] for a_item, b_item in zip(a, b)]

rawDescription: Unpack items and add a new one

description: Unpack items and add a new one


code:
from itertools import groupby

lst = [{} for _ in range(21)]  # simple testlist

def rank_it(lst,n):
    for index,d in enumerate(lst):
        rank = index/(len(lst)/n)+1
        d['rank'] = rank if rank < n else n

rank_it(lst,5)  #  add ranks
[list(g) for _,g in groupby(lst, lambda x: x['rank'])]  #group by rank

rawDescription: Assigning a a sequence number to dictionaries in a list


code:
import os
sorted(l, key=os.urandom)

rawDescription: Shuffle in Python

description: Shuffle in Python


code:
for company, data in company_data.iteritems():
    # Data is now  the inner dictionary
    for state_abbrev, values in data.iteritems():
         func1(values, dict1[states[state_abbrev]])

rawDescription: issue in processing data from a csv file and a dictionary in python

description: Issue in processing data from a csv file and a dictionary in python


code: localStorage.setItem('name', 'tom');

rawDescription: Writing to HTML5 localStorage from python/Flask app


code: df.apply(lambda x: re.sub('\s*{}$'.format(x['series']), '', x['id']), axis=1)

rawDescription: Pandas replace full word string

description: Pandas replace full word string


code:
import itertools
time1 = list(itertools.chain(*timeList))[0].split(":")[0]

rawDescription: A better way to extract data in Python

description: A better way to extract data in Python


code: d = {tuple(k): v for k,v in my_lookup}

rawDescription: Mapping list of lists to pandas Series

description: Mapping list of lists to pandas Series


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

def main():
    x, y = generate_data()
    plot(x, y).set(title='Original data')

    x, y = radial_sort_line(x, y)
    plot(x, y).set(title='Sorted data')

    plt.show()

def generate_data(num=50):
    t = np.linspace(.2, 1.6 * np.pi, num)
    x, y = np.cos(t), np.sin(t)

    # Shuffle the points...
    i = np.arange(t.size)
    np.random.shuffle(i)
    x, y = x[i], y[i]

    return x, y

def radial_sort_line(x, y):
    """Sort unordered verts of an unclosed line by angle from their center."""
    # Radial sort
    x0, y0 = x.mean(), y.mean()
    angle = np.arctan2(y - y0, x - x0)

    idx = angle.argsort()
    x, y = x[idx], y[idx]

    # Split at opening in line
    dx = np.diff(np.append(x, x[-1]))
    dy = np.diff(np.append(y, y[-1]))
    max_gap = np.abs(np.hypot(dx, dy)).argmax() + 1

    x = np.append(x[max_gap:], x[:max_gap])
    y = np.append(y[max_gap:], y[:max_gap])
    return x, y

def plot(x, y):
    fig, ax = plt.subplots()
    ax.plot(x, y, color='lightblue')
    ax.margins(0.05)
    return ax

main()

rawDescription: Numpy way to sort out a messy array for plotting


code:
#!/usr/bin/env python2.7

from numpy import copy, random, arange

random.seed(0)
data = random.randint(30, size=10**5)

d = {4: 0, 9: 5, 14: 10, 19: 15, 20: 0, 21: 1, 22: 2, 23: 3, 24: 0}
dk = d.keys()
dv = d.values()

def f1(a, d):
    b = copy(a)
    for k, v in d.iteritems():
        b[a==k] = v
    return b

def f2(a, d):
    for i in xrange(len(a)):
        a[i] = d.get(a[i], a[i])
    return a

def f3(a, dk, dv):
    mp = arange(0, max(a)+1)
    mp[dk] = dv
    return mp[a]

a = copy(data)
res = f2(a, d)

assert (f1(data, d) == res).all()
assert (f3(data, dk, dv) == res).all()

rawDescription: Fast replacement of values in a numpy array


code:
arr = np.array([5, 4, -2, 1, -2, 0, 4, 4, -6, -1])
u, indices = np.unique(arr, return_inverse=True)
u[np.argmax(np.bincount(indices))]

rawDescription: How to find most frequent values in numpy ndarray?

description: Find most frequent values in numpy ndarray


code:
class SoccerPlayer(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    team_id = db.Column(db.Integer, db.ForeignKey('Team.id'))
    stats = db.relationship("Stats", uselist=False, backref="player")

class Team(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    players = db.relationship("SoccerPlayer")

class Stats(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    player_id = db.Column(db.Integer, db.ForeignKey('SoccerPlayer.id'))
    goals_scored = db.Column(db.Integer)
    assists = db.Column(db.Integer)
    # Add more stats as you see fit

rawDescription: can I store a Dictionary as the property of an object?

description: Store a Dictionary as the property of an object


code: re.split(r',\s*', "Dogs, Cats")

rawDescription: Python Regex on comma, space

description: Python Regex on comma, space


code:
for x in xrange(mat.cols):
    for y in xrange(mat.rows):
        # multiply all 3 components by 0.5
        mat[y, x] = tuple(c*0.5 for c in mat[y, x])

        # or multiply only the red component by 0.5
        b, g, r = mat[y, x]
        mat[y, x] = (b, g, r * 0.5)

rawDescription: Opencv... getting at the data in an IPLImage or CvMat


code:
stemmer.stem('dancitization')
stemmer.stem('dancendence')
#since dancitization gives us dancit, let's try dancization to get danc
stemmer.stem('dancization')
stemmer.stem('dancation')

rawDescription: Probability count/frequency of related words?


rawDescription: Add values in two dictionaries together on same key


code:
mask = ~dataset['v3'].isnull()
dataset['v3'][mask] = enc.fit_transform(dataset['v3'][mask])

rawDescription: python - TypeError: unorderable types: str() > float()

description: Python - TypeError: unorderable types: str() > float()


code: [(u'Remaking', u'O'), (u'The', u'O'), (u'Republican', u'ORGANIZATION', u'Party', u'ORGANIZATION')]

rawDescription: Chunking Stanford Named Entity Recognizer (NER) outputs from NLTK format


code:
mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
for k, v in mydict.iteritems():
   if k == 'two':
       del mydict[k]

rawDescription: How to delete items from a dictionary while iterating over it?

description: Delete items from a dictionary while iterating over it


code:
to_produce  = 'DAP_Local'
ingredience = 'Ammonia'
print('To produce {to_produce} we need {amount} of {ingredience}'.format(
      to_produce=to_produce, ingredience=ingredience,
      amount=ConsomRatio[to_produce].get(ingredience, '0.0')))

rawDescription: Dicts in Python

description: Dicts in Python


code:
alpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
buttonFrame = Frame(self).grid(row=0, column=1)

all_buttons = dict()

for i in range(len(alpha)):

    if i <= 6:
         all_buttons[ alpha[i] ] = Button(buttonFrame, height=2, width=5, text = alpha[i], command=lambda j=i: self.letterGuess(alpha[j]))
         all_buttons[ alpha[i] ].grid(row=1, column=self.columnz(i))
    elif 6 < i <=13:
         all_buttons[ alpha[i] ] = Button(buttonFrame, height=2, width=5, text = alpha[i], command=lambda j=i: self.letterGuess(alpha[j]))
         all_buttons[ alpha[i] ].grid(row=2, column=self.columnz(i))
    elif 13 < i <=20:
         all_buttons[ alpha[i] ] = Button(buttonFrame, height=2, width=5, text = alpha[i], command=lambda j=i: self.letterGuess(alpha[j]))
         all_buttons[ alpha[i] ].grid(row=3, column=self.columnz(i))
    elif 20 < i <26:
         all_buttons[ alpha[i] ] = Button(buttonFrame, height=2, width=5, text = alpha[i], command=lambda j=i: self.letterGuess(alpha[j]))
         all_buttons[ alpha[i] ].grid(row=4, column=self.columnz(i))

rawDescription: Sneaky way of disabling a button once it's been pressed?


code:
# ...

from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__.split('.')[0])

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///path/database.db'
#app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user:pass@localhost/database'

db = SQLAlchemy(app)

class Entry(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.Text)
    text = db.Column(db.Text)

    def __init__(self, title, text):
        self.title = title
        self.text = text

    def uppercase(self):
        self.title = self.title.upper()
        self.text = self.text.upper()

rawDescription: What alterations do I need to make for my Flask python application to use a MySQL database?


code:
fig, axes = plt.subplots(nrows=4, sharex=True)

axes[0].plot(series1, color='lightblue', lw=2)
axes[0].plot(series2, color='salmon', lw=1.5)
axes[0].set(ylabel='Original Series')

axes[1].plot(diff, color='gray')
axes[1].set(ylabel='Difference')

axes[2].plot(easing, color='black', lw=2)
axes[2].margins(y=0.1)
axes[2].set(ylabel='Easing')

axes[3].plot(series1, color='lightblue', lw=2)
axes[3].plot(series3, color='salmon', ls='--', lw=2, dashes=(12,20))
axes[3].set(ylabel='Modified Series')

for ax in axes:
    ax.locator_params(axis='y', nbins=4)
for ax in axes[-2:]:
    ax.axvspan(i0, i1, color='0.8', alpha=0.5)

plt.show()

rawDescription: numpy / scipy: Making one series converge towards another after a period of time

description: Numpy / scipy: Making one series converge towards another after a period of time


code:
with open('highscores.txt', 'rb') as f:
    reader = csv.reader(f)
    scores = list(reader)

rawDescription: How to display top 10 highscores from a comma separated value (.txt) file in Python (Pygame)

description: Display top 10 highscores from a comma separated value (.txt) file in Python (Pygame)


code:
def put_to_list(num):
    items = ((0, list(reversed(range(1, num + 1)))), (1, []), (2, []))
    return items[0]

rawDescription: Appending numbers into a list in reverse


code:
kwargs = {'title' : 'mytitle',
          'age'   : 34 }

q = MyModel.query()

for kw, vals in kwargs.items():
    if not isinstance(vals, (list, tuple)):
        vals = (vals,)
    for v in vals:
        q = q.filter(ndb.GenericProperty(kw) == v)

rawDescription: NDB query filtering by property (string)


code: (square * sub3)(n)

rawDescription: How to multiply functions in python?

description: Multiply functions in python


rawDescription: SVC with class_weight='auto' fails on scikit-learn?


code:
def onClose():
    myName.pack_forget()

rawDescription: How do I get rid of a label in TkInter?

description: Get rid of a label in TkInter


code:
def test(myList = None):
    if myList is None:
        myList = []

rawDescription: Keep a structure "alive" in a function over iteration?


rawDescription: Python pandas: creating condensed dataframe


code:
def update_filters(request):
    try:
        # get POST data
        url = request.POST['form_url']
        id = url.split('/')[-2:-1][0]
        system_type = url.split('/')[-3:-2][0]

        if id is not "new":
            system_content_type = ContentType.objects.get(app_label="systems", model=system_type.rstrip('s'))
            system = system_content_type.get_object_for_this_type(id=id)
            system.set_filters(request)
        else:
            request.session['filters'] = ''
        return HttpResponse("Filters where updated.")
    except:
        return HttpResponse("Select a part and click 'Save and continue' to set the filters.")

def delete_filters(request):
    request.session['filters'] = ''
    return HttpResponse("Filters where deleted.")

rawDescription: Alternative to global variables in Django?


code: pattern = '|'.join(['(?:{})'.format(p) for p in args.patterns])

rawDescription: Take multiple patterns from cli. argparse Python3


code: response = requests.get(url, stream=True)

rawDescription: Checking if a file is being downloaded by Python Requests library


code: root.after(100, color, 'black')

rawDescription: customize tkinter menu while menu is open

description: Customize tkinter menu while menu is open


code:
res['RevID'] = res['RevID'].convert_objects(convert_numeric=True)
res

rawDescription: Merging Dataframes with Arrays?

description: Merging Dataframes with Arrays


code:
class QuestionForm(forms.Form):

    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
             initial=None, error_class=ErrorList, label_suffix=':',
             empty_permitted=False):
        super(QuestionForm, self).__init__(data, files, auto_id, prefix,
             initial, error_class, label_suffix, empty_permitted)
        self.questions = Question.objects.all()
        if self.questions:
            for question in self.question:
                self.fields['question_%s' % question.pk] =\
                    forms.ChoiceField(label=question.question_text,
                        choices=[(q.pk, q.answer) for q in question.answer_set.all()])

rawDescription: django weighted questionnaire?

description: Django weighted questionnaire


rawDescription: How to dynamically create new python class files?

description: Dynamically create new python class files


rawDescription: Using GAE Channel's from a TaskQueue

description: Using GAE Channel's from a TaskQueue


code:
colors = iter(cm.rainbow(np.linspace(0, 1, len(ys))))
for y in ys:
    plt.scatter(x, y, color=next(colors))

rawDescription: Setting different color for each series in scatter plot on matplotlib


code:
class NPC:
     def __init__(self,dialogue):
         #... set the variables ...
         self.current_question = None

     def converse(self):
         #.... do some stuff....
         self.current_question = users_choice;

rawDescription: Python tree-based chat bot

description: Python tree-based chat bot


code:
from inspect import getmodule
getmodule(sqrt)

rawDescription: How do you check in which module a function is defined? Python

description: Check in which module a function is defined? Python


code:
for key, test in tests.iteritems():

    line = '{thread} [ {run}, test-{key} ]: {url} = [{times}]\n'
    line = line.format(thread=test['thread'], run=test['run'], key=key,
        url=test['url'], times=test['times'])

    log3.append(line)

with open('log3.txt', 'a') as f:
    f.write(''.join(log3))

rawDescription: Parse data from 2 log files in Python

description: Parse data from 2 log files in Python


code: dst = cv2.applyColorMap(src, cv2.COLORMAP_RAINBOW)

rawDescription: Create colour picture from greyscale picture


code:
def nearby_spots_old(request, lat, lng, radius=5000, limit=50):
    """
    WITHOUT use of any external library, using raw MySQL and Haversine Formula
    http://en.wikipedia.org/wiki/Haversine_formula
    """
    radius = float(radius) / 1000.0

    query = """SELECT id, (6367*acos(cos(radians(%2f))
               *cos(radians(latitude))*cos(radians(longitude)-radians(%2f))
               +sin(radians(%2f))*sin(radians(latitude))))
               AS distance FROM demo_spot HAVING
               distance < %2f ORDER BY distance LIMIT 0, %d""" % (
        float(lat),
        float(lng),
        float(lat),
        radius,
        limit
    )

    queryset = Spot.objects.raw(query)
    serializer = SpotWithDistanceSerializer(queryset, many=True)

    return JSONResponse(serializer.data)

rawDescription: Returning nearby locations in Django

description: Returning nearby locations in Django


code: text = ~any_section_header + everything_up_to_the_end_of_the_line

rawDescription: pyparsing capturing groups of arbitrary text with given headers as nested lists

description: Pyparsing capturing groups of arbitrary text with given headers as nested lists


code:
import importlib
func_names = ["func1", "func2"]
operation_dispatch = {
    name : getattr(importlib.import_module(name), name)
    for name in func_names}

#usage
result = operation_dispatch[function_name](param)

rawDescription: Call a user defined function given its name as a string input to another function Python 2.7


code:
def cycle_file(filename):
    while True:
        with open(filename) as f:
            yield from f

rawDescription: Re-reading file when cycling over a file object in Python


code:
def gridgen(zmin, zmax, Nlvls):
    dlnz = (np.log(zmax) - np.log(zmin))/(Nlvls-1)
    z = np.zeros(Nlvls, dtype=float)
    z[Nlvls-1] = np.log(zmax)
    for i in range(Nlvls-2, -1, -1):
        z[i] = z[i+1] - dlnz
    z = np.exp(z)
    return z

rawDescription: Defining a function from IDL in Python

description: Defining a function from IDL in Python


code: apple, grape = itemgetter('apple', 'grape')(foodColors())

rawDescription: Assign values in returned dictionary to unique variables


code:
print >>my_out_file, "%s(%d): %s" % (bname, lineno,
                      linecache.getline(filename, lineno)),

rawDescription: Python trace module - Trace lines as they are executed, but save to file, rather than stdout


code:
[{'course_id': 1456, 'name': 'History', 'score': 56},
 {'course_id': 316, 'name': 'Science', 'score': 71},
 {'course_id': 926, 'name': 'Geography'}]

rawDescription: How to merge lists of dictionaries

description: Merge lists of dictionaries


code:
with open('c:\pull.csv', 'wb+') as f:
    csv_writer = unicodecsv.writer(f, encoding='utf-8')

    # Write a header row (do once)
    # csv_writer.writerow(["login", "title", "changed_files", "commits"])

    # Write data row
    csv_writer.writerow([changes['user']['login'], changes['title'],changes['changed_files'], changes['commits']])

rawDescription: Python: Unicode output to csv using unicodecsv


rawDescription: Highlighting a clicked line in an unfocused Tkinter text widget


code:
import functools

instC = C(5.)
meth = functools.partial(instC.withParam, 239)

rawDescription: How to bind a constant parameter in Python?

description: Bind a constant parameter in Python


code:
diffs = (current - last for current, last in
         it.izip(it.islice(entries, 1, None), entries))

rawDescription: python for loop, how to find next value(object)?

description: Python for loop, how to find next value(object)


code:
outfilename1 = 'data1-{}.csv'.format(now_str)
out_file1 = open(outfilename1, 'w')

outfilename2 = 'data2-{}.csv'.format(now_str)
out_file2 = open(outfilename2, 'w')

out_file1.write(str1)
out_file2.write(str2)

rawDescription: How Do I Output Multiple Scraped Datasets to Their Own .CSV Files in Python?


code: df2.drop('None').apply(lambda c: c / c.sum() * 100, axis=0)

rawDescription: percentage of sum in dataframe pandas

description: Percentage of sum in dataframe pandas


code:
def do_thing(dct):
    lst = dct["outer_list"]

    # Sort the nested_lists, assuming you want to sort by the numeric value of the "id" value
    for obj in lst:
        obj["nested_list"].sort(key=lambda d: int(d["id"]))

    # Sort the outer_list
    lst.sort(key=lambda d: d["name"])

    return lst

rawDescription: sort on multiple parameters in list of dictionaries/lists

description: Sort on multiple parameters in list of dictionaries/lists


code:
a
v
np.where(a == v[:,None])[1]

rawDescription: Row wise element search in an array

description: Row wise element search in an array


code:
def func(s):
    hour = int(s.split(':')[0][-2:])
    minute = int(s.split(':')[1][:2])
    suffix = s.split(':')[1][2:4]
    return [hour, minute, suffix]

answer = map(func, open_info)
print(answer)

rawDescription: Condensing Multiple List Comprehensions

description: Condensing Multiple List Comprehensions


code:
m = pd.merge(df2, df1, how='left', on=['end','start'], suffixes=['','_r'])
df2[m['pkid_r'].isnull()]

rawDescription: picking out elements based on complement of records in Python pandas

description: Picking out elements based on complement of records in Python pandas


rawDescription: Python Pandas: Get index of rows which column matches certain value


rawDescription: Python StringIO is not correctly capturing data from stderr


code:
import collections

short_data = collections.defaultdict(list)
for key, value in data.items():
    short_key = (key[0], key[1], key[3])
    short_data[short_key].extend(value)

rawDescription: Python Dictionary Trouble: Grouping by elements in tuple key


rawDescription: How to arrange a dict by value, and back again?

description: Arrange a dict by value, and back again


rawDescription: Finding the rows which has a unique column values in python


code:
from django.conf.urls import patterns, url

from myapp.views import MyView

urlpatterns = patterns('',
    url(r'^mine/$', MyView.as_view(), name='my-view'),
)

rawDescription: Django GET and POST handling methods

description: Django GET and POST handling methods


code: mysql -hlocalhost -uuser1 -ppass1

rawDescription: List species names in local MySQL EnsEMBL database via PyCogent?


code:
def function():
    pass
function = decorator(function)

rawDescription: Is a Python Decorator the same as Java annotation, or Java with Aspects?


code: nums = input('Enter some numbers: ')  # Type in [1, 2, 3]

rawDescription: user inputs ipython

description: User inputs ipython


code:
import datetime
sorted_data = sorted(data, key=lambda row: datetime.datetime.strptime(row[0], "%d/%m/%Y"))

rawDescription: Python List splitting, sorting by date, then joining


rawDescription: Printing until a specific character position in python


code: list(word)

rawDescription: Take user input and put it in a list of characters (Python 3)


code:
query = gdata.spreadsheet.service.CellQuery()
query.return_empty = 'true'

cells = _api_client.GetCellsFeed(self._key, wksht_id=self._raw_events_worksheet_id, query=query)

rawDescription: Add multiple rows into google spreadsheet using API


rawDescription: How does np.multiply work?

description: How does np.multiply work


code:
if not ():
    print('empty!')
if (1, 0):
    print('not empty!')

rawDescription: "Non-equal" or "greater than" is quicker?


code:
from jinja2 import Environment, FileSystemLoader

if local_settings.DEBUG:
    jinja2_env = Environment(loader=FileSystemLoader('views/'), cache_size=0)
else:
    jinja2_env = Environment(loader=FileSystemLoader('views/'))

def template(name, ctx):
    t = jinja2_env.get_template(name)
    return t.render(**ctx)

rawDescription: What's the best way to disable Jinja2 template caching in bottle.py?


rawDescription: python: Right Click on list menu not showing item selected

description: Python: Right Click on list menu not showing item selected


code:
import random
population=[1,2,3,4,5,6,7,8,9,10,11,12,]
ls=random.sample(population,5)
ls

rawDescription: random.sample and "selection order"

description: Random.sample and "selection order"


rawDescription: Using groupby and apply to add column to each group


code:
t = threading.Thread(target=self.workerFuncSpinner(
    taskOnDeckQueue, taskCompletionQueue, taskErrorQueue, i))
t.start()

rawDescription: Python threading issue: threads blocking each other


code:
arr=np.random.random((4,4))
arr

rawDescription: Numpy Routine for Computing Matrix Minors?


rawDescription: Selecting Unique Rows between Two DataFrames in Pandas


rawDescription: How to get values from a 2-d Array with indices

description: Get values from a 2-d Array with indices


code:
from operator import add
def func(x, y):
    return map(add, x, y[1:])
[[item[0][0]] + reduce(func, item[1:], item[0][1:])  for item in zip(*lis)]

rawDescription: merge complex matrix with python

description: Merge complex matrix with python


rawDescription: raw_input check to allow for reinitiation of same function

description: Raw_input check to allow for reinitiation of same function


code:
def function(x, a,b,c):
    #a = upper asymptote
    #b = negative = x axis displacement
    #c = negative = growth rate
    return a*(np.exp(b*(np.exp(c*x))))

rawDescription: Getting completely wrong fit from python scipy.optimize.curve_fit


code: session.execute('INSERT INTO t1 (SELECT * FROM t2)')

rawDescription: How do I INSERT INTO t1 (SELECT * FROM t2) in SQLAlchemy?


rawDescription: Python: No pass by reference.. how to do it then?


code:
import numpy as np
np.compress(sec,f)

rawDescription: Creating New Array when Second Array is > 0


code: data = json.load(filename)  # note, no `s` after `load`.

rawDescription: How to remove commas, brackets in python using regular expression?

description: Remove commas, brackets in python using regular expression


code: board = player[9]

rawDescription: Tic Tac Cover up!! Can't get the program to work correctly


code: any(map(lambda v: v in list2, list1))

rawDescription: Python - Comparing two lists

description: Python - Comparing two lists


code:
from selenium import webdriver

driver = webdriver.Chrome(service_log_path="/tmp/log")
driver.get("http://www.google.com")
driver.find_element_by_css_selector("input")
driver.quit()

rawDescription: Monitoring JSON wire protocol logs

description: Monitoring JSON wire protocol logs


code: part0, part2 = str.partition(' ')[::2]

rawDescription: How to pick certain elements of x-tuple returned by a function?

description: Pick certain elements of x-tuple returned by a function


code:
def body(line):
    global title_flag

    # skip over comments
    if line[0] == '#':
        return None, False
    # skip over blank lines
    if re.search(r'^\s+$', line):
        return None, False

    # Find the line where the title is defined
    if 'DEFINE_MENU' in line and title_flag == 0:
        type, name = line.split()
        title = name
        title_flag = 1
        return title, body(line)

    # If DEFINE_MENU is found and flag has been raised, this
    # signifies a new menu definition.
    if 'DEFINE_MENU' in line and title_flag == 1:
        return None, True

rawDescription: Is it possible to repeat an iteration of a loop?


code:
import twitter
t = twitter.Twitter(auth=twitter.OAuth(ACCESS_KEY, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET))
t.users.lookup(screen_name=SCREEN_NAME)
# returns the user object

rawDescription: Get user id from user name for twitter using python


rawDescription: Calculating the minimum distance between two DataFrames


code:
('red', 'indoors', 'bathroom')
('red', 'indoors', 'bedroom')
('red', 'indoors', 'kitchen')
('red', 'outdoors')
('blue', 'indoors', 'bathroom')
('blue', 'indoors', 'bedroom')
('blue', 'indoors', 'kitchen')
('blue', 'outdoors')
('green', 'indoors', 'forest', 'bathroom')
('green', 'indoors', 'forest', 'bedroom')
('green', 'indoors', 'forest', 'kitchen')
('green', 'indoors', 'light', 'bathroom')
('green', 'indoors', 'light', 'bedroom')
('green', 'indoors', 'light', 'kitchen')
('green', 'indoors', 'dark', 'bathroom')
('green', 'indoors', 'dark', 'bedroom')
('green', 'indoors', 'dark', 'kitchen')
('green', 'outdoors', 'forest')
('green', 'outdoors', 'light')
('green', 'outdoors', 'dark')

rawDescription: generating conditional product of lists in python (combinatorics)

description: Generating conditional product of lists in python (combinatorics)


code: import module.submodule.subsubmodule as short_name

rawDescription: Can you define aliases for imported modules in Python?

description: Define aliases for imported modules in Python


rawDescription: How to remove leading and trailing zeros in a string? Python

description: Remove leading and trailing zeros in a string? Python


code:
# syntax.py
class Block(object):
    pass
class List(object):
    pass

rawDescription: Conveniently import several classes from modules in a Python package


rawDescription: How do I access an object, knowing only its memory address and not a variable that refers to it?

description: Access an object, knowing only its memory address and not a variable that refers to it


code:
c = []

for i in a:
    if any(np.isclose(i, b)):
        c.append(i)
    else:
        c.append(0.0)

rawDescription: Python: Comparing all elements of two arrays and modifying 2nd array


rawDescription: How to transform a pair of values into a sorted unique array?

description: Transform a pair of values into a sorted unique array


code:
from collections import OrderedDict

d = OrderedDict()
for t in l:
    d.setdefault(t, 0)
    d[t] += 1

print([k+(v,) for k,v in d.items()])

rawDescription: Grouping tuples using libraries in Python


code:
def Cel2Fah(temp):
    fah = temp * 9.0/5.0 + 32

    return fah

rawDescription: python 2.7 function to convert temprature

description: Python 2.7 function to convert temprature


code:
import types
def press_zoom(self, event):
    event.key='x'
    matplotlib.backends.backend_tkagg.NavigationToolbar2TkAgg.press_zoom(self,event)
figure.canvas.toolbar.press_zoom=types.MethodType(press_zoom, figure.canvas.toolbar)

rawDescription: matplotlib forcing pan/zoom to constrain to x-axes

description: Matplotlib forcing pan/zoom to constrain to x-axes


code:
from astropy.coordinates import Angle
import astropy.units as u
import numpy as np

angles = np.array([100,200,300,400])
angles_quantity = a * u.degree # Could also be u.radian, u.arcmin, etc.
Angle(angles_quantity).wrap_at('360d')

rawDescription: How to covert np.ndarray into astropy.coordinates.Angle class?

description: Covert np.ndarray into astropy.coordinates.Angle class


code:
## [ . . . ]

class RandomSrc(BaseSource):
    def get(self):
        return random.random()

class WhateverSrc(BaseSource):
    def get(self):
        return "Foo Bar??"

def create_source(choice):
    if choice == 0:
        return ManualSrc()
    elif choice == 1:
        return RandomSrc()
    elif choice == 2:
        return WhateverSrc()
    else:
        raise ValueError('source choice parameter {} not valid'.format(choice))

rawDescription: Duck-typable classes, ABC, iheritance, __new__


code:
import re
from collections import Counter

p = re.compile('|'.join(map(re.escape, p_words)))
d = Counter(p.findall(s))
# -> Counter({'limited time offer': 2, 'cash': 2})

rawDescription: Python: How to find n-gram patterns in the text?


code: basket = dict(basket_one, **basket_two)

rawDescription: How can 2 Python dictionaries become 1?

description: How can 2 Python dictionaries become 1


code: types = Type.objects.all()

rawDescription: Python Django models execute a join query


code:
# at top of file
import heapq
#... etc

# replace greedy_set_cover
@timer
def greedy_set_cover(subsets, parent_set):
    parent_set = set(parent_set)
    max = len(parent_set)
    # create the initial heap. Note 'subsets' can be unsorted,
    # so this is independent of whether remove_redunant_subsets is used.
    heap = []
    for s in subsets:
        # Python's heapq lets you pop the *smallest* value, so we
        # want to use max-len(s) as a score, not len(s).
        # len(heap) is just proving a unique number to each subset,
        # used to tiebreak equal scores.
        heapq.heappush(heap, [max-len(s), len(heap), s])
    results = []
    result_set = set()
    while result_set < parent_set:
        logging.debug('len of result_set is {0}'.format(len(result_set)))
        best = []
        unused = []
        while heap:
            score, count, s = heapq.heappop(heap)
            if not best:
                best = [max-len(s - result_set), count, s]
                continue
            if score >= best[0]:
                # because subset scores only get worse as the resultset
                # gets bigger, we know that the rest of the heap cannot beat
                # the best score. So push the subset back on the heap, and
                # stop this iteration.
                heapq.heappush(heap, [score, count, s])
                break
            score = max-len(s - result_set)
            if score >= best[0]:
                unused.append([score, count, s])
            else:
                unused.append(best)
                best = [score, count, s]
        add_set = best[2]
        logging.debug('len of add_set is {0} score was {1}'.format(len(add_set), best[0]))
        results.append(add_set)
        result_set.update(add_set)
        # subsets that were not the best get put back on the heap for next time.
        while unused:
            heapq.heappush(heap, unused.pop())
    return results

rawDescription: Set Cover or Hitting Set; Numpy, Least element combinations to make up full set