code:
import numba

@numba.jit("f8[::1](f8[::1], f8[::1], f8[::1], f8[::1])")
def interp2(x, xp, fp, f):
    n = len(x)
    n2 = len(xp)
    j = 0
    i = 0
    while x[i] <= xp[0]:
        f[i] = fp[0]
        i += 1

    slope = (fp[j+1] - fp[j])/(xp[j+1] - xp[j])
    while i < n:
        if x[i] >= xp[j] and x[i] < xp[j+1]:
            f[i] = slope*(x[i] - xp[j]) + fp[j]
            i += 1
            continue
        j += 1
        if j + 1 == n2:
            break
        slope = (fp[j+1] - fp[j])/(xp[j+1] - xp[j])

    while i < n:
        f[i] = fp[n2-1]
        i += 1

@numba.jit("f8[:, ::1](f8[::1], f8[:, ::1], f8[:, ::1])")
def multi_interp(x, xp, fp):
    nrows = xp.shape[0]
    f = np.empty((nrows, x.shape[0]))
    for i in range(nrows):
        interp2(x, xp[i, :], fp[i, :], f[i, :])
    return f

rawDescription: Fast interpolation over 3D array for 3D origin x


code:
for char in s:
    if char not in string.ascii_letters + string.digits:
        return False

return True

rawDescription: Return True if alphanumeric (No methods or import allowed)


rawDescription: iterate through df column and return value in dataframe based on row index, column reference

description: Iterate through df column and return value in dataframe based on row index, column reference


rawDescription: Apply function to Dataframe GroupBy Object and return dataframe


code: someseq[slice(2, None)]

rawDescription: Creating a slice object in python

description: Creating a slice object in python


code:
import cv2
import numpy as np
frame1 = cv2.imread('my1.bmp')
frame2 = cv2.imread('my2.bmp')
prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)
next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)

flow = cv2.calcOpticalFlowFarneback(prvs, next, 0.5, 3, 15, 3, 5, 1.2, 0)

# Change here
horz = cv2.normalize(flow[...,0], None, 0, 255, cv2.NORM_MINMAX)
vert = cv2.normalize(flow[...,1], None, 0, 255, cv2.NORM_MINMAX)
horz = horz.astype('uint8')
vert = vert.astype('uint8')

# Change here too
cv2.imshow('Horizontal Component', horz)
cv2.imshow('Vertical Component', vert)

k = cv2.waitKey(0) & 0xff
if k == ord('s'): # Change here
    cv2.imwrite('opticalflow_horz.pgm', horz)
    cv2.imwrite('opticalflow_vert.pgm', vert)

cv2.destroyAllWindows()

rawDescription: Optical Flow using OpenCV - Horizontal and Vertical Components


code:
re.search('e', line)
             # ^^^^

rawDescription: how to give re.search() a line from a file

description: Give re.search() a line from a file


code:
class model_name(models.Model):
    _name = 'model.name'

    test_id = fields.Many2one('relation.table.name', string="Many2One Label")
    type = fields.Char(related='test_id.type', string="Type")

rawDescription: Set domain on Many2one field value in Odoo


code:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt

t = mdates.drange(dt.datetime(2011, 10, 15), dt.datetime(2011, 11, 27),
                  dt.timedelta(hours=2))
y = np.sin(t)

fig, ax = plt.subplots()
ax.plot_date(t, y, 'b-')
ax.axvspan(*mdates.datestr2num(['10/27/2011', '11/2/2011']), color='red', alpha=0.5)
fig.autofmt_xdate()
plt.show()

rawDescription: In a matplotlib plot, can I highlight specific x-value ranges?


rawDescription: How to validate image format in django ImageField

description: Validate image format in django ImageField


code:
# Simple gaussian function (just to illustrate how to define such a func)
def func(x_values, maximum_y, maximum_x, sigma):
    return maximum_y*np.exp(-(maximum_x_range-x0)**2/(2*sigma**2))

rawDescription: Fit a curve to a histogram in Python

description: Fit a curve to a histogram in Python


code:
def read_file(filename):
    file = open(filename)
    contents = map(str.strip,file.readlines())
    file.close()
    return contents

def get_column_values(col_num,lines):
    column_values = []

    for line in lines:
        if not line:
            continue

        values = line.split()

        #col_num - 1 = index of list
        #[:-1] will chop the last char i.e. comma from the string
        column_values.append(values[col_num-1][:-1])

    return column_values

def remove_duplicates(xList):
    return list(set(xList))

def write_file(filename,lines):
    file = open(filename,"w")
    for line in lines:
        file.write("%s\n" % line)
    file.close()

def main():
    lines = read_file("input.txt")

    #Work on 1st Column i.e. 0th index
    column_values = get_column_values(1,lines)
    entries = remove_duplicates(column_values)
    write_file("output.txt",entries)

main()

rawDescription: python no idea what's wrong

description: Python no idea what's wrong


code:
import pandas.tseries.offsets as offsets
pd.date_range('1/1/1940', periods=900, freq=offsets.MonthBegin())

rawDescription: Setting up an empty time series dataframe with monthly data for the FIRST day of the month


code:
ax.zaxis.set_rotate_label(False)  # disable automatic rotation
ax.set_zlabel('label text', rotation=90)

rawDescription: Rotating axes label text in 3D matplotlib


code: results, paths = zip(*((k, v) for k, v in lines.items() if keywrd in k))

rawDescription: return two lists from a list comprehension -- performance

description: Return two lists from a list comprehension -- performance


code: ''.join('%5.1f ' % n for n in s)

rawDescription: write formated file

description: Write formated file


code:
from Tkinter import *
import tkMessageBox

root = Tk()
root.title('Payroll System')
def on_printtext():
    global entryform
    strng = entryform.get()
    if strng == '1':
        tkMessageBox.showinfo(message='You typed 1')
    else:
        tkMessageBox.showinfo(message='Please type 1')

entryform = Entry(root)
entryform.pack()
submit = Button(root, text="Submit", command=on_printtext)
submit.pack()

root.mainloop()

rawDescription: Python Tkinter Use Entry Field to Create MessageBox


code:
def prepareTCPConnection(username, password):
    rc = RemoteConnection()
    def connection_handler():
        # perform the connection, and setup results
        rc.setResults(results)
    rc.function = connection_handler
    return rc

rawDescription: Python decorate function with class and access class instance


code:
def do_tasks(puzzle, name):
    print('Number of times', name, 'occurs left-to-right: ', end='')
    return lr_occurrences(puzzle, name)

rawDescription: Calling a function inside a function

description: Calling a function inside a function


code: list(zip(*ll))

rawDescription: Creating dictionary with key/values coming from a list of lists


rawDescription: How to create lists from every item of an existing list in python 2.7.11?

description: Create lists from every item of an existing list in python 2.7.11


code: df

rawDescription: how to use word_tokenize in data frame

description: Use word_tokenize in data frame


code:
from __future__ import print_function
import time
import gmpy2

def prime_numbers(limit=1000000):
    '''Prime number generator. Yields the series
    2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ...
    using Sieve of Eratosthenes.
    '''
    yield 2
    sub_limit = int(limit**0.5)
    flags = gmpy2.xmpz(1)
    # pre-allocate the total length
    flags.bit_set((limit>>1)+1)
    f_scan0 = flags.bit_scan0
    current = 0
    while True:
        current += 1
        current = f_scan0(current)
        prime = 2 * current + 1
        if prime > limit:
            break
        yield prime
        if prime <= sub_limit:
            flags.bit_set(slice(2*current*(current+1), limit>>1, prime))

start = time.time()
result = list(prime_numbers(1000000000))
print(time.time() - start)

rawDescription: Speed up bitstring/bit operations in Python?


rawDescription: parallelize recursion python

description: Parallelize recursion python


code:
class MetaClass(type):
    @property
    def f(cls):
        return cls._f

class MyClass(object):
    __metaclass__ = MetaClass

    def __init__(f):
        self._f = f

rawDescription: Idiom to define a class property

description: Idiom to define a class property


code:
def page_parser(self, response):
      sites = hxs.select('//div[@class="row"]')
      items = []

      request = Request("http://www.example.com/lin1.cpp", callback=self.parseDescription1)
      request.meta['item'] = item
      yield request

      request = Request("http://www.example.com/lin1.cpp", callback=self.parseDescription2, meta={'item': item})
      yield request

      yield Request("http://www.example.com/lin1.cpp", callback=self.parseDescription3, meta={'item': item})

def parseDescription1(self,response):
            item = response.meta['item']
            item['desc1'] = "test"
            return item

def parseDescription2(self,response):
            item = response.meta['item']
            item['desc2'] = "test2"
            return item

def parseDescription3(self,response):
            item = response.meta['item']
            item['desc3'] = "test3"
            return item

rawDescription: How can i use multiple requests and pass items in between them in scrapy python

description: Use multiple requests and pass items in between them in scrapy python


code:
# Page begins without a number suffix.
number = None
while True:
    # Determine URL.
    url = 'http://www.google.com/page'
    if number is not None:
        # Don't add number suffix for first page.
        url += str(number)

    # Request page.
    page = requests.get(url)

    # Handle page.
    # ...
    if done_handling_pages:
        break

    # Increment number for next page.
    if number is None:
        # The starting number for the second page.
        number = 1
    else:
        # Increment page number by 1 after second page.
        number += 1

rawDescription: request url with number increase

description: Request url with number increase


code:
import pymongo
conn = pymongo.MongoClient()
db = conn.test #test is my database
col = db.spam #Here spam is my collection
cur = col.find()
cur
for doc in cur:
    print(doc)

rawDescription: How to convert a pymongo.cursor.Cursor into a dict?

description: Convert a pymongo.cursor.Cursor into a dict


code:
answer = {}
with open('path/to/file') as infile:
    for line in infile:
        key, value = line.strip().split()
        if key not in answer:
            answer[key] = []
        answer[key].append(value)

rawDescription: Combining the use of update and append for dictionaries


code: df.columns = [c.lower() for c in df.columns]

rawDescription: Building a dataframe in an efficient way from dictionary


code:
from collections import namedtuple
RecordLayout = namedtuple('RecordLayout',['field1','field2','field3',...])
def process( aLine ):
    fields = ( aLine[:10], aLine[10:20], aLine[20:30], ... )
    record = RecordLayout( fields )
    ...

rawDescription: What is the best file parsing solution for converting files?


code:
from django.views.generic import TemplateView

urlpatterns = patterns('',
    url(r'^profile/', TemplateView.as_view(template_name='profile.html'),
                      name='profile'),
)

rawDescription: Django: Loading another template on click of a button


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

class HackerNewsItem(scrapy.Item):
    title = scrapy.Field()
    comment = scrapy.Field()

class HackerNewsSpider(CrawlSpider):
    name = 'hackernews'
    allowed_domains = ['news.ycombinator.com']
    start_urls = [
        'https://news.ycombinator.com/'
    ]
    rules = (
        # Follow any item link and call parse_item.
        Rule(LinkExtractor(allow=('item.*', )), callback='parse_item'),
    )

    def parse_item(self, response):
        item = HackerNewsItem()
        # Get the title
        item['title'] = response.xpath('//*[contains(@class, "title")]/a/text()').extract()
        # Get the first words of the first comment
        item['comment'] = response.xpath('(//*[contains(@class, "comment")])[1]/font/text()').extract()
        return item

rawDescription: scrapy crawlspider output

description: Scrapy crawlspider output


code:
from main.models import ImageTest
ImageTest.objects.all()[0].photo.url

rawDescription: image.url returns local full path in view.py Django 1.6

description: Image.url returns local full path in view.py Django 1.6


code: m.sum() - m.trace()

rawDescription: Addition of values in a 10x10 python pandas dataframe excluding the diagonal


code:
from collections import defaultdict
from itertools import groupby, imap

d = defaultdict(list)
with open("doc1") as f,open("doc2") as f2:
    values = map(float, f2.read().split())
    for line in f:
        if line.strip() and not line.startswith("TOPIC"):
            name, val = line.split()
            d[name].append(float(val))

for k,v in d.items():
    print("Prob for {} is {}".format(k ,sum(i*j for i, j in zip(v,values)) ))

rawDescription: How to determine probability of words?

description: Determine probability of words


code:
def get_tags(s, open_delim  ='{{',
                close_delim ='}}' ):

   while True:

      # Search for the next two delimiters in the source text
      start = s.find(open_delim)
      end   = s.find(close_delim)

      # We found a non-empty match
      if -1 < start < end:

         # Skip the length of the open delimiter
         start += len(open_delim)

         # Spit out the tag
         yield s[start:end].strip()

         # Truncate string to start from last match
         s = s[end+len(close_delim):]

      else:
         return

rawDescription: Split tags in python

description: Split tags in python


rawDescription: Parsing apache log files

description: Parsing apache log files


rawDescription: Minimum lenght of string that match a regex


code:
#!/usr/bin/env python

import sys
from collections import Counter
from itertools import islice
from pprint import pprint

def split_every(n, iterable):
    i = iter(iterable)
    piece = ''.join(list(islice(i, n)))
    while piece:
        yield piece
        piece = ''.join(list(islice(i, n)))

def main(text):
    """ return ngrams for text """
    freqs = Counter()
    for pair in split_every(2, text): # adjust n here
        freqs[pair] += 1
    return freqs

if __name__ == '__main__':
    with open(sys.argv[1]) as handle:
        freqs = main(handle.read())
        pprint(freqs.most_common(10))

rawDescription: NLTK makes it easy to compute bigrams of words. What about letters?


rawDescription: How to create a binary column a timedelta and a list of bins

description: Create a binary column a timedelta and a list of bins


code:
{"setup": "test", "punchline": "ok", "numOfRatings": 0, "sumOfRatings": 0}
{"setup": "test2", "punchline": "ok2", "numOfRatings": 0, "sumOfRatings": 0}

rawDescription: How to get values of one key from multiple dictionaries in python?

description: Get values of one key from multiple dictionaries in python


code:
(x for x in (1, 2, 3))
gen = (x for x in (1, 2, 3))
next(gen)  # Advance the generator 1 position.
next(gen)  # Advance the generator 1 position.
next(gen)  # Advance the generator 1 position.
next(gen)  # StopIteration is raised when there are no more items.

rawDescription: What is an expression such as [d[k] for k in d] called?


rawDescription: Django: Lookup by length of text field

description: Django: Lookup by length of text field


code: cast.query('title == "Hamlet" & year == 1921')

rawDescription: Can Pandas infer DataFrame names?

description: Can Pandas infer DataFrame names


rawDescription: Convert function arguments to lists

description: Convert function arguments to lists


code:
p = Parser()
p.parseFile()

rawDescription: Python classmethod and(?) instancemethod


rawDescription: Add reply to address to django EmailMultiAlternatives


code:
def _reduce_method_descriptor(m):
    return getattr, (m.__objclass__, m.__name__)

import copyreg
copyreg.pickle(type(set.union), _reduce_method_descriptor)

rawDescription: Pickling method descriptor objects in python


code:
df_wanted = pd.pivot_table(
    df_orig,
    index=['AN', 'Bincode', 'BC_all'],
    columns=['Treatment', 'Timepoint'],
    values=['RIA_avg', 'sum14N_avg']
)

rawDescription: Python Pandas DataFrame how to Pivot

description: Python Pandas DataFrame how to Pivot


code:
t = [["a", "b"], ["c", "d"], ["a", "e"], ["f", "g"], ["c", "d"], ["e","a"]]
st = set()
t[:] = (st.add(frozenset(sub)) or sub for sub in t if frozenset(sub) not in st)

print(t)

rawDescription: Removing duplicate lists within another list


rawDescription: python convert to binary and keep leading zeros

description: Python convert to binary and keep leading zeros


code:
def add_col(df, col_name, col_entry):
    df = df.copy() # so as not to change df_lunch etc.
    df[col_name] = col_entry
    return df

rawDescription: Pandas append data frames, add a field, and then flood the field with a default value?


code:
s = "<sometag>this is stuff<othertag>this is other stuff<closetag>"

d = {'othertag': 'blah'}

#this doesn't work because `group` returns the whole match, including non-groups
re.sub(r'<(\w+)>', lambda m: d.get(m.group(), m.group()), s)
Out[23]: '<sometag>this is stuff<othertag>this is other stuff<closetag>'

#this output isn't exactly ideal...
re.sub(r'<(\w+)>', lambda m: d.get(m.group(1), m.group(1)), s)
Out[24]: 'sometagthis is stuffblahthis is other stuffclosetag'

#this works, but is ugly and hard to maintain
re.sub(r'<(\w+)>', lambda m: '<{}>'.format(d.get(m.group(1), m.group(1))), s)
Out[26]: '<sometag>this is stuff<blah>this is other stuff<closetag>'

#lookbehind/lookahead makes this nicer.
re.sub(r'(?<=<)(\w+)(?=>)', lambda m: d.get(m.group(), m.group()), s)
Out[27]: '<sometag>this is stuff<blah>this is other stuff<closetag>'

rawDescription: Python Regex Sub - Use Match as Dict Key in Substitution


code:
def main():
    print("Sum-of-the-Years'-Digits Method")

    years = 15
    sum_of_years = years * (years + 1) // 2    # = sum(1..years)
    initial_value = 10000000

    value = initial_value
    for year in range(years):
        depr = (years - year) / sum_of_years * initial_value
        value -= depr
        print("End of year {}: depreciation = {:0.2f}, new value = {:0.2f}".format(year + 1, depr, value))

if __name__=="__main__":
    main()

rawDescription: how to write a program

description: Write a program


code:
a = [1, 2, 3]

import functools
map(functools.partial(add, y=2), a)

import itertools
map(add, a, itertools.repeat(2, len(a)))

rawDescription: How to do multiple arguments to map function where one remains the same in python?

description: Do multiple arguments to map function where one remains the same in python


code:
def something(self):
    return 42
something = property(something)

rawDescription: Can I see what a Python decorator does to my code?

description: See what a Python decorator does to my code


code: numpy.split(seq, 4)

rawDescription: Separate a list into four parts based on percentage even if the list is not divisible by 10. Python


code: list_of_ids_matching_query = list(Item.objects.filter(my_field = a_value).values_list('id', flat=True))

rawDescription: Django code to get IDs from queryset, shuffle IDs, and query database in shuffled order


code:
from itertools import filterfalse

def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in filterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

rawDescription: How to divide a list in python?

description: Divide a list in python


rawDescription: Python: Replace value with the value from a dictionary key value pair


code: from app import testingA

rawDescription: Python creating a module

description: Python creating a module


rawDescription: How does one convert a .NET tick to a python datetime?

description: Convert a .NET tick to a python datetime


code:
nt = [('left', int), ('right', int)]
n
out = np.array(np.zeros(n.shape[0]),nt)
out
out['left']=n[:,0]
out['right']=n[:,1]
out
out['left']

rawDescription: Convert numpy array to numpy record array


code: df.apply(lambda x: x['w' + str(x.year)], axis=1)

rawDescription: pandas: conditionally return a column's value

description: Pandas: conditionally return a column's value


rawDescription: filter by array numpy

description: Filter by array numpy


code:
has_repeats([1, 2, 3, 4, 3])
True

has_repeats([1, 2, 3, 4, 0])
False

rawDescription: Python recursive no 'in' work around

description: Python recursive no 'in' work around


code:
for obj in queryset:
    status = obj.status

rawDescription: How do I check the value of a field in a custom action in Django admin?

description: Check the value of a field in a custom action in Django admin


code:
import os.path

BASE = os.path.dirname(os.path.abspath(__file__))

rawDescription: Relative paths approach (python)

description: Relative paths approach (python)


code: a(False) or (b(False),a(False))[0] or (c(True),b(False),a(False))[0]

rawDescription: Pythonic way to "run X before Y if Y fails"?


code:
keyword = 'MyTest' # Later I want to pull this iterating through a list
key = 'test1'
sections = {keyword: {}}
sections[keyword][key] = 'Some value'

print(sections)
{'MyTest': {'test1': 'Some value'}}

rawDescription: Defining a nested dictionary in python

description: Defining a nested dictionary in python


code: default = MyClass()

rawDescription: alternate for multiple constructors

description: Alternate for multiple constructors


code:
def get_collapsed_ranges(ranges):
    ranges = iter(sorted(ranges))
    current_range = next(ranges)
    for start, end in ranges:
        if start > current_range[1]:
            yield current_range
            current_range = [start, end]
        elif end > current_range[1]:
            current_range[1] = end
    yield current_range

rawDescription: Finding total duration in time series data without overlap


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

# Generate some data...
gray_data = np.arange(10000).reshape(100, 100)

masked_data = np.random.random((100,100))
masked_data = np.ma.masked_where(masked_data < 0.9, masked_data)

# Overlay the two images
fig, ax = plt.subplots()
ax.imshow(gray_data, cmap=cm.gray)
ax.imshow(masked_data, cmap=cm.jet, interpolation='none')
plt.show()

rawDescription: Setting Transparency Based on Pixel Values in Matplotlib


rawDescription: Calling specific version of python from PHP


code:
import os, stat

def is_stdin_a_file():
    status = os.fstat(0)
    return stat.S_ISREG(status.st_mode)

rawDescription: Python - stdin - how to recognize the source of the input?


code:
def edit_user (request, id):
    current_user = request.user
    if current_user.is_superuser:
        ...

rawDescription: Edit user profiles form without using django admin


code:
from collections import namedtuple
from datetime import datetime
Employee = namedtuple('Employee', 'id manager user contact')
Person = namedtuple('Person', 'first_name last_name')
Account = namedtuple('Account', 'username password last_login')
Contact = namedtuple('Contact', 'phone_number email')
data = [
    Employee(0, Person('Alice', 'Brown'),
             Account('abrown', 'secret', datetime(2013, 3, 3)),
             Contact('5551234', 'abrown@example.com')),
    Employee(1, Person('Bob', 'Jones'),
             Account('bjones', 'safe', datetime(2013, 3, 3)),
             Contact('5555678', 'bjones@example.com')),
    Employee(2, Person('Carol', 'Smith'),
             Account('csmith', 'hidden', datetime(2013, 3, 3)),
             Contact('5559012', 'csmith@example.com'))]

rawDescription: Django/Jinja2 : Generate (data for) CSV via template syntax


code:
with open(filename,'r+') as fr,open(filename,'r+') as fw:
    for line in fr:
        x = line.find('order')
        fw.write(line if x==-1
                 else line[0:x]+'\n' if '\n' in line
                 else line[0:x])
    fw.truncate()

rawDescription: Python: Modifying text file after certain character


code: from subdirectory import foo

rawDescription: How to do imports in python?

description: Do imports in python


rawDescription: Python regular expression to remove space and capitalize letters where the space was?


code: dataframe.to_csv('./my_file.csv', mode = 'a')

rawDescription: pandas to_csv comma were replace with a

description: Pandas to_csv comma were replace with a


code:
import argparse

if __name__ == '__main__':
    parser=argparse.ArgumentParser()
    parser.add_argument('locations', nargs = '+')
    args=parser.parse_args()
    print(args.locations)

rawDescription: Python CLI Menu

description: Python CLI Menu


code:
bstring=b"Hello World"
list( bstring)

rawDescription: Working with bit streams

description: Working with bit streams


rawDescription: Copying file content to multi-dimensional list in Python


code:
['q//Attachments/Swoop_coverletter_311386_20120103.doc',
 'q//Attachments/Swoop_reSume_311386_20120103.doc',
 'q//Attachments/Swoop_Resume_311386_20100901.doc',
 'q//Attachments/Swoop_coverletter_311386_20100901.doc',
 'q//Attachments/Swoop_RESUME_311386_20091012.doc',
 'q//Attachments/Swoop_coverletter_311386_20091012.doc',
 '']

rawDescription: Python sorting array according to date

description: Python sorting array according to date


code:
import sys
sys.modules['project'] = sys.modules.pop('temp/a40bd22344')

rawDescription: Override namespace in Python

description: Override namespace in Python


rawDescription: How to use list (or tuple) as String Formating value

description: Use list (or tuple) as String Formating value


code:
def recursive_get(d, *keys):
    return reduce(lambda c, k: c.get(k, {}), keys, d)

rawDescription: Is there a recursive version of Python's dict.get() built-in?


code:
import itertools
# Example: line = ['A','B','%']
def line_permutations(line):
   if '%' not in line:
       return [line]
   line.remove('%') # use copy.copy if you don't want to modify your matrix here
   return (line[:i] + ['%'] + line[i:] for i in range(len(line) + 1))

rawDescription: Grid Permutation Algorithm - Fixed Row Order


code: self.c.create_image(0, 0, anchor=NW, image=self.c.photo)

rawDescription: Pixel Manipulation via GUI in Python (poss PIL, Tkinter)


code:
df.groupby(["company", "period"])["revenue"].transform(sum)
df.groupby(["company", "period"])["revenue"].transform(sum) != 0

rawDescription: Remove rows from dataframe that sum to zero


code:
def __iter__(self):
    return iter(self.users)

rawDescription: Python newbie class design question

description: Python newbie class design question


code: all_the_numbers = [int(s) for s in integer.finditer(expression)]

rawDescription: Retrieving a full number

description: Retrieving a full number


code: output_lines = [i for i in re.split(r'\n', output) if re.search("Lorem",i)]

rawDescription: Regex returns text of every line with match, when text is inside variable


code: print("Monthly Total: $", total, sep='')

rawDescription: How to change value of comma in python?

description: Change value of comma in python


code:
import os
os.system("./x")
quit()

rawDescription: writing Python shell output to file

description: Writing Python shell output to file


rawDescription: Auto logout/destroy session after Password Change in Django


rawDescription: i am trying send email using web2py with gmail and using smtp setting i have attached all code

description: I am trying send email using web2py with gmail and using smtp setting i have attached all code


code:
service = build("your_api", "your_api_version", http=http,
  discoveryServiceUrl=("https://yourapp.appspot.com/_ah/api/discovery/v1/"
                       "apis/{api}/{apiVersion}/rest"))

rawDescription: Consuming GAE Endpoints with a Python client


code:
x = GetData(df)
x.data

rawDescription: Python 3.5 - Pandas - Call a method with a for loop from another method


code:
class ChangingAttribute(object):
    @property
    def n(self):
            self._n += 1
            return self._n
    def __init__(self):
            self._n = 0
foo = ChangingAttribute()
foo.n
foo.n
foo.n
foo.n is foo.n
foo.n

rawDescription: Why is a method not identical to itself?

description: Why is a method not identical to itself


code:
import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))

rawDescription: Total time for executing the code--python


code: ds.div(ds['sum'], axis=0)

rawDescription: pandas dataframe create new columns and fill with calculated values from same df

description: Pandas dataframe create new columns and fill with calculated values from same df


code:
df = df.set_index(['Id', 'appName'], append=True).unstack()
df.columns = ['{}{}'.format(name, id) for id, name in df.columns]

rawDescription: Pandas rename/transpose column using value from another column


rawDescription: Order mapping - more efficient Python solution for sorting?


code:
from collections import OrderedDict

Et_OD = OrderedDict(line.strip().split('\t') for line in open('Ethanol_rivacombined.txt'))

with open("compare.txt","w+") as output_doc:
    for line in open('Sucrose_rivacombined.txt'):
        key,val = line.strip().split('\t')
        line_out = '\t'.join((key,val,Et_OD.pop(key,'ND')))
        output_doc.write(line_out+'\n')

    for key,val in Et_OD.items():
        line_out = '\t'.join((key,'ND',val))
        output_doc.write(line_out+'\n')

rawDescription: Efficiency of comparing two dictionaries


code:
if __name__ == '__main__':
    import sys
    if "-background" in sys.argv:

        import background
        background.main()

    else:
        main() #camelot's main

rawDescription: How do I schedule my desktop application(PyQt) to send emails at some intervals

description: Schedule my desktop application(PyQt) to send emails at some intervals


code:
with open('output.file','w') as f:
    f.write(foo)

rawDescription: Python: how to create a new file and write contents of variable to it?


rawDescription: How to reference a regex match as a variable in python

description: Reference a regex match as a variable in python


rawDescription: Extract LSB bit from a Byte in python

description: Extract LSB bit from a Byte in python


code:
for meth, timestamp in zip([Day.SetSunRise, Day.SetSunSet], [sunrise, sunset]):
    meth(someday, timestamp)

rawDescription: How do I refer indirectly to a method defined in a class when I have multiple ojects

description: Refer indirectly to a method defined in a class when I have multiple ojects


code:
import pandas.rpy.common as com

def get_labels(filename):
    w = com.robj.r('attr(foreign::read.spss("%s"), "variable.labels")' % filename)
    w = com.convert_robj(w)
    return w

rawDescription: How to preserve Labels when SPSS file (.sav) imported into pandas via rpy?

description: Preserve Labels when SPSS file (.sav) imported into pandas via rpy


code: df['running total'] = df['data'].cumsum()

rawDescription: Spreadsheet Manipulation Tricks w/ Python's Pandas


code:
fig = plt.figure()
data = (0, 2, 3, 5, 5, 5, 9, 7, 8, 6, 6)

ax = fig.add_subplot(1, 1, 1)
ax.plot(data, 'r-', linewidth=4)
ax.axvline(x=5, ymin=0, ymax=4.0 / max(data), linewidth=4)
ax.text(5, 4, 'your text here')
fig.show()

rawDescription: Using matplotlib to annotate certain points


code: score += get_score(child)*.1

rawDescription: Calculate score in a pyramid score system


code:
def get_queryset(self):
    form = TagForm(self.request.GET)
    if form.is_valid():
        context = RequestContext(self.request)
        # set self.object to the "tag"
        self.object = form.cleaned_data['tag']
        return self.send_results(self.object)
    else:
        # set self.object to None since the form is not validated
        self.object = None
        return Fact.objects.all()

def get_context_data(self, **kwargs):
    context = super(AllView, self).get_context_data(**kwargs)
    if 'TagForm' not in context:
        context['TagForm'] = TagForm()
    # put self.object in the context dict
    context['tag'] = self.object
    return context

rawDescription: Modify context after using form

description: Modify context after using form


code: columns = [(item.name, item.type) for item in my_table.c.values()]

rawDescription: column names and types for insert operation in sqlalchemy

description: Column names and types for insert operation in sqlalchemy


rawDescription: Distance between numpy arrays, columnwise


code:
def key(x):
    return int(x.split()[0])

rawDescription: Merging text files in ascending order of their contents


code:
def checkprime(n):
    # Trial division
    for i in range(2,int(sqrt(n)+1)):
        if n/i == int(n/i):
            # Number gives a remainder upon division and therefore is not prime
            isprime = False
            break
        else:
            isprime = True

rawDescription: Why does my Python function work in the console, but not when called within code?


code:
# assume driver is an instance of WebDriver
# NOTE: this code is untested
driver.find_element_by_xpath(".//a[@href='http://www.testsite.com/pageOne.html']")

rawDescription: Python selenium webdriver click functionality


code:
users = [User(x, 'name_{}'.format(x)) for x in xrange(5)]
ids = set(u.id for u in users)

for x in xrange(5):
    i = randint(2,6)
    if i in ids:
        print("User id already exists: {}".format(i))
    else:
        print("{} is not in users list. Creating new user with id: {}".format(i, i))
        ids.add(i)
        users.append(User(i, 'new_user{}'.format(i)))

rawDescription: Using __contains__ on a list of custom class objects


code:
import numpy as np
import ctypes as C
import cv2

libmog = C.cdll.LoadLibrary('path/to/libmog2.so')

def getfg(img):
    (rows, cols) = (img.shape[0], img.shape[1])
    res = np.zeros(dtype=np.uint8, shape=(rows, cols))
    libmog.getfg(img.shape[0], img.shape[1],
                       img.ctypes.data_as(C.POINTER(C.c_ubyte)),
                       res.ctypes.data_as(C.POINTER(C.c_ubyte)))
    return res

def getbg(img):
    (rows, cols) = (img.shape[0], img.shape[1])
    res = np.zeros(dtype=np.uint8, shape=(rows, cols, 3))

    libmog.getbg(rows, cols, res.ctypes.data_as(C.POINTER(C.c_ubyte)))
    return res

if __name__ == '__main__':
    c = cv2.VideoCapture(0)
    while 1:
        _, f = c.read()
        cv2.imshow('f', f)
        cv2.imshow('fg', getfg(f))
        cv2.imshow('bg', getbg(f))
        if cv2.waitKey(1) == 27:
            exit(0)

rawDescription: Get background model from BackgroundSubtractorMOG2 in python


code:
from sklearn.naive_bayes import MultinomialNB
clf = MultinomialNB().fit(X_train, y_train)

rawDescription: Text Categorization Python with pre-trained data


rawDescription: python - filter minimum element for given condition

description: Python - filter minimum element for given condition


rawDescription: How to append a vector to a matrix in python

description: Append a vector to a matrix in python


code:
class GrowingList(list):
    def __setitem__(self, index, value):
        if index >= len(self):
            self.extend([None]*(index + 1 - len(self)))
        list.__setitem__(self, index, value)

rawDescription: Automatically growing lists in Python

description: Automatically growing lists in Python


rawDescription: split a 256 bit hash into 32 bit prefix in python

description: Split a 256 bit hash into 32 bit prefix in python


code:
df = pd.DataFrame([1, 2, np.inf, -np.inf])
df.replace([np.inf, -np.inf], np.nan)

rawDescription: dropping infinite values from dataframes in pandas?

description: Dropping infinite values from dataframes in pandas


code:
from string import Formatter
a = 'add {new} sentence {with} this word'
[i[1] for i in Formatter().parse(a) if i[1]]

rawDescription: Python regex to match all words in {}

description: Python regex to match all words in {}


code:
from itertools import islice
from string import ascii_lowercase
print(list(islice(generate_strings("xyzzy", None, ascii_lowercase), 5)))

rawDescription: Generating a list of combinations with repetition... with a twist


code:
tags = session.query(Tag).join(
    Tag.photo, Photo.user
).filter(User.id == specific_user_id)

for tag in tags:
    session.delete(tag)

session.commit()

rawDescription: How to create an SQLAlchemy nested filter

description: Create an SQLAlchemy nested filter


code:
import networkx as nx
G=nx.empty_graph()
G.add_edge(1,2)
G.add_edge(2,3)
G.add_edge(4,5)
nx.path.bidirectional_dijkstra(G,1,2)
nx.path.bidirectional_dijkstra(G,1,3)
nx.path.bidirectional_dijkstra(G,1,4)
nx.path.bidirectional_dijkstra(G,1,5)

rawDescription: Python: How to find if a path exists between 2 nodes in a graph?


code:
import datetime
epoch_start = datetime.datetime(1601, 1, 1)
delta = datetime.timedelta(microseconds=12979264931952304)
epoch_start + delta

rawDescription: Convert Long Int Timestamp to Date/Time

description: Convert Long Int Timestamp to Date/Time


code:
# The list defined above
lista = [a,b,c,d]

# Sorted from least to greatest absolute value
sorted_abs_list = sorted(map(abs, lista))

# Sorted from greatest to least absolute value
sorted_abs_list = sorted(map(abs, lista), reverse=True)

rawDescription: How to sort a list and put it in absolute value

description: Sort a list and put it in absolute value


rawDescription: How do I organize data in alphabetical order?

description: Organize data in alphabetical order


code:
import time, calendar
sample = '2014-04-11 10:13:36'
int(time.mktime(time.strptime(sample, pattern)))
int(calendar.timegm(time.strptime(sample, pattern)))

rawDescription: Epoch time is one hour out from UTC, should be UTC+1


rawDescription: return an array instead of a tuple from a NumPy function

description: Return an array instead of a tuple from a NumPy function


rawDescription: write 5M data to a csv file using file write operation

description: Write 5M data to a csv file using file write operation


code: res_list = [x for x,_ in rows]

rawDescription: Get the first element of each tuple in a list in Python


code:
import xml.etree.cElementTree as ET
root = ET.XML('<root><elm key="value">Some text</elm>More text</root>')
list(root.itertext())
root = ET.XML('<root>Text 1<elm key="value">Text</elm>Text 2<elm2 />Text 3</root>')
list(root.itertext())

rawDescription: How to get all text children of an element in cElementTree?

description: Get all text children of an element in cElementTree


code:
import numpy
from matplotlib import pyplot

# Enable interactive mode
pyplot.ion()

# Draw the grid lines
pyplot.grid(True)

# Numbers from -50 to 50, with 0.1 as step
xdomain = numpy.arange(-50,50, 0.1)

# Plots a simple linear function 'f(x) = x'
pyplot.plot(xdomain, xdomain)
# Plots 'sin(x)'
pyplot.plot(xdomain, numpy.sin(xdomain))

# 'linear' is the default mode, so this next line is redundant:
pyplot.xscale('linear')

rawDescription: What is the difference between 'log' and 'symlog'?


code: print(df)

rawDescription: Extract nested JSON embedded as string in Pandas dataframe


code: df["ANI/IP"].str.extract(r'(\d{10})')  # before overwriting!

rawDescription: Replacing pandas column with a subset of itself through regex


code:
from mercurial import ui, hg
from mercurial.node import hex

repo = hg.repository('/path/to/repo/root', ui.ui())
fctx = repo.filectx('/path/to/file', 'tip')
hexnode = hex(fctx.node())

rawDescription: Mercurial scripting with python

description: Mercurial scripting with python


code: logger.error('oops caused by %s', exc)

rawDescription: Logging Format Interpolation

description: Logging Format Interpolation


code:
with open('csv.csv', 'w') as f:
    f.write(df.to_string())

rawDescription: Printing to CSV file with automatic width


code: am=np.ma.masked_where(a!='', a)

rawDescription: Python - slice array until certain condition is met


code:
OperatorFunctions = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.div,
    # etc
}

rawDescription: Python operators

description: Python operators


rawDescription: How do you multiply the first element in a list by a number (in a list of lists) in Python?

description: Multiply the first element in a list by a number (in a list of lists) in Python


code:
from urllib2 import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://finance.yahoo.com/q?s=AAPL&q1=1")
soup = BeautifulSoup(html)

for data in soup.find_all('td', class_="yfnc_tabledata1")[0:6]:
    if data.parent.name == "tr":
            print (data.text)

rawDescription: Python webscrape text inside of multiple tags


code:
import numpy as np
LL = np.array(["A", "B", "C"])
ind = np.ma.masked_array([True, False, True])
LL[ind]

rawDescription: Logical vector as index in Python?

description: Logical vector as index in Python


code:
class MyDelegate(QItemDelegate):
    def __init__(self):
        QItemDelegate.__init__(self)

    def sizeHint(self, option, index):
        return QSize(32,32)

rawDescription: How to set the icon-size in a QTreeWidget?

description: Set the icon-size in a QTreeWidget


code:
l = [1,2,3]
" ".join([str(i) for i in l])
" ".join(map(str, l))

rawDescription: How to turn a list/tuple into a space separated string in python using a single line?

description: Turn a list/tuple into a space separated string in python using a single line


code: list(map(lambda s: s+(100 if s < 4 else 1), a))

rawDescription: Fastest way to modify list values with condition python


code:
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, resource):
        resource = str(urllib.unquote(resource))
        blob_info = blobstore.BlobInfo.get(resource)
        self.send_blob(blob_info,save_as=True)

rawDescription: Downloaded filename with Google App Engine Blobstore


code:
from datetime import date, datetime
def spanning_months(start, end):
    assert start <= end
    current = start.year * 12 + start.month - 1
    end = end.year * 12 + end.month - 1
    while current <= end:
        yield date(current // 12, current % 12 + 1, 1)
        current += 1

rawDescription: Get the difference between dates in the form of list years and months


code: ['categorya.1.file', 'categoryb.1.file', 'categoryc.1.file', 'categorya.2.file']

rawDescription: Python Rearrange order of a list according to element contents


rawDescription: Set of float numbers, append numbers to empty list in sets . Python


rawDescription: how to dynamically read a specific cell value in a table using selenium and python

description: Dynamically read a specific cell value in a table using selenium and python


code: {p.id: {name: p.name, description: p.description}  for p in products.all()}

rawDescription: Python create nested dictionary from list


code:
data = "[53, 2]"
data_stripped = data.strip('[]')  # remove '[' and ']'s from the ends
data_split = data.split(',')  # split into a list containing each entry
data_final = [int(x) for x in data_split]  # convert strings to ints

rawDescription: Assign part of a string to a variable [Python]


code: deltas = [b - a for a, b in zip(positions, positions[1:])]

rawDescription: How to find recurring patterns on a hexdump?

description: Find recurring patterns on a hexdump


code:
# pass scroll if you want to scroll somewhere
return render_template('search.html', scroll='something')

rawDescription: Automatically scroll to a div when Flask returns rendered template


code:
# these are matplotlib.patch.Patch properties
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)

# place a text box in upper left in axes coords
ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14,
    verticalalignment='top', bbox=props)

rawDescription: How to put text inside a box on a plot in matplotlib

description: Put text inside a box on a plot in matplotlib


code:
from rest_framework.views import APIView
from rest_framework.response import Response

from .models import SiteConfiguration

config = SiteConfiguration.get_solo()

class SiteConfiguration(APIView):
    permission_classes = []

    def get(self, request, format=None):
        """
        Return site configuration key-values.
        """
        return Response({
            'name': config.site_name
        })

rawDescription: django rest-framework singleton ViewSet

description: Django rest-framework singleton ViewSet


code:
self.labels = dict()
for i in range(5):
    name = 'q_label_{}'.format(i)
    label = QLabel()
    label.setObjectName(name)
    grid.addWidget(label, i, 0)
    self.labels[name] = label

rawDescription: creating Qlabels with dynamic name at run time

description: Creating Qlabels with dynamic name at run time


code:
reflected_matrix = reflectXZMatrix * reflectionObjectMatrix
result = target_matrix * reflected_matrix
cmds.xform( target_object, m = result)

rawDescription: Maya Python API Scaling a matrix about another matrix


code:
category_id = request.form.get('category_id')
sub_category_id = request.form.get('sub_category_id')
...

rawDescription: sqlalchemy core build dynamic query

description: Sqlalchemy core build dynamic query


code:
rfc_model_3 = RandomForestClassifier(n_estimators=200)
rfc_model_3.predict(X_test)

rawDescription: Python/Pandas: add random forest predictions as column into test file


rawDescription: tf-idf function in python need help to satisfy my output

description: Tf-idf function in python need help to satisfy my output


code: percentiles

rawDescription: Is it possible to draw a matplotlib boxplot given the percentile values instead of the original inputs?


rawDescription: python argsparse data types

description: Python argsparse data types


rawDescription: Adding lists to existing nested lists

description: Adding lists to existing nested lists


code:
module = sys.modules[__name__]
for var_name in ('doctype', 'content_type', 'framework', 'cms', 'server'):
     setattr(var_name, None)

rawDescription: Easier way to assign a value to multiple global variables in a function


rawDescription: numpy structured array from arbitrary-level nested dictionary

description: Numpy structured array from arbitrary-level nested dictionary


code:
def OnDoubleClick(self, event):
        frame3 = tk.LabelFrame(self, text="frame1", width=300, height=130, bd=5)
        frame3.grid(row=2, column=0, columnspan=3, padx=8)
        #frame is just for managing objects not absolutely needed but i think it is good
        #to use frame when using object so i have kept it in
        curItem = self.tree.focus()
        contents =(self.tree.item(curItem))
        selectedetails = contents['values']
        #this is what you would use to when presenting the selectedd information

rawDescription: Selecting data from a treeview

description: Selecting data from a treeview


code: list(df["price"][df["signal"] == "S"])

rawDescription: List Comprehension Loop

description: List Comprehension Loop


code:
from subprocess import call
call(["xdotool", "mousemove", "300", "500"])

rawDescription: Follow the keyboard selection in Ubuntu preferably by Python


code:
# Vectorised-code example, to see the syntax & principles
#                          do not mind another order of RGB->BRG layers
#                          it has been OpenCV traditional convention
#                          it has no other meaning in this demo of VECTORISED code

def get_YUV_U_Cb_Rec709_BRG_frame( brgFRAME ):  # For the Rec. 709 primaries used in gamma-corrected sRGB, fast, VECTORISED MUL/ADD CODE
    out =  numpy.zeros(            brgFRAME.shape[0:2] )
    out -= 0.09991 / 255 *         brgFRAME[:,:,1]  # // Red
    out -= 0.33601 / 255 *         brgFRAME[:,:,2]  # // Green
    out += 0.436   / 255 *         brgFRAME[:,:,0]  # // Blue
    return out
# normalise to <0.0 - 1.0> before vectorised MUL/ADD, saves [usec] ...
# on 480x640 [px] faster goes about 2.2 [msec] instead of 5.4 [msec]

rawDescription: Python - Quick batch modification of PNGs


code:
fix('(PREDIR )?NAME|PREDIR NAME')
fix('(PREDIR )?PRETYP NAME|PREDIR (PRETYP )?NAME')
fix('NAME SUFTYP|NAME( SUFTYP)?')

rawDescription: Find characters within substring using Python regex


code:
IV = 'NFhS0jOCAR0ymB2MM+3Pfg=='
x = 128
IV = base64.b64decode(IV)
base64.b64encode(IV[:-1] + chr(ord(IV[-1]) ^ x))

rawDescription: Altering the Last Byte of a String

description: Altering the Last Byte of a String


code:
def a():
    return "a" if True else "b"

rawDescription: Allowed syntax for in-line if statements


code:
import lxml.html

html = lxml.html.fromstring(html_txt)
go_away = html.cssselect('.go-away')[0] # Or with suitable xpath
go_away.getparent().remove(go_away)

lxml.html.tostring(html) # Or lxml.html.tostring(html).decode("utf-8") to get a string

rawDescription: Manipulating HTML-Code in Python3

description: Manipulating HTML-Code in Python3


code:
from selenium.selenium import selenium
import unittest, time, re
import BRConfig

class BRTestCase(unittest.TestCase):
    selenium = None

    @classmethod
    def getSelenium(cls):
        if (None == cls.selenium):
            cls.selenium = selenium("localhost", 4444, "*chrome", BRConfig.WEBROOT)
            cls.selenium.start()
        return cls.selenium

    @classmethod
    def restartSelenium(cls):
        cls.selenium.stop()
        cls.selenium.start()

    @classmethod
    def stopSelenium(cls):
        cls.selenium.stop()

    def setUp(self):
        self.verificationErrors = []
        self.selenium = BRTestCase.getSelenium()

    def tearDown(self):
        self.assertEqual([], self.verificationErrors)

rawDescription: keeping firefox profile persistent in multiple selenium tests without specifying a profile

description: Keeping firefox profile persistent in multiple selenium tests without specifying a profile


code:
def ask_for_directory(self):
    self.directory_path = filedialog.askdirectory(mustexist=True, title=self.dialog_title)
    if self.directory_path:

        # Check that we have access to the path
        if not os.access(self.directory_path, os.R_OK):

            # If we don't have access
            if messagebox.askretrycancel(title=self.dialog_title, message="Can't read directory."):
                self.ask_for_directory()

rawDescription: How do I hook into tkinters FileDialog?

description: Hook into tkinters FileDialog


code:
from tkinter import *
main = Tk()
dialog = Toplevel(main)
button = Button(dialog, text="Send", underline="0", command=lambda: print("hello"))
button.pack()
dialog.bind('<Alt-s>', lambda event: button.invoke())
main.mainloop()

rawDescription: Failure of tkinter .focus_set()

description: Failure of tkinter .focus_set()


code: ofset = (len(objlist))

rawDescription: Splitting Python Integer(blender3d)

description: Splitting Python Integer(blender3d)


code:
import eventlet
eventlet.monkey_patch()
import time
time.sleep.__module__

rawDescription: eventlet.greenthread.sleep VS time.sleep in monkey-patched environment

description: Eventlet.greenthread.sleep VS time.sleep in monkey-patched environment


code:
df2 = df.groupby(level=0).mean()
df2['index2'] = 'AVG'
df2 = df2.reset_index().set_index(['index','index2']).append(df).sort()
df2

rawDescription: append rows to a Pandas groupby object

description: Append rows to a Pandas groupby object


code: ' '.join([word[::-1] for word in line.split()])

rawDescription: How do I reverse each word in a string, but in the same sentence order?

description: Reverse each word in a string, but in the same sentence order


code:
fubar = Fubar()
myMethod = fubar.myMethod # note instance fubar, resulting in a bound method.
fubar.myMethod = lambda self, calls = [myMethod, (lambda: 'MyMock'), myMethod]: calls.pop()()

rawDescription: Mock only a subset of all calls to a method


code:
def increment_person_counts(count_per_person):
   with sqlite3.connect(r'./people_database') as connection:
      cursor = connection.cursor()
      cursor.execute('select person from personCounts')
      known_persons = set(row[0] for row in cursor.fetchall())
      for person, count in count_per_person.iteritems():
         if person in known_persons:
            cursor.execute('insert into personCounts(person, count) values (?, ?)', [person, count])
         else:
            cursor.execute('update personCounts SET count=count + ? WHERE person=?', [count, person])
      connection.commit()

rawDescription: Entering large amount of entries in a SQLite Database


code:
s = "[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]"
result = eval(s)

rawDescription: Running a function from a string

description: Running a function from a string


code:
from functools import partial
( partial(MY_DSL_FOO_FUNCTION, params), ANOTHER_DSL_FUNCTION, lambda: expression_in_python, lambda: more_expressions_in_python )

rawDescription: When a DSL gets 'lispy'

description: When a DSL gets 'lispy'


code:
plt.plot(dates, values, '-o')
plt.show()

rawDescription: Matplotlib connect scatterplot points with line - Python


code:
def check(g,s):
    if any(s in vlist for vlist in g.values()):
        return 1
    else:
        return 0

rawDescription: Code not iterating over whole dictionary


code: (df1 + df2).dropna(axis=0, how='all').dropna(axis=1, how='all')

rawDescription: Add Multiple DataFrames and Drop Mismatched Indices


code:
def get_A_with_Bs_in_batch(b_limit=10):
    """
    @return: dict(A, [list of top *b_limit* A.b_s])
    @note: uses 2 SQL statements, but does not screw up relationship.
    @note: if the relationship is requested via a_instance.b_s, the new SQL statement will be
    issued to load *all* related objects
    """
    qry_a = session.query(A)
    qry_b = (session.query(B)
            .join(subq, and_(subq.c.b_id == B.id, subq.c.rownum <= b_limit))
            )
    a_s = qry_a.all()
    b_s = qry_b.all()
    res = dict((a, [b for b in b_s if b.a == a]) for a in a_s)
    return res

rawDescription: How to load a collection with limited number in Sqlalchemy?

description: Load a collection with limited number in Sqlalchemy


code:
from __future__ import division
import numpy as np
from scipy import misc

data = [np.linspace(255, 0, i*10).reshape(i,10)
        for i in range(5, 100, 11)]

max_height = np.max([len(obs) for obs in data if len(obs[0])/len(obs) <= 2])
max_width = 2*max_height
result = []
for obs in data:
    norm_arr = obs
    h, w = obs.shape
    if float(w)/h <= 2:
        scale_factor = max_height/float(h)
        target_size = (max_height, int(round(w*scale_factor)))
        new_arr = misc.imresize(obs, target_size, interp='bicubic')
        norm_arr = np.full((max_height, max_width), fill_value=255)
        # check the shapes
        # print(obs.shape, new_arr.shape, norm_arr.shape)
        nh, nw = new_arr.shape
        norm_arr[:nh, :nw] = new_arr
    result.append(norm_arr)
    # visually check the result
    # misc.toimage(norm_arr).show()

rawDescription: Better image normalization with numpy

description: Better image normalization with numpy


code: np.issubdtype(myArray.dtype, str)

rawDescription: Can I use dtype to find the elements of an numpy array are strings?

description: Use dtype to find the elements of an numpy array are strings


rawDescription: Pickling method descriptor objects in python


code:
# Extract the words features and put them into FreqDist
# object which records the no. of times each unique word occurs
word_features = FreqDist(chain(*[i for i,j in documents]))
# Cuts the FreqDist to the top 100 words in terms of their counts.
word_features = word_features.keys()[:100]

rawDescription: Testing the NLTK classifier on specific file


rawDescription: Sorting objects in Python

description: Sorting objects in Python


code:
# RESET TO DATA FRAME
grouped_df = self.df.groupby(self.df.player_time).count().reset_index()

# SERIES SUM FUNCTION (SUMS EVERY LAST 10 VALUES OF PLAYER_TIME)
def intsum(x):
    if x < 10:
        ser = groupdf.event_name[(groupdf.player_time < x)]
    else:
        ser = groupdf.event_name[(groupdf.player_time >= x - 10) & (groupdf.player_time < x)]
    return ser.sum()

# APPLY FUNCTION
groupdf['intervalSum'] = groupdf['player_time'].apply(intsum)

print(groupdf)

rawDescription: Using pandas resample / rolling_sum to calculate seconds time intervals


code:
import bs4 as bs
content = '''\

Giraffe
14
7

'''
soup = bs.BeautifulSoup(content)

for td in soup.find('td', text='Giraffe').parent.find_all('td'):
    print(td.text)

rawDescription: BeautufulSoup 4, findNext() function

description: BeautufulSoup 4, findNext() function


rawDescription: Pandas set format for single dataframe

description: Pandas set format for single dataframe


code:
from ConfigParser import SafeConfigParser

section_names = 'official', 'debugging'

class MyConfiguration(object):

    def __init__(self, *file_names):
        parser = SafeConfigParser()
        parser.optionxform = str  # make option names case sensitive
        found = parser.read(file_names)
        if not found:
            raise ValueError('No config file found!')
        for name in section_names:
            self.__dict__.update(parser.items(name))  # <-- here the magic happens

config = MyConfiguration('my.cfg', 'other.cfg')

rawDescription: Creating a class with all the elements specified in a file using ConfigParser


code: pprint(combine(l))

rawDescription: Converting list of dictionaries to unique list of dictionaries


code:
from PyQt4 import QtCore, QtGui
import sys

class CentralWidget(QtGui.QWidget):

    def __init__(self, parent=None):
        super(CentralWidget, self).__init__(parent)

        # set layouts
        self.layout = QtGui.QVBoxLayout(self)
        # Poly names
        self.pNames = QtGui.QLabel(self)
        polyNameInput = QtGui.QLineEdit(self)
        # polyName entry
        polyNameInput.textChanged[str].connect(self.onChanged)

        # Polytype selection
        self.defaultPolyType = QtGui.QLabel("Random polyhedra", self)
        polyType = QtGui.QComboBox(self)
        polyType.addItem("Random polyhedra")
        polyType.addItem("Spheres")
        polyType.addItem("Waterman polyhedra")
        polyType.activated[str].connect(self.onActivated)

        self.layout.addWidget(polyNameInput)
        self.layout.addWidget(self.pNames)
        self.layout.addWidget(polyType)
        self.layout.addWidget(self.defaultPolyType)
        self.layout.addStretch()

    def onActivated(self, text):
        '''Adds randSeed to layout'''

        if text=="Random polyhedra":
            self.randomSeedLbl = QtGui.QLabel("Seed: ", self)
            randomSeed = QtGui.QLineEdit(self)
            randomSeed.textChanged[str].connect(self.setSeed)
            self.layout.addWidget(randomSeed)
        else:
            self.defaultPolyType.setText(text)
            self.defaultPolyType.adjustSize()

    # Poly names
    def onChanged(self, text):

        self.pNames.setText(text)
        self.pNames.adjustSize()

class Polyhedra(QtGui.QMainWindow):
    def __init__(self):
        super(Polyhedra, self).__init__()

        # I like having class attributes bound in __init__
        # Not very Qt of me, but it's more
        # so I break everything down into subclasses
        # find it more Pythonic and easier to debug: parent->child
        # is easy when I need to repaint or delete child widgets
        self.central_widget = CentralWidget(self)
        self.setCentralWidget(self.central_widget)

        # Set up window
        self.setGeometry(500, 500, 300, 300)
        self.setWindowTitle('Pyticle')
        self.show()

    # Combo box
    def onActivated(self, text):
        '''Pass to child'''

        self.central_widget.onActivated(text)

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Polyhedra()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: PyQt QVBoxLayout and missing widgets?

description: PyQt QVBoxLayout and missing widgets


code:
dt = None
now = now()

next = Resource.objects.filter(date__gt=now()).order_by('date')[:1]
if next.exists(): #A quick lookup for the date
    now = next[0].date

archive = Resource.objects.filter(date__lt=now).order_by('date')

rawDescription: Django QuerySet: filter by date, then select one more


code:
"a".isalpha()
# True

"&".isalpha()
# False

rawDescription: How to convert characters of a string from lowercase to upper case and vice versa without using string functions in python?

description: Convert characters of a string from lowercase to upper case and vice versa without using string functions in python


code: dict(zip(*data["Tel"]))

rawDescription: Storing multiple get.arguments in a dict


code:
df = pandas.DataFrame(['abc', 'cde', 'aaa'],columns=['A'])
given = 'abcdef'
df[df['A'].apply(lambda x: x in given)]

rawDescription: How to use boolean indexing for substring relation in pandas dataframe?

description: Use boolean indexing for substring relation in pandas dataframe


rawDescription: Poker hand string display

description: Poker hand string display


code: {v for key in yourdict for v in key}

rawDescription: How to get all values from Python tuple keys from dictionaries into one list?

description: Get all values from Python tuple keys from dictionaries into one list


code:
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--input', default='My Input')
    parser.add_argument('filename', default='some_file.txt')
    parser.add_argument('unittest_args', nargs='*')

    args = parser.parse_args()
    # TODO: Go do something with args.input and args.filename

    # Now set the sys.argv to the unittest_args (leaving sys.argv[0] alone)
    sys.argv[1:] = args.unittest_args
    unittest.main()

rawDescription: python, unittest: is there a way to pass command line options to the app

description: Python, unittest: is there a way to pass command line options to the app


code:
v = CountVectorizer(ngram_range=(1, 2), vocabulary={"keeps", "keeps the"})
v.fit_transform(["an apple a day keeps the doctor away"]).toarray()

rawDescription: Understanding the `ngram_range` argument in a CountVectorizer in sklearn


code:
from PIL import Image
import numpy as np

img = Image.open('imagename')
img2 = img.convert('L')
img2_array = np.asarray(img2).copy()

rawDescription: Group pixels in an Image array, in Python


code:
from itertools import chain

with open("ted.csv") as f1, open("ted2.csv") as f2, open('foo.csv', 'w') as out:
    r1, r2 = csv.reader(f1), csv.reader(f2)
    st1 = set((row[0], row[3]) for row in r1)
    st2 = set((row[0], row[3]) for row in r2)
    f1.seek(0), f2.seek(0)
    wr = csv.writer(out)
    r1, r2 = csv.reader(f1), csv.reader(f2)
    output1 = (row for row in r1 if (row[0], row[3]) not in st2)
    output2 = (row for row in r2 if (row[0], row[3]) not in st1)
    for row in chain.from_iterable((output1, output2)):
        wr.writerow(row)

rawDescription: Manipulating csv files with Python

description: Manipulating csv files with Python


code:
from scipy.ndimage import labeled_comprehension
medians = labeled_comprehension(values, idx, uniq, np.median, np.float64, None)
medians

rawDescription: getting median of particular rows of array based on index

description: Getting median of particular rows of array based on index


code:
import requests

from bs4 import BeautifulSoup
from urlparse import urljoin
base = "http://www.gosugamers.net"
url = 'http://www.gosugamers.net/counterstrike/teams'
r = requests.get(url)
page = r.text

soup = BeautifulSoup(page)
for team_links in soup.select("div.details h3 a"):
    print ( urljoin(base, team_links["href"]))

rawDescription: Why am I getting duplicate links ? And how do I fetch links on the next pages?


code:
from itertools import combinations_with_replacement
min, max, n = 10, 20, 2
for combo in combinations_with_replacement(range(min, max), n):
    print(combo)

rawDescription: Pythonic way to generate a tuple of length n


code:
import random
from random import shuffle

a = ['a','b','c','d']
b = ['a','b','c','d']
c = ['w','x','y','z']
d = ['w','x','y','z']
shuffle(c)
shuffle(d)
# print a,b,c,d
print (a,b,c,d)
ac = a + c
bd = b + d
indices = random.sample(range(len(ac)),len(ac))
ac = list(map(ac.__getitem__, indices))
bd = list(map(bd.__getitem__, indices))
#print ac, bd
print (ac, bd)

rawDescription: Shuffling two lists separately in Python


code:
import numpy as np
import Image

def palette(img):
    """
    Return palette in descending order of frequency
    """
    arr = np.asarray(img)
    palette, index = np.unique(asvoid(arr).ravel(), return_inverse=True)
    palette = palette.view(arr.dtype).reshape(-1, arr.shape[-1])
    count = np.bincount(index)
    order = np.argsort(count)
    return palette[order[::-1]]

def asvoid(arr):
    """View the array as dtype np.void (bytes)
    This collapses ND-arrays to 1D-arrays, so you can perform 1D operations on them.
    http://stackoverflow.com/a/16216866/190597 (Jaime)
    http://stackoverflow.com/a/16840350/190597 (Jaime)
    Warning:
    >>> asvoid([-0.]) == asvoid([0.])
    array([False], dtype=bool)
    """
    arr = np.ascontiguousarray(arr)
    return arr.view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[-1])))

img = Image.open(FILENAME, 'r').convert('RGB')
print(palette(img))

rawDescription: Build a color palette from image URL

description: Build a color palette from image URL


code:
def getTimes(aliens):
    n = len(aliens)
    dp = [0] * n #your s array. I'm just used to using dp for dp tables
    parent = [-1] * n
    dp[1] = 1
    for i in range(2, n):
        max = 0; #assuming there can't be a negative number of aliens.
        for j in range(0, i):
            x = dp[j] + min(int(aliens[i]), (i - j) * (i - j))
            if(x >= max):
                max = x
                parent[i] = j
        dp[i] = max;
    times = getTimesRec(n - 1, [], parent)
    return times

def getTimesRec(i, times, parent):
    if(i == -1):
        return times
    getTimesRec(parent[i], times, parent)
    times.append(i)
    return times

rawDescription: How to get the time we shot the aliens?

description: Get the time we shot the aliens


code: plt.xticks(locations, labels)

rawDescription: How to change ticks in matplotlib when saving to a figure?

description: Change ticks in matplotlib when saving to a figure


code:
new_array=np.array(alist)
newer_array = np.array([y for y in new_array if 0 not in y.shape])

rawDescription: remove empty numpy array

description: Remove empty numpy array


code:
import itertools as IT
import numpy as np

def find_idx_1d(rowA, rowB):
    result = []
    if np.in1d(rowB, rowA).all():
        result = [tuple(sorted(idx))
                  for idx in IT.product(*[np.where(rowA==b)[0] for b in rowB])]
    return result

def find_idx(A, B):
    candidates = set([idx for row in A for idx in find_idx_1d(row, B[0])])
    for Bi in B[1:]:
        if len(candidates) == 1:
            # stop when there is a unique candidate
            return candidates.pop()
        new = [idx for row in A for idx in find_idx_1d(row, Bi)]
        candidates = candidates.intersection(new)
    if candidates:
        return candidates.pop()
    raise ValueError('no solution found')

rawDescription: Extract indices of intersecting array from numpy 2D array in subarray


code: list(map(int, re.findall(r'\d+', ' ٢٠١٥-١٠-٠٣ ١٩:٠١:٤٣')))

rawDescription: Convert Arabic Characters (Eastern Arabic Numerals) to Arabic Numerals in Python


code:
from time import sleep
from flask import Flask, render_template

app = Flask(__name__)

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

@app.route('/stream')
def stream():
    def generate():
        with open('job.log') as f:
            while True:
                yield f.read()
                sleep(1)

    return app.response_class(generate(), mimetype='text/plain')

app.run()

rawDescription: Display the contents of a log file as it is updated


code:
class Profile(models.Model):
    user = models.OneToOneField(User)

rawDescription: Django reverse url to onetoonefield on success


code:
def ReadStream(RXcount):
    global ftdi
    return np.frombuffer(ftdi.read(RXcount), dtype=np.uint8)

rawDescription: High-speed alternatives to replace byte array processing bottlenecks


code:
IGHV3-23-IGHJ4-CAKDRGYTGYGVYFDYW
IGHV4-39-IGHJ4-CARHDILTGYSYYFDYW
IGHV3-23-IGHJ3-CAKSGGWYLSDAFDIW
IGHV4-39-IGHJ4-CARTGFGELGFDYW
IGHV1-2-IGHJ2-CARDSDYDWYFDLW
IGHV1-8-IGHJ3-CARGQTYYDILTGPSDAFDIW
IGHV4-39-IGHJ5-CARSTGDWFDPW
IGHV3-9-IGHJ3-CANVPIYSSSYDAFDIW
IGHV3-23-IGHJ4-CAKDWELYYFDYW
IGHV3-23-IGHJ4-CAKDRGYTGFGVYFDYW
IGHV4-39-IGHJ4-CARHLGYNNSWYPFDYW
IGHV1-2-IGHJ4-CAREGYNWNDEGRFDYW
IGHV3-23-IGHJ3-CAKSSGWYLSDAFDIW
IGHV4-39-IGHJ4-CARYLGYNSNWYPFDYW
IGHV3-23-IGHJ6-CAKEGCSSGCPYYYYGMDVW
IGHV3-23-IGHJ3-CAKWGPDAFDIW
IGHV3-11-IGHJ-CATSGGSP
IGHV3-11-IGHJ4-CARDGDGYNDYW
IGHV1-2-IGHJ4-CARRIGYSSGSEDYW
IGHV1-2-IGHJ4-CARDIAVPGHGDYW
IGHV6-1-IGHJ4-CASGGAVPGYYFDYW
IGHV1-2-CAREGYNWNDEGRFDYW
IGHV4-39-CARSTGDWFDPW
IGHV1-2-CARDSDYDWYFDLW

rawDescription: Comparing items in large list - finding items differing in 1 letter by length - Python


rawDescription: Escape filenames for applescript

description: Escape filenames for applescript


code:
import numpy as np
import pandas as pd
import re

def natural_keys(text):
    '''
    alist.sort(key=natural_keys) sorts in human order
    http://nedbatchelder.com/blog/200712/human_sorting.html
    (See Toothy's implementation in the comments)
    '''
    def atoi(text):
        return int(text) if text.isdigit() else text

    return [atoi(c) for c in re.split('(\d+)', text)]

# df = pandas.read_csv('path/to/file', skip_footer=1)
df = pd.DataFrame({'eCPM': np.random.randint(20, size=40)})
bins = np.arange(0, df['eCPM'].max()+1, 0.1, dtype=float)
df['ecpm group'] = pd.cut(df['eCPM'], bins, right=False, labels=None)
df = df.groupby('ecpm group').sum()
df = df.reindex(index=sorted(df.index, key=natural_keys))
print(df)

rawDescription: Python Numpy arange bins should be shown in ascending order


code:
string_io.seek(0)
for row in dict_reader:
    print(row)
    print("Position: {}".format(string_io.tell()))

description: Resetting csv.DictReader(StringIO.StringIO(some_string))


rawDescription: Is there a multiple column map function for dataframes?


code:
import os
import csv

# Assuming files are just in current directory
wav_files = [f for f in os.listdir('.') if f.endswith('.wav')]
with open('your_file.csv', 'rb') as csv_file:
    mappings = [row.strip().split(',' ) for row in csv_file.readlines()[1:]]

for f in wav_files:
    for digit, name in mappings:
        if f[:-4].endswith(digit):
            new_name = f.replace(digit,name)
            os.rename(f, new_name)
            break

rawDescription: How to rename a file name with referenace of csv file

description: Rename a file name with referenace of csv file


rawDescription: When will numpy copy the array when using reshape()


code:
mydict = {'george':[1,2,3],'amber':[18,19]}
[i for i in mydict if 19 in mydict[i]]

rawDescription: Get dictionary key by value if value is list


rawDescription: re.match (regular expression) in python: matching issue

description: Re.match (regular expression) in python: matching issue


code:
def index(request):
    ctx = {}
    if request.method == 'POST' and 'input' in request.POST:
        ctx['result'] = int(request.POST.get('input', 0)) + 5
    return render(request, 'brew/index.html', ctx)

rawDescription: Django can't process html form data

description: Django can't process html form data


code: TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]

rawDescription: How do I keep one menu across multiple Django apps?

description: Keep one menu across multiple Django apps


code:
class MyThread:
    def __init__(self):
        self.result = None
        self.error = None
    def start(self):
        self.proc = multiprocessing.Process(target=self.run)
        self.proc.start()
    def stop(self):
       self.proc.send_signal(multiprocessing.SIG_KILL)
    def run(self):
        try:
            self.result = myfun(*args, **kw) #run external resource and the interrupt it
        except Exception as e:
            self.error = e

rawDescription: Killing Thread and releasing memory in Python


rawDescription: problems with dict.keys not printing a list but printing the view of the list

description: Problems with dict.keys not printing a list but printing the view of the list


code:
seen = set()

[x for x in g if frozenset(x) not in seen and not seen.add(frozenset(x))]
Out[4]: [[1, 2, 3], [9, 0, 1], [4, 3, 2]]

rawDescription: Remove duplicated lists in list of lists in Python


code:
# Define the size of the icons and buttons
iconSize = (24, 24)

# Set the size of the buttons
toolbar.SetToolBitmapSize(iconSize)

# Add some button
saveIcon = wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE, wx.ART_TOOLBAR, iconSize)
toolBar.AddSimpleTool(1, saveIcon, "Save", "Save current file")

rawDescription: How to make a wx Toolbar buttons larger?

description: Make a wx Toolbar buttons larger


code:
format(1e-6, 'f').rstrip('0')
format(1e-3, 'f').rstrip('0')

rawDescription: How to avoid printing scientific notation in python without adding extra digits?

description: Avoid printing scientific notation in python without adding extra digits


code:
g = nx.Graph()
g.add_edge('a', 'b')
g.add_edge('a', 'c')

rawDescription: How to do shortest path algorithm for unweighted graph?

description: Do shortest path algorithm for unweighted graph


code: return super(MessageResource, self).get_object_list(request).filter(Q(sender__user = request.user) | Q(recipient__user = request.user)).values('conversation_id').annotate(last_created=Max(created), distinct=True).order_by('-last_created')

rawDescription: Getting the latest distinct object in Django


rawDescription: resample gives different final dates in pandas

description: Resample gives different final dates in pandas


code:
import numpy as np
import pandas as pd
df = pd.DataFrame({'foo': [1, np.nan, 1, 2, 3, 2, 3, np.nan, float('nan'),
                           np.nan, float('nan'), 'xyz']})

print(df.dropna().loc[df['foo'].duplicated()])

rawDescription: Pandas.Dataframe.duplicated() includes missing rows as duplicates


code: {{ form.name(placeholder="Name", ng_model='NameModel') }}

rawDescription: Custom attributes for Flask WTForms

description: Custom attributes for Flask WTForms


rawDescription: How to manipulate digits within an integer/string?

description: Manipulate digits within an integer/string


code:
from random import sample

def get_random_samples(a, b, n):
    n_prod = len(a) * len(b)
    indices = sample(range(n_prod), n)
    return [(a[idx % len(a)], b[idx // len(a)]) for idx in indices]

rawDescription: Fastest way to sample from product of two lists


rawDescription: How to wrap a python dict?

description: Wrap a python dict


code:
def fun():
    state = [1, 2]
    for i in range(10):
        for j, var in enumerate(state):
            next_st = np.random.randint(0, 3)
            state[j] = next_st
        yield state[:]  # copy

def fun():
    for i in range(10):
        state = [1, 2]  # new list object each iteration
        for j, var in enumerate(state):
            next_st = np.random.randint(0, 3)
            state[j] = next_st
        yield state

rawDescription: Why is this python generator returning the same value everytime?


rawDescription: Trouble pivoting / reshaping a pandas dataframe


code:
import time
import linecache
import itertools

def f_readlines(filename, start_line, endline):
    with open(filename) as f:
        f.readlines()[5000:10000]

def f_enumerate(filename, start_line, endline):
    result = []
    with open(filename) as f:
        for i, line in enumerate(f):
            if i in range(start_line, endline):
                result.append(line)
            if i > endline:
                break

def f_linecache(filename, start_line, endline):
    result = []
    for n in range(start_line, endline):
        result.append(linecache.getline(filename, n))

def f_itertools_islice(filename, start_line, endline):
    result = []
    with open(filename) as f:
        resultt = itertools.islice(f, start_line, endline)
        for i in resultt:
            result.append(i)

def runtest(func_to_test):
    filename = "testlongfile.txt"
    start_line = 5000
    endline = 10000
    start_time = time.time()
    func_to_test(filename, start_line, endline)
    print("--- %s seconds --- %s" % ((time.time() - start_time),func_to_test.__name__))

runtest(f_readlines)
runtest(f_enumerate)
runtest(f_linecache)
runtest(f_itertools_islice)

rawDescription: opening specific lines inside multiple files

description: Opening specific lines inside multiple files


code: {"fieldnames" : json.dumps(['type', 'precision', 'width', 'data'])}

rawDescription: How to store a python dict in Postgresql hstore

description: Store a python dict in Postgresql hstore


code:
l
["%f" % i for i in l]
["%.2f" % i for i in l]
["%.4f" % i for i in l]

rawDescription: Python variable to float list

description: Python variable to float list


code:
image/png
image/jpeg
image/gif

rawDescription: Regular Expression for FileTypes

description: Regular Expression for FileTypes


code: num_coins = coins(num_coins)

rawDescription: Python 2.6, global variable wont change, calling functions in another function


code:
class Quiz(models.Model):
    message = models.CharField(max_length=100)
    order = models.IntegerField()
    response = models.CharField(max_length=100)
    # ... fields you need ...

    def __unicode__():
        return self.message

class QuizUser(models.Model):
    quiz = models.ForeignKey('Quiz')
    user = models.ForeignKey('User')

rawDescription: Series of Questions without database with Django/Twilio


rawDescription: How to remove duplicate lists that contain elements in different order?

description: Remove duplicate lists that contain elements in different order


code:
import dis
dct = {1:1, 2:2}
dis.dis('1 in dct')
dis.dis('len(dct) <= 2')

rawDescription: What is faster in Python3? len or dictionary lookup?


code:
load('p.mat')
myrec

rawDescription: How can I create a Matlab struct array from scipy.io?

description: Create a Matlab struct array from scipy.io


code:
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

rawDescription: Convert complex command into python subprocess


code:
[[x - y for y in sub_y]
     for i, sub_x in enumerate(a[:-1]) for sub_y in a[i+1:] for x in sub_x]

rawDescription: Python, in a list of lists compare first element of the first list to the first element of the second list


rawDescription: Choose Pandas dataframe index after which data in a column is all higher than a specific value


code:
N = 0
xbar = tbar = C = V = 0

rawDescription: Recursive least squares in python?

description: Recursive least squares in python


code:
from skimage import data
im = gray2rgb(data.coins())
tpl = im[170:220, 75:130].copy()
y, x = find_image(im, tpl)
y, x

rawDescription: Determine if an image exists within a larger image, and if so, find it, using Python


code:
SOME_IP = '192.168.1.1'
node_info = PP_NodeStatInfo()
sn_count = c_int(0)
lib.cluster_info(SOME_IP, byref(node_info), byref(sn_count))
[node_info[i][0].status for i in range(sn_count.value)]
[node_info[i][0].name for i in range(sn_count.value)]

rawDescription: Python Ctypes : pointer to array of pointers to a structure


code:
images = [img['src'] for img in soup.findAll('img') if img.has_key('src')]
images[:5]

rawDescription: Load all third party scripts using requests or mechanize in Python


code:
def foo(arg1, arg2, src, dst=None):
    dst = dst if dst is not None else src

rawDescription: Python - how to set default parameter equal to another parameter


rawDescription: Numpy extract values along a dimension for a given point


code: df = pd.DataFrame([{'number': '50', 'box': []}])

rawDescription: Pandas Dataframe from dict with empty list value


code:
from PyQt4 import QtGui, QtSvg
import sys

app = QtGui.QApplication([])
wnd = QtSvg.QSvgWidget()
wnd.load("flower.svg")
wnd.show()
sys.exit(app.exec_())

rawDescription: Images not showing when running a frozen pyqt app on another computer


code:
import pandas as pd
from datetime import date

expr1 = [[1.2,date(2012,1,1)], [1.3,date(2012,1,2)], [1.4,date(2012,1,3)]]
expr2 = [[1.2,date(2012,1,1)], [1.3,date(2012,1,2)], [1.4,date(2012,1,3)], [1.5,date(2012,1,4)]]
expr3 = [[1.2,date(2012,1,1)], [1.3,date(2012,1,2)], [1.4,date(2012,1,3)]]

exper_df1 = pd.DataFrame(expr1).set_index(1).rename(columns={0: "Result_1"})
exper_df2 = pd.DataFrame(expr2).set_index(1).rename(columns={0: "Result_2"})
exper_df3 = pd.DataFrame(expr3).set_index(1).rename(columns={0: "Result_3"})

experiments = [exper_df2, exper_df3]

exper_df = exper_df1.join(experiments, how='inner')

rawDescription: How do I join multiple lists of uniform variables but different values into a single matrix?

description: Join multiple lists of uniform variables but different values into a single matrix


code:
class PriorityQueue(Queue):
    """A subclass of Queue; retrieves entries in priority order (lowest first).

    Entries are typically tuples of the form: (priority number, data).
    """

    def _init(self, maxsize):
        self._queue = []

    def _put(self, item, heappush=heapq.heappush):
        heappush(self._queue, item)

    def _get(self, heappop=heapq.heappop):
        return heappop(self._queue)

rawDescription: Joinable PriorityQueue in python's asyncio


code:
def unformat(s, formatting_str):
    typingdict = {'s': str, 'f': float, 'd':int}  # are there any more?
    name_to_type = {}
    groups = re.findall(r"{([^}]*)}", formatting_str)
    expr_str = ""
    for group in groups:
        name, formatspec = group.split(":")
        length, type_ = formatspec[:-1], typingdict.get(formatspec[-1], str)
        expr_str += "(?P<{name}>.{{{length}}})".format(name=name, length=length)
        name_to_type[name] = type_
    g = re.match(expr_str, s).groupdict()
    for k,v in g.items():
        g[k] = name_to_type[k](v)

    return g

rawDescription: Python parse issue

description: Python parse issue


rawDescription: Dealing with foreign characters in django query


code:
tups = {'narrative': narrative,
        'subject': subject,
        'activity': activity,
        'filer': filer}

rawDescription: Filter a tuple with another tuple in Python


code:
# main.py
print("A")
import test
print("B")
test.foo()
print("C")

rawDescription: when does admin.autodiscover() get executed (python newbie)

description: When does admin.autodiscover() get executed (python newbie)


code:
import re
s = "Water, Titanium Dioxide (CI 77897), Black 2 (CI 77266), Iron Oxides (CI 77491, 77492, 77499), Ultramarines (CI 77007)"
re.split(r',\s*(?![^()]*\))', s)

rawDescription: How to split by commas that are not within parentheses?

description: Split by commas that are not within parentheses


rawDescription: Adding one element from a list to next,after that to next etc


code:
from extensions import celery, db

def create_app():
    app = Flask()

    #configure/initialize all your extensions
    db.init_app(app)
    celery.config_from_object(app.config)

    return app

rawDescription: How to use Flask-SQLAlchemy in a Celery task

description: Use Flask-SQLAlchemy in a Celery task


code:
from bs4 import BeautifulSoup

data = """

                        ...
                        TEXT

"""

soup = BeautifulSoup(data, "html.parser")

print(soup.select_one("ul#select li.generic div.header h2 span.header_arrow").next_sibling.strip())

rawDescription: Python->BeautifulSoup, get some text

description: Python->BeautifulSoup, get some text


code:
class BoxWithOranges:
    def __init__(self):
        self.attributes = {}

    def __getitem__(self, key):
        return self.attributes[key]

    def __setitem__(self, key, value):
        self.attributes[key] = value

rawDescription: Way to iterate though object in python

description: Way to iterate though object in python


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

def plot_colourline(x,y,c):
    c = cm.jet((c-np.min(c))/(np.max(c)-np.min(c)))
    ax = plt.gca()
    for i in np.arange(len(x)-1):
        ax.plot([x[i],x[i+1]], [y[i],y[i+1]], c=c[i])
    return

rawDescription: Color line by third variable - Python

description: Color line by third variable - Python


code:
import matplotlib.pyplot as plt

# plt.plot something

plt.show()

rawDescription: How to plot on Pandas Python

description: Plot on Pandas Python


code:
len2 = itertools.product(numbers, alnum) # length 2
len3 = itertools.product(numbers, alnum, alnum) # length 3
...

rawDescription: How to iterate through alpha and numeric numbers

description: Iterate through alpha and numeric numbers


rawDescription: Hashing uncertain objects

description: Hashing uncertain objects


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

def main():
    x = np.linspace(-2,2,100)
    p1 = 2  #starts from zero
    p2 = 50 #starts from zero

    y1 = main_func(x)
    y2 = calculate_secant(x, y1, p1, p2)
    plot(x, y1, y2)
    plt.show()

def main_func(x):
    return x**2

def calculate_secant(x, y, p1, p2):
    points = [p1, p2]
    m, b = np.polyfit(x[points], y[points], 1)
    return m * x + b

def plot(x, y1, y2):
    plt.plot(x, y1)
    plt.plot(x, y2)

main()

rawDescription: secant line too long, trying not to use y limits

description: Secant line too long, trying not to use y limits


code:
import requests
from bs4 import BeautifulSoup

soup = BeautifulSoup(requests.get("http://oilprice.com/Latest-Energy-News/World-News").content)
main_div = soup.find("div", class_="tableGrid__column tableGrid__column--articleContent category")
divs = main_div.find_all("div","categoryArticle__content")

print([(d.find("p", {"class": "categoryArticle__meta"}).text.split("|")[0].strip(), d.a["href"]) for d in divs])

rawDescription: Python and beautifulSoup: scraping two values - url and date and having the return results paired


code:
def ev_expression(line):
    opfunc = op_funcs[line['operator']]
    return opfunc(line)

rawDescription: Refactoring Python

description: Refactoring Python


code:
r = requests.get('http://myserver/somefile.txt')
f = open('local_file_name.txt', w)
f.write(r.content)
f.close()

rawDescription: Is it Possible to Send a File And or Folder Over Python's Socket Module?


code:
import subprocess
subprocess.call(cmd)

rawDescription: How execute script from command prompt in python


code:
class ComplextCallableObject(object):
    @wrap_me
    def __call__(self, a1, a2):
        pass #...

@wrap_me
def simple_function(tgt, a1, a2):
    pass

ComplextCallableObject.anInstanceMethod = simple_function
ComplextCallableObject.anClassMethod = classmethod(simple_function)
ComplextCallableObject.aStaticMethod = staticmethod(simple_function)

rawDescription: Python: decorate __call__ and ordinary function with the same decorator?


rawDescription: Unable to generate network data in tree format while retaining node attributes


code:
class myThread (threading.Thread):
    def __init__(self, device):
        self.device = device
        threading.Thread.__init__(self)

    def run(self):
        packagename = "com.android.settings"
        classname = "com.android.settings.DisplaySettings"
        componentname = packagename + "/" + classname
        self.device.startActivity(component=componentname)
        maml.click(self.device, 1088, 300)
        MonkeyRunner.sleep(0.4)
        maml.click(self.device, 864, 361)
        MonkeyRunner.sleep(0.4)
        maml.click(self.device, 612, 621)
        MonkeyRunner.sleep(0.5)
        self.device.press('KEYCODE_HOME', 'DOWN_AND_UP')

def main():
    connected_devices = util.get_connected_devices()
    count = 0
    devices = []
    for deviceId in connected_devices:
        devices[count] = MonkeyRunner.waitForConnection(10.0, deviceId[0])
        count = count + 1
    for device in devices:
        thread = myThread(device)
        thread.start()

if __name__ == "__main__":
    main()

rawDescription: Monkeyrunner parallel execution on devices


code:
h = """

Kansas City KC"""

soup = BeautifulSoup(h)

print(soup.find("a", attrs={"class":"team-name"}).abbr["title"])

rawDescription: How to get a specific tag attribute text in Python with BeautifulSoup?

description: Get a specific tag attribute text in Python with BeautifulSoup


code:
def num_double_letters(astr):
    if len(astr) < 2:
        return 0
    if astr[0] == astr[1]:
        return 1 + num_double_letters(astr[2:])
    return num_double_letters(astr[1:])

rawDescription: Python Recursion Double letters

description: Python Recursion Double letters


code:
with settings(sudo_user=sudouser):
      sudo(command)

rawDescription: Fabric: do everything as a particular user


code:
import pkgutil

__all__ = []
for loader, module_name, is_pkg in  pkgutil.walk_packages(__path__):
    __all__.append(module_name)
    module = loader.find_module(module_name).load_module(module_name)
    exec('%s = module' % module_name)

rawDescription: How to import all submodules?

description: Import all submodules


code:
import feedparser
url = "http://..."
feed = feedparser.parse(url)
for post in feed.entries:
    title = post.title
    print(title)

rawDescription: Feedparser newbie questions

description: Feedparser newbie questions


rawDescription: operate with python '\' special character in a string

description: Operate with python '\' special character in a string


rawDescription: Count verbs, nouns, and other parts of speech with python's NLTK


code:
while not gunar_the_orc.is_dead() or smith_the_human.is_dead():
     # Gunar attacks Smith!
     smith_the_human.make_strong_or_weak(-1)

     # Smith drinks some potions:
     smith_the_human.make_strong_or_weak(3)

     # Smith attacks!
     gunar_the_orc.make_strong_or_weak(-10)

if gunar_the_orc.is_dead():
   print("Smith won!")
else:
   print("Gunar won!")

rawDescription: How to add to dictionaries, but not dictionaries - Python

description: Add to dictionaries, but not dictionaries - Python


code: hashvalue = getattr(hashlib, Hash)(f.read()).hexdigest

rawDescription: Unable to pass a variable to function

description: Unable to pass a variable to function


code:
data = simplejson.loads(yourString)
for image in data['images']:
    image['viewurl'] = '/view?imagekey=%s' %(image['imagekey'])

rawDescription: Editing Existing JSON in Python

description: Editing Existing JSON in Python


code:
file_name = "output1.dat"

new_file_name = "sorted_"+file_name
data = csv.reader(open(file_name),delimiter='\t')
sortedlist = sorted(list(data)[2:-2], key=lambda x:int(x[0]))
#now write the sorte result into new CSV file
with open(new_file_name, "wb") as f:
    fileWriter = csv.writer(f, delimiter=',')
    for row in sortedlist:
        fileWriter.writerow(row[:1])

rawDescription: Sort a file according to values in first column


rawDescription: Spark: Use same OneHotEncoder on multiple dataframes


code: lambda x: summation(lambda x: x, 1, lambda x: x + 1, x)

rawDescription: Lambdas and sums Python

description: Lambdas and sums Python


code:
FooArray = make_obarray(Foo, dtype)
BarArray = make_obarray(Bar, some_other_dtype)

f = FooArray([Foo(1,2)])

print(isinstance(f, FooArray)) # True
print(isinstance(f, BarArray)) # False

rawDescription: Python Object via Function

description: Python Object via Function


rawDescription: Nth Fibonacci number for n as big as 10^19?


code:
from matplotlib.dates import WeekdayLocator

def plot_series(x, y):
    fig, ax = plt.subplots()
    ax.plot_date(x, y, fmt='g--') # x = array of dates, y = array of numbers

    fig.autofmt_xdate()

    # For tickmarks and ticklabels every week
    ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO))

    # For tickmarks and ticklabels every other week
    #ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO, interval=2))

    plt.grid(True)
    plt.show()

rawDescription: Custom date range (x-axis) in time series with matplotlib


rawDescription: Python: The best way to get complex dictionary values


code: re.sub("(?<=Apples)\r", ": 1\r", fruits)

rawDescription: Appending to a line

description: Appending to a line


code:
dt=np.dtype([('x',float,(2,))])
y=np.zeros(x.shape[0],dtype=dt)
y
y['x']=x
y
y['x']

rawDescription: convert (nx2) array of floats into (nx1) array of 2-tuples

description: Convert (nx2) array of floats into (nx1) array of 2-tuples


rawDescription: Sleeping after every Selenium function call


code:
Person = Struct('fname', 'age')
person1 = Person('Kevin', 25)
person2 = Person(age=42, fname='Terry')
person1.age += 10
person2.age -= 10
person1.fname, person1.age, person2.fname, person2.age

rawDescription: Python Class Factory to Produce simple Struct-like classes


code:
import io
import pandas as pd

text = """SaleDate    Car
12/1/2016   Wrangler
12/2/2016   Camry
12/3/2016   Wrangler
12/7/2016   Prius
12/10/2016  Prius
12/12/2016  Wrangler"""

df = pd.read_csv(io.StringIO(text), delim_whitespace=True, parse_dates=[0])
df["lastSaleDate"] = df.groupby("Car").SaleDate.shift()

rawDescription: Pandas and Python Dataframes and Conditional Shift Function


code:
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
suite = ['clubs', 'hearts', 'spades', 'diamonds']

deck = [r + ' ' + s for r in ranks for s in suite]

random.shuffle(deck)

rawDescription: How to make cards work in python

description: Make cards work in python


rawDescription: Compute percentile for pandas dataframe row based on previous years data


code:
class ship_class(object):
    def __int__(self,length):
        self.i=0
        self.length=length

    def make_ship(self):
        ship = []
        ship_tmp = []
        ship_row = random_row(board, length)
        ship.append(ship_row)
        ship_col = random_col(board, length)
        ship.append(ship_col)
        if randint(0,1) == 0:
            while self.i<self.length:
                ship_tmp.append(ship[:])
                ship[0] += 1
                for ship in ship_tmp:
                    if ship in ship_all:
                        make_ship(self.length)
                    else:
                        ship_all.append(ship)
                        self.i+=1
        else:
            while self.i<self.length:
                ship_tmp.append(ship[:])
                ship[1] += 1
                for ship in ship_tmp:
                    if ship in ship_all:
                        make_ship(self.length)
                    else:
                        ship_all.append(ship)
                        self.i+=1

rawDescription: Recursion in python didn't work out

description: Recursion in python didn't work out


code:
enum_list = list(map(int, Color))
print(enum_list) # prints [1, 2]

rawDescription: How to get all values from python enum class?

description: Get all values from python enum class


code:
url = "http://www.expatistan.com/cost-of-living/comparison/phoenix/new-york-city"
request = urllib2.Request(url)
opener = urllib2.build_opener()
request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20130406 Firefox/23.0')
page = opener.open(request).read()

rawDescription: Python - Web Scraping - BeautifulSoup

description: Python - Web Scraping - BeautifulSoup


code:
import os.path

def load_and_call(package_path, module_class, method_name):
    module_name, class_name = module_class.split(".")
    module_globals = {}
    execfile(os.path.join(package_path, module_name + ".py"), module_globals)
    return getattr(module_globals[class_name](), method_name, lambda: None)()

rawDescription: python, instance dynamic module.class from given path package and call dynamic method

description: Python, instance dynamic module.class from given path package and call dynamic method


code:
#! /usr/bin/env python

def print_grid(g):
    gsize = len(g)
    base = ord('A')
    print(' '.join([chr(base + i) for i in range(gsize)]))
    print((gsize * 2) * '-')
    for i, row in enumerate(g, 1):
        print(' '.join(row) + ' | ' + str(i))
    print('\n')

def main():
    gsize = 9
    rowstr = gsize * '_'
    grid = [list(rowstr) for i in range(gsize)]
    print_grid(grid)

    while True:
        move = input('Enter move: ')
        letter, number, bit = move.strip()
        col = ord(letter.upper()) - ord('A')
        row = int(number) - 1

        grid[row][col] = bit
        print_grid(grid)

if __name__ == "__main__":
    main()

rawDescription: In python, how would I go about linking user input to a index in a list?


rawDescription: How to extract data from matplotlib plot

description: Extract data from matplotlib plot


code:
lst = [('a','b'), ('c', 'b'), ('a', 'd'), ('e','f'), ('a', 'b')]

def merge(x):
    s = set()
    for i in x:
        if not s.intersection(i):
            yield i
            s.update(i)

rawDescription: Removing duplicates from tuples within a list


code:
data = open(in_filename,'r').read()
out_file = open(out_filename,'w')

rawDescription: python file copy gives larger file

description: Python file copy gives larger file


code:
# Use None to represent missing data. Think about it: "hello" is not a
# valid width; neither is "".
def __init__(self, center=None, width=None, height=None, SW=None, NE=None):
    """A constructor that assigns attributes to the proper variables

    Block, tuple, tuple -> None"""

    if center is not None and width is not None and height is not None:
        # If either SW or NE is given, ignore them
        self.center = center
        self.width = width
        self.height = height
    elif SW is not None and NE is not None:
        # _convert_corners is a helper function you define
        self.center, self.width, self.height = _convert_corners(SW, NE)
    else:
        # Not entirely true. Give width, height, and one corner, you
        # could reconstruct the center, but this is just an example.
        raise ValueError("Insufficient information to construct Block")

rawDescription: Groups of optional arguments for a function - python


rawDescription: how to verify a hash in python?

description: Verify a hash in python


code: bool_list[:] = [False for item in bool_list]

rawDescription: Python: Alter elements of a list

description: Python: Alter elements of a list