rawDescription: how to automatically release a semaphore in a thread after run() is executed?

description: Automatically release a semaphore in a thread after run() is executed


code:
DATE_FORMAT = '%d/%m/%Y'
import datetime
def load_list(filename):
    new_list = []
    with open(filename, 'rU') as f:
        for line in f:
            task, date = line.rsplit(',', 1)
            try:
                # strip removes any extra white space / newlines
                date = datetime.datetime.strptime(date.strip(), DATE_FORMAT)
            except ValueError:
                continue # go to next line
            new_list.append((date, task))
    return new_list

rawDescription: .split() and .append information from .txt file as tuples to a new list


code:
driver = webdriver.Firefox()

class Test(object):
    url1 = "https://www.youtube.com/trendsdashboard#loc0=ind"
    url2 = "https://www.youtube.com/trendsdashboard#loc0=ind&feed=shared"
    url3 = "https://www.youtube.com/trendsdashboard#loc0=ind&feed=shared&gen0=male"

def get_video_trend(url):
    driver.get(url)
    assert "YouTube Trends" in driver.title
    video_trend = []
    element = WebDriverWait(driver, 10).until(lambda driver: driver.find_elements_by_class_name('video-item'))
    for s in element:
        print (s.text)
        video = {}
        videourl = s.find_element_by_css_selector('a').get_attribute('href')
        video['url'] = videourl
        videotitle = s.find_element_by_css_selector('a').get_attribute('alt')
        video['title'] = videotitle
        video_trend.append(video)
    print (video_trend)

if __name__ == '__main__':
    get_video_trend(Test.url1)
    get_video_trend(Test.url2)
    get_video_trend(Test.url3)

rawDescription: Does selenium not work with & in url

description: Does selenium not work with & in url


code:
def newline(self, options, text = ''):
  if getattr(self, 'lpp', None) == self.lines[self.pages]:
    self.newpage()

  if getattr(self, 'y', None) > self.h - self.bm * inch:
    self.newpage()

  self.addLine()

  self.putText(self.x, self.h - self.y, text)

def putText(self, x, y, text):
  # If we actually place some text then we want to record that.
  if len(text.strip()) > 0 and not self.hasText[self.pages]:
    self.hasText[self.pages] = True
  # Something here to handle word wrap.
  if self.wrap:
    lines = self._breakScan(text)

    if len(lines) > 1:
      self.c.drawString(x, y, lines[0])

      self.newline('', ' '.join(lines[1:]))
    elif lines:
      self.c.drawString(x, y, lines[0])
  else:
    self.c.drawString(x, y, text)

rawDescription: In reportlab add as many empty rows to a long table as fit on the last page


rawDescription: Find Closest Vector from a List of Vectors | Python


rawDescription: Parse positions of dictionary values into a list


code: df

rawDescription: How to use pandas to group pivot table results by week?

description: Use pandas to group pivot table results by week


code:
row = ['city', 'state', 'zip', 'zippostal', 'company']
joins = [[4, 0, 2], [1], [3]]
[''.join(row[i] for i in indices) for indices in joins]

rawDescription: Merge Items in List from different areas Python


code:
weight = 0

for word in sentence.split():
    weight += weights[word]

rawDescription: Optimizing the search of a string in a phrases. Don't know which Python structures I need to use


code:
res = empty_like(a, dtype=dtype, order=order, subok=subok)
multiarray.copyto(res, 0, casting='unsafe')

rawDescription: Why the performance difference between numpy.zeros and numpy.zeros_like?


code:
import subprocess
a = subprocess.check_output(["python", "/tmp/b.py"])
print(a.decode('utf-8'))

rawDescription: How to gather return value from function in another script in python?

description: Gather return value from function in another script in python


code:
with open(p_out, 'wb') as fp:
    json.dump(my_dictionary, fp, indent=0)

rawDescription: Dumping multiple variables to disk in Json. One variable per line


code:
import operator

var_1 = 2
var_2 = 3

print(operator.add(var_1, var_2))
print(operator.mul(var_1, var_2))

rawDescription: Python - use an operator at runtime

description: Python - use an operator at runtime


code:
while next(in_file).strip() != TAG1:  # Consume all lines up to TAG1
    pass

for line in in_file:
    if line.strip() == TAG2:          # Break at TAG2
        break
    out_file.write(line)

rawDescription: Keep Linies between two expressions (exclusive) from a file using python


code:
def norm_spirals(a,k, pi=pi, abs=abs, gamma=gamma):
    se = 0.25 +0.5*k + 0.5j*a
    return pi * abs(gamma(se)/gamma(se + 0.5)) ** 2.0

rawDescription: Order of operations and fast computation in Python


code: selitems = [complexobjects[int(idx)] for idx in listbox.curselection()]

rawDescription: Objects from Tkinter controls: how to go beyond StringVar, IntVar, DoubleVar, BooleanVar?


code:
import pandas as pd
from itertools import izip
import csv

with open("foo.csv") as f:
    next(f) # skip header
    r = csv.reader(f)
    zp = izip(*r)
    pairs = izip(next(zp), next(zp))
    df = pd.DataFrame(("{} {}".format(a,b) for a,b in pairs),columns=["Time"])

    print(df)

rawDescription: Extract specified area from DataFrame

description: Extract specified area from DataFrame


rawDescription: Numpy: find the the non-intersecting values of two arrays


code:
import csv
from StringIO import StringIO

quotedData = StringIO()

with open('file.csv') as f:
    reader = csv.reader(f)
    writer = csv.writer(quotedData, quoting=csv.QUOTE_ALL)
    for row in reader:
       writer.writerow(row)

rawDescription: Read a CSV file and put double quote on each item in python


code: find_all_paths(graph, 'A', 'D')

rawDescription: Finding reachable vertices of a vertice in a graph


code:
from thread import start_new_thread
from Queue import Queue

def my_fmin(func, x0, end_callback=(lambda x:x), timeout=None):

    q = Queue() # fmin produces, the generator consumes
    job_done = object() # signals the processing is done

    # Producer
    def my_callback(x):
        q.put(x)
    def task():
        ret = scipy.optimize.fmin(func,x0,callback=my_callback)
        q.put(job_done)
        end_callback(ret) # "Returns" the result of the main call

    # Starts fmin in a new thread
    start_new_thread(task,())

    # Consumer
    while True:
        next_item = q.get(True,timeout) # Blocks until an input is available
        if next_item is job_done:
            break
        yield next_item

rawDescription: Turn functions with a callback into Python generators?


code:
import csv
import scipy.stats as ss
results = []
treatment1 = ""
with open('R:/Python ETL/AGG7.csv') as f:
    reader = csv.reader(f)
    next(reader, None)
    for line in reader:
        treatment2, stdev2, n2, avg2 = line[0], float(line[2]), int(line[3]), float(line[4])
        if treatment2 == treatment1:
            ttest_res = ss.ttest_ind_from_stats(avg1, stdev1, n1, avg2, stdev2, n2, equal_var=False)
            results.append((avg2-avg1, ttest_res.pvalue))
        treatment1, stdev1, n1, avg1 = treatment2, stdev2, n2, avg2

rawDescription: pandas: t-test and p-value of month over month mean difference in aggregated dataframe using groupby function

description: Pandas: t-test and p-value of month over month mean difference in aggregated dataframe using groupby function


code:
import itertools
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = [1, 2, 3]

for i,j in itertools.izip_longest(list1, list2):
    if i: sys.stdout.write('%s' %i)
    if j: sys.stdout.write('%d' %j)
    sys.stdout.write('\n')

rawDescription: Print two presorted lists into one output file in python


rawDescription: Python regex - conditional matching?

description: Python regex - conditional matching


rawDescription: join - duplicates in nested lists

description: Join - duplicates in nested lists


code:
from nltk.corpus import wordnet as wn
game = wn.synset('game.n.04')
leonardo = wn.synset('leonardo.n.01')
game.lowest_common_hypernyms(leonardo)
organism = game.lowest_common_hypernyms(leonardo)[0]
game.shortest_path_distance(organism)
leonardo.shortest_path_distance(organism)

rawDescription: python nltk returning odd result for wordnet similarity measure

description: Python nltk returning odd result for wordnet similarity measure


code:
headers = ['raceid']
values = [raceid]
for perm in itertools.permutations(list(range(1, horses+1)), 3):
    headers.append('perm_{}_{}_{}'.format(*perm))
    values.append(odds.get(perm, None))

rawDescription: Reformat data (permutations) in Python

description: Reformat data (permutations) in Python


code:
import re
from pprint import pprint

def loadmaze(filename):

    maze = []

    with open(filename) as f:
        for line in f:
            with_delimiters = ''
            for i,ch in enumerate(line):
                with_delimiters += 'S' + ch
            line = with_delimiters

            inchars = '# M'
            outchars = ['-1','0','-2']
            for i,ch in enumerate(inchars):
                line = line.replace(ch,outchars[i])
                line = line.replace('\n','')

            maze_col = line.split('S')
            for i in maze_col:
                if i == '':
                    maze_col.remove(i)
            maze.append(map(int,maze_col))

    return maze

pprint (loadmaze('maze.txt'))

rawDescription: Convert a file into a matrix, replace each character with a number in Python


rawDescription: Fama Macbeth Regression in Python (Pandas or Statsmodels)


code:
groups = data.groupby('device_id')
data.ix[groups.groups.get(34)].head()   # Get the data for device_id = 34

rawDescription: Fastest way to calculate average of datetime rows using pandas


code:
def do_sth():
    d = {'a':2, 'b':3}
    print(id(d))

import dis
dis.dis(do_sth)

rawDescription: Python local variable initialization

description: Python local variable initialization


code:
# Python 3.x interpreter
'exec' in dir(__builtins__)
callable(exec)

rawDescription: Where is python exec?

description: Where is python exec


code: Rfoobar = ceil(foobar * 10 ** digits) / 10 ** digits

rawDescription: How to round decimal digits always up

description: Round decimal digits always up


code:
def f(x):
    return math.sin(x)

rawDescription: How to numerically integrate f(x) between a lower and an upper bound?

description: Numerically integrate f(x) between a lower and an upper bound


code:
from itertools import chain, repeat
bar = chain(foo, repeat("default"))

rawDescription: Using iter on a list with a default value


code:
html = """

     <select class="catalogPagination_dropdown" data-baseurl="/herrenbekleidung-shirts/?order=popularity" data-current="1" data-pages="97">
      <select class="catalogPagination_dropdown" data-baseurl="/herrenbekleidung-shirts/?order=popularity" data-current="1" foo="97">

      <option>
       Seite 1 von 97
      </option>
     </select>"""

soup = BeautifulSoup(html)

selects = soup.find_all("select", {"class": "catalogPagination_dropdown", "data-pages": True})

print([s["data-pages"] for s in selects])

rawDescription: python - web scraping - return attributes from inside a class

description: Python - web scraping - return attributes from inside a class


rawDescription: Python instance of class defined inside a method is still able to use local variables inside the method when called outside the method


code:
m = MyObj()
m.x

rawDescription: Docstring inheritance for properties using sphinx's autodoc


code:
#!/usr/bin/env python3
import cgi
from html.parser import HTMLParser
from urllib.request import urlopen

url = 'http://finance.yahoo.com/q?s=GOOG'

def is_price_tag(tag, attrs):
    return tag == 'span' and dict(attrs).get('id') == 'yfs_l84_goog'

class Parser(HTMLParser):
    """Extract tag's text content from html."""
    def __init__(self, html, starttag_callback):
        HTMLParser.__init__(self)
        self.contents = []
        self.intag = None
        self.starttag_callback = starttag_callback
        self.feed(html)

    def handle_starttag(self, tag, attrs):
        self.intag = self.starttag_callback(tag, attrs)
    def handle_endtag(self, tag):
        self.intag = False
    def handle_data(self, data):
        if self.intag:
            self.contents.append(data)

# download and convert to Unicode
response = urlopen(url)
_, params = cgi.parse_header(response.headers.get('Content-Type', ''))
html = response.read().decode(params['charset'])

# parse html (extract text from the price tag)
content = Parser(html, is_price_tag).contents[0]
print(content)

rawDescription: How to display proper output when using re.findall() in python?

description: Display proper output when using re.findall() in python


rawDescription: tkinter - Expanding a Listbox inside a Notebook

description: Tkinter - Expanding a Listbox inside a Notebook


code:
import ImageFilter

def filterBlur(im):

    im1 = im.filter(ImageFilter.BLUR)

    im1.save("BLUR" + ext)

filterBlur(im1)

rawDescription: Blur image with python

description: Blur image with python


rawDescription: Change base python counts in

description: Change base python counts in


code:
filled_1 = False
filled_2 = True
filled_3 = False
filled_4 = False

rawDescription: pygame circle not changing

description: Pygame circle not changing


code: z = [y-256 if y > 256 else y for y in x]

rawDescription: Tuple Subtract statement in Python

description: Tuple Subtract statement in Python


code: final = test.traverse(len(test.children), test, [])

rawDescription: Parsing a tree using python

description: Parsing a tree using python


code:
import sqlite3
import json

def dict_factory(cursor, row):
    '''
    Provides DictCursor for sqlite
    '''
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

conn = sqlite3.connect('db.sqlite')
conn.row_factory = dict_factory
cur = conn.cursor()
cur.execute('''SELECT * FROM HEADER''')
headers_list = list(cur.fetchall())
for header in headers_list:
    cur.execute('SELECT * FROM DETAIL WHERE HEADER_ID=' + str(header['id']))
    row = cur.fetchone()
    if row is not None:
       header['details'] = row
cur.close()

print(json.dumps(headers_list))

rawDescription: create nested json from the ouput of two queries django

description: Create nested json from the ouput of two queries django


rawDescription: Python - Convert list of single key dictionaries into a single dictionary


code: dt = datetime.datetime.strptime(xsdDateTime, '%Y-%m-%dT%H:%M:%S')

rawDescription: Parse xsd:dateTime formatted string to python datetime


rawDescription: How to shift a list nth time in Left or Right and fill it up with 0 in python

description: Shift a list nth time in Left or Right and fill it up with 0 in python


code:
start = line.index('data-name') + len('data-name="')
end = line.index('"', start)
print(line[start:end])

rawDescription: Writing from one file to another python

description: Writing from one file to another python


code:
import calendar
months = {calendar.month_name[i].lower(): i for i in range(1, 12+1)}
my_list = ['apple_april', 'banana_july', 'carrot_december', 'dog_january']
sorted(my_list, key=lambda x: months[x.split('_')[1]])

rawDescription: Sorting of one list using specific strings contained in the list


code:
df = pd.DataFrame({'month': ['Jan','Jan','Feb'], 'val':[1,2,3]})
df = df.set_index(['month'])

rawDescription: creating multiple dataframes which contain subsets of an orginal pandas dataframe

description: Creating multiple dataframes which contain subsets of an orginal pandas dataframe


rawDescription: Regex - Print the lines starting with a T


code:
def calc_distance(startCity, endCity):
    # whatever magic you need to do to calculate your distances
    return [distance, gc_distance]

rawDescription: Printing list to table

description: Printing list to table


code:
s='
Ввоскресень
'
import HTMLParser
h=HTMLParser.HTMLParser()
print(h.unescape(s))

rawDescription: Python - Convert unicode hex to string

description: Python - Convert unicode hex to string


code:
def count_name(self,genre,name_count = 0):

    for node in self.children:
        if node.genre == genre:
            print ("same genre") #you probably know this but take this
            print ("word = ", genre) #and this line out to only print `3`
            name_count+=1
        name_count = node.count_name(genre,name_count)
    return name_count

rawDescription: Count the number of nodes with the same name in a tree


rawDescription: return data from HTMLParser handle_starttag

description: Return data from HTMLParser handle_starttag


rawDescription: Can't figure out how to increment certain values in a list


code:
def __neg__(self):
    return Integer(-self.p)

rawDescription: Sympy classes Zero, One and NegativeOne, why they exist?


rawDescription: autoscroll of text and scrollbar in python text box

description: Autoscroll of text and scrollbar in python text box


code:
#!/usr/bin/env python3
import logging
import os
import signal
import subprocess
import tkinter

info = logging.getLogger(__name__).info

def on_signal(pipe, mask, count=[0]):
    try:
        signals = os.read(pipe, 512)
    except BlockingIOError:
        return # signals have been already dealt with

    # from asyncio/unix_events.py
    #+start
    # Because of signal coalescing, we must keep calling waitpid() as
    # long as we're able to reap a child.
    while True:
        try:
            pid, status = os.waitpid(-1, os.WNOHANG)
        except ChildProcessError:
            info('No more child processes exist.')
            return
        else:
            if pid == 0:
                info('A child process is still alive. signals=%r%s',
                     signals, ' SIGCHLD'*(any(signum == signal.SIGCHLD
                                              for signum in signals)))
                return
            #+end
            # you could call your callback here
            info('{pid} child exited with status {status}'.format(**vars()))
            count[0] += 1
            if count[0] == 2:
                root.destroy() # exit GUI

logging.basicConfig(format="%(asctime)-15s %(message)s", datefmt='%F %T',
                    level=logging.INFO)
root = tkinter.Tk()
root.withdraw() # hide GUI

r, w = os.pipe2(os.O_NONBLOCK | os.O_CLOEXEC)
signal.set_wakeup_fd(w)
root.createfilehandler(r, tkinter.READABLE, on_signal)
signal.signal(signal.SIGCHLD, lambda signum, frame: None) # enable SIGCHLD
signal.siginterrupt(signal.SIGCHLD, False) # restart interrupted syscalls automatically
info('run children')
p = subprocess.Popen('sleep 4', shell=True)
subprocess.Popen('sleep 1', shell=True)
root.after(2000, p.send_signal, signal.SIGSTOP) # show that SIGCHLD may be delivered
root.after(3000, p.send_signal, signal.SIGCONT) # while the child is still alive
root.after(5000, lambda: p.poll() is None and p.kill()) # kill it
root.mainloop()
info('done')

rawDescription: Event Driven System Call in Python

description: Event Driven System Call in Python


code: rc2xy = lambda r, c: (c, r) * T1

rawDescription: How to I get the coordinates of a cell in a geotif?


code: np.hstack((a[:-b.size], a[-b.size:]*b))

rawDescription: Elementwise multiplication of shorter array with longer one at an offset index with numpy?


code:
A = list(range(10))
found1=True
while found1:
    found1=False
    for i,j in enumerate(range(1,len(A))):
        if A[i] < A[j]:
            A[i],A[j] = A[j],A[i]
            found1=True
print(A)

rawDescription: Pythonic way of comparing all adjacent elements in a list


code:
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200, 'OK')
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write( "hello" )

HTTPServer(('', 8888), MyServer).serve_forever()

rawDescription: Communication from arduino to a browser extension all run locally


rawDescription: Modifying nested dictionaries

description: Modifying nested dictionaries


code:
class AdminCategoryBySupercategory(forms.CheckboxSelectMultiple):

     def render(self, name, value, attrs=None, choices=()):
         if value is None: value = []
         has_id = attrs and 'id' in attrs
         final_attrs = self.build_attrs(attrs, name=name)
         output = [u'
']
         # Normalize to strings
         str_values = set([force_unicode(v) for v in value])
         supercategories = models.SuperCategory.objects.all()
         for supercategory in supercategories:
             output.append(u'
%s
'%(supercategory.name))
             output.append(u'
')
             del self.choices
             self.choices = []
             categories = models.Category.objects.filter(super_category=supercategory)
             for category in categories:
                 self.choices.append((category.id,category.name))
             for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
                 if has_id:
                     final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
                     label_for = u' for="%s"' % final_attrs['id']
                 else:
                     label_for = ''
                 cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
                 option_value = force_unicode(option_value)
                 rendered_cb = cb.render(name, option_value)
                 option_label = conditional_escape(force_unicode(option_label))
                 output.append(u'
%s %s
' % (label_for, rendered_cb, option_label))
             output.append(u'
')
             output.append(u'
')
         output.append(u'
')
         return mark_safe(u'\n'.join(output))

rawDescription: Grouping CheckboxSelectMultiple Options in Django


code:
def characters(self, content):
    # assert content is not None and len(content) > 0
    assert content
    # if len(self.stack) == 0:
    if not self.stack:
        return
    if self.stack[-1] == "title":
        self.title += content
    elif self.stack[-1] == "text":
        # assert self.title is not None
        assert self.title # This assertion is gross overkill IMHO
        self.text += content

rawDescription: convert to lxml sax interface from default python xml.sax

description: Convert to lxml sax interface from default python xml.sax


code:
with open('file.txt', 'r') as f:
    for line in f:
        print(line, end='')

rawDescription: Python: Opening a file within a print() function


code:
import sys
import xlrd
book = xlrd.open_workbook(sys.argv[1])

rawDescription: How to access through a path rather than just in current directory?

description: Access through a path rather than just in current directory


code:
reactor.connectTCP('localhost', 50000, myProtocolFactory())
reactor.run()

rawDescription: Twisted client for a send only protocol that is tolerant of disconnects


code:
import numpy as np
list(np.argsort(np.argsort(list('hello'))))
list(np.argsort(np.argsort(list('cadeb'))))

rawDescription: How to create a list of small values out of large values

description: Create a list of small values out of large values


code:
class CarpoolField(serializers.PrimaryKeyRelatedField):
    def to_representation(self, value):
        serializer = CarpoolSerializer(value)
        return serializer.data

class ParentArrivalSerializer(serializers.HyperlinkedModelSerializer):
    carpool = CarpoolField(queryset=Carpool.objects.all())

    class Meta:
        model = ParentArrival

rawDescription: Django Rest Framework receive primary key value in POST and return model object as nested serializer


code:
import tkinter as tk
import os

def save_data():
    text = name.get().strip()
    if text: # checks for empty entries
        f = open('names.txt', 'a')
        f.write(text + '\n')
        f.close()
        name.delete(0, tk.END)

# Checks if the file exists
# if not then create it and
# write the header 'Name List'
if not os.path.exists('names.txt'):
    f = open('names.txt', 'w')
    f.write('Name_List:\n')
    f.close()

root = tk.Tk()

tk.Label(root, text = "Please Enter Name Here:").pack()

name = tk.Entry(root)
name.pack()

tk.Button(root, text = 'Save', command = save_data).pack()

root.mainloop()

rawDescription: how to create clear entry text in tkinter and display on to the window

description: Create clear entry text in tkinter and display on to the window


code:
result = df.groupby(['category', 'subcategory', 'contract']).sum() > 0
result

rawDescription: pandas dataframe count uniques with respect to another column

description: Pandas dataframe count uniques with respect to another column


code: ''.join(r'\x{0:02x}'.format(ord(c)) for c in value)

rawDescription: Python binary conversion to hex

description: Python binary conversion to hex


code:
for x in range(0,len(tuesday)):
     print(" -",x)

rawDescription: Use loop to print an array

description: Use loop to print an array


code:
urlpatterns = patterns('myuserprofile.views',
         url(r'^(?P<username>[^/]+)/$', 'profile', name='profile'),
         url(r'^(?P<username>[^/]+)/follow/$', 'follow', name='follow'),
         url(r'^(?P<username>[^/]+)/unfollow/$', 'unfollow', name='unfollow'),
)

rawDescription: NoReverseMatch found

description: NoReverseMatch found


code:
df.values
df.values[:, :-1]
df.values[:, :-1].ravel()

rawDescription: How to select all data from Data Frame?

description: Select all data from Data Frame


code:
if inputString.endswith('y'):
    fixed = inputString[:-1] + 'ies'

rawDescription: str.endswith() does not seem to consider the first if statment

description: Str.endswith() does not seem to consider the first if statment


code:
results = []
for elem in tree.getiterator():
    if elem.tag=='{http://www.namespace.co.uk}AssetEquipment':
        output={}
        results.append(output)
        ...

rawDescription: Looping over multiple dictionaries and not just the last dictionary in python


code: {u'geometry': {u'type': u'Point', u'classifier': None, u'coordinates': [152.356430053711, -27.5912036895752]}, u'source': {u'externalid': None, u'id': 2, u'name': u'Department of Transport and Main Roads'}, u'type': u'Feature', u'id': 55141891, u'properties': {u'temporal': {u'end': None, u'nextUpdate': None, u'lastReviewed': None, u'modified': u'08/05/2015T09:35:14', u'start': u'22/08/2015T10:30:00', u'review': None}, u'metadata': {u'status': None, u'owner': None, u'contactEmail': None, u'modifiedBy': None, u'url': u'http://131940.qld.gov.au/road-conditions.aspx?id=55141891'}, u'location': {u'direction': u'Both Directions', u'additional': u'Gallipoli Rememberence March.\r\nVictoria Street Forest Hill, between Church Street and William Steet', u'region': {u'id': 104, u'name': u'Darling Downs'}, u'localGovernment': None, u'suburb': u'FOREST HILL', u'state': u'QLD', u'postcode': u'4342', u'road': u'VICTORIA STREET'}, u'event': {u'impact': None, u'description': u'Special Event Both Directions\r\nGallipoli Rememberence March.\r\nVictoria Street Forest Hill, between Church Street and William Steet.\r\nCommencing: 22 August 2015, between the hours of 10:30am and 11:15am\r\nConcluding: 22 August 2015.\r\nRoad closed both directions\r\nNo delays expected. Use alternative route. \r\n\r\n\r\nLast edited: 08 May 2015 09:35', u'type': u'Planned', u'advice': u'Use alternative route', u'delay': u'No delays expected', u'incidentDetails': u'N/A', u'limit': None, u'incidentType': u'', u'extraDetails': u'\r\n', u'cause': u'Special Event', u'isHighImpact': False}}}

rawDescription: return value in json file 5 levels deep in python using simplejson

description: Return value in json file 5 levels deep in python using simplejson


code:
class _NestedClassGetter(object):
    """
    From: http://stackoverflow.com/a/11493777/741316
    When called with the containing class as the first argument,
    and the name of the nested class as the second argument,
    returns an instance of the nested class.
    """
    def __call__(self, factory_method, base):
        nested_class = factory_method(base)

        # make an instance of a simple object (this one will do), for which we
        # can change the __class__ later on.
        nested_instance = _NestedClassGetter()

        # set the class of the instance, the __init__ will never be called on
        # the class but the original state will be set later on by pickle.
        nested_instance.__class__ = nested_class
        return nested_instance

rawDescription: Factory method pattern conflicts with use of multiprocessing queue


code: numpy.ma.MaskedArray(a, numpy.concatenate([mask] * reps, axis=0))

rawDescription: Appending 3d array into 4d array, the 4th dimension being number of 3D arrays


code:
from collections import defaultdict

myDict = defaultdict(int)

for _, key, val in myTupleList:
    myDict[key] += val

rawDescription: Map List of Tuples into a Dictionary, python


code:
response = requests.get('http://10.xx.xx.xx:1234/virtual-networks')
response.json

rawDescription: How would you use a cURL "GET" with a Python based REST API for network programming?


code:
import itertools
input = [['a','b'],['c','d'],['e','f']]
combs = []
for i in range(1, len(input)+1):
    els = [list(itertools.chain.from_iterable(x)) for x in itertools.combinations(input, i)]
    combs.extend(els)
import pprint
pprint.pprint(combs)

rawDescription: Python all combinations of a list of lists


code:
with open("test.txt", "r") as myfile:
    fil = myfile.read().rstrip('\n')
with open("test.txt", "w") as f:
    f.write(re.sub(r'(?m)^', r'append text', fil))

rawDescription: Append in each line of a .txt file a specific string using Python


code: columns = zip(*my_2d_list)

rawDescription: Convert a column in a list to number, keeping other columns unchanged


code:
def alpha_to_num(alpha):
    num_bytes = base64.b64decode(alpha)
    return int(num_bytes.encode('hex'), 16)

rawDescription: Encoding a numeric string into a shortened alphanumeric string, and back again


code: straight = any(a[4+i] - a[i] == 4 for i in (0,1,2))

rawDescription: Check a tuple for at least 5 consecutive numbers


code:
from pylab import *
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

# fake up some data
spread= rand(50) * 100
center = ones(25) * 50
flier_high = rand(10) * 100 + 100
flier_low = rand(10) * -100
data =concatenate((spread, center, flier_high, flier_low), 0)

# fake up some more data
spread= rand(50) * 100
center = ones(25) * 40
flier_high = rand(10) * 100 + 100
flier_low = rand(10) * -100
d2 = concatenate( (spread, center, flier_high, flier_low), 0 )
data.shape = (-1, 1)
d2.shape = (-1, 1)
data = [data, d2, d2[::2,0]]

# multiple box plots on one figure
fig = plt.figure(1, [5,4])
ax = fig.add_subplot(111)
ax.boxplot(data)
ax.set_xlim(0.5,5)
ax.set_ylim(0,300)

# Create the zoomed axes
axins = zoomed_inset_axes(ax, 3, loc=1) # zoom = 3, location = 1 (upper right)
axins.boxplot(data)

# sub region of the original image
x1, x2, y1, y2 = 0.9, 1.1, 125, 175
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
plt.xticks(visible=False)
plt.yticks(visible=False)

# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

show()

rawDescription: matplotlib: inset axes for multiple boxplots

description: Matplotlib: inset axes for multiple boxplots


code:
b = ['d']
c = ['e', 'f',['x', 'y'],["x"]]
h = []
a = [b,c,h]
from collections import Iterable

def flatten_nest(l):
    if not l:
        return l
    if isinstance(l[0], Iterable) and not isinstance(l[0],basestring): # isinstance(l[0],str) <- python 3
        return flatten_nest(l[0]) + flatten_nest(l[1:])
    return l[:1] + flatten_nest(l[1:])

In [13]: len(flatten_nest(a))
Out[13]: 6

rawDescription: How to count items in list recursively

description: Count items in list recursively


code:
map(d.get, it)  # Existing
map(d, it)      # Proposed

rawDescription: Why aren't dictionaries callable?

description: Why aren't dictionaries callable


code: t_plustext    = r'plus'

rawDescription: How to make a calculator with strings and numbers as mixed input using parser python ply

description: Make a calculator with strings and numbers as mixed input using parser python ply


code: lo, hi = sorted([heapq.heappop(tree), heapq.heappop(tree)], key=len)

rawDescription: Why does a label permutation produce a different Huffman code?


code:
def get_signature(key, msg):
    if(isinstance(key, str)):
        key = key.encode('ascii')
    if(isinstance(msg, str)):
        msg = msg.encode('ascii')
    return base64.b64encode(hmac.new(key, msg, hashlib.sha1).digest())

rawDescription: Why my python and objective-c code get different hmac-sha1 result?


rawDescription: When the key is a tuple in dictionary in Python


code:
import benchmark
from random import choice, randint
import string

def str_key(length=8, alphabet=string.ascii_letters):
    return ''.join(choice(alphabet) for _ in xrange(length))

def int_key(min=10, max=99):
    return randint(min, max)

class Benchmark_DictLookup(benchmark.Benchmark):

    each = 100 # allows for differing number of runs

    def setUp(self):
        # Only using setUp in order to subclass later
        # Can also specify tearDown, eachSetUp, and eachTearDown
        self.size = 1000000
        self.n = 50
        self.intdict = { int_key():str_key() for _ in xrange(self.n) }
        self.strdict = { str_key():int_key() for _ in xrange(self.n) }
        self.intkeys = [ int_key() for _ in xrange(self.size) ]
        self.strkeys = [ str_key() for _ in xrange(self.size) ]

    def test_int_lookup(self):
        d = self.intdict
        for key in self.intkeys:
            try:
                d[key]
            except KeyError:
                pass

    def test_int_lookup_get(self):
        d = self.intdict
        for key in self.intkeys:
            d.get(key, None)

    def test_str_lookup(self):
        d = self.strdict
        for key in self.strkeys:
            try:
                d[key]
            except KeyError:
                pass

    def test_str_lookup_get(self):
        d = self.strdict
        for key in self.strkeys:
            d.get(key, None)

class Benchmark_Hashing(benchmark.Benchmark):

    each = 100 # allows for differing number of runs

    def setUp(self):
        # Only using setUp in order to subclass later
        # Can also specify tearDown, eachSetUp, and eachTearDown
        self.size = 100000
        self.intkeys = [ int_key() for _ in xrange(self.size) ]
        self.strkeys = [ str_key() for _ in xrange(self.size) ]

    def test_int_hash(self):
        for key in self.intkeys:
            id(key)

    def test_str_hash(self):
        for key in self.strkeys:
            id(key)

if __name__ == '__main__':
    benchmark.main(format="markdown", numberFormat="%.4g")

rawDescription: Python dict: there a speed difference between matching a numeric key over a word in python?


code:
import pythoncom
from pyHook import HookManager, GetKeyState, HookConstants

def OnKeyboardEvent(event):
    # in case you want to debug: uncomment next line
    # print repr(event), event.KeyID, HookConstants.IDToName(event.KeyID), event.ScanCode , event.Ascii, event.flags
    if GetKeyState(HookConstants.VKeyToID('VK_LSHIFT')) and event.KeyID == HookConstants.VKeyToID('VK_SNAPSHOT'):
        print("shift + snapshot pressed")
    elif GetKeyState(HookConstants.VKeyToID('VK_CONTROL')) and HookConstants.IDToName(event.KeyID) == 'D':
        print("ctrl + d pressed")
    return True

# create a hook manager
hm = HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()

rawDescription: How to capture Shift + PrintScreen with pyHook?

description: Capture Shift + PrintScreen with pyHook


code:
# you probably want to use a space ' ' to replace `\n`
mystring = mystring.replace('\n', ' ').replace('\r', '')

rawDescription: Remove all line breaks from a long string of text


code:
ary = np.arange(5).astype(float)
np.triu(combinatorics(ary))
np.triu(sums(ary))

rawDescription: Numpy with Combinatoric generators: How does one speed up Combinations?


code:
out = {}
for colour, array_ in h:
     if colour in out:
         out[colour] += array_
     else:
         out[colour] = array_

rawDescription: find duplicates within list

description: Find duplicates within list


code:
def refresh_token(self, token, *args, **kwargs):
    """
    Overridden method to add extra info during refresh token.
    Args:
        token (str): valid refresh token
    Returns:
        dict of information about the user
    """
    response = super(EdxOrgOAuth2, self).refresh_token(token, *args, **kwargs)
    response['updated_at'] = datetime.utcnow().timestamp()
    return response

rawDescription: Decide when to refresh OAUTH2 token with Python Social Auth


code: ((firstbyte & 0b111111) << 8) + secondbyte

rawDescription: Read 14 bit number from 2 bytes

description: Read 14 bit number from 2 bytes


code: q = Session.query(Articles).filter(Articles.tags.any(name = 'tag_name'))

rawDescription: How to do a JOIN in SQLAlchemy on 3 tables, where one of them is mapping between other two?

description: Do a JOIN in SQLAlchemy on 3 tables, where one of them is mapping between other two


code:
def myfunc(*args):
    statement = "INSERT INTO table VALUES(" + ', '.join('$'+str(i) for i in range(0, len(args)+1)) + ");"
    handle = db.prepare(statement)
    handle(args)

rawDescription: How to efficiently unravel arguments to a database in Python

description: Efficiently unravel arguments to a database in Python


code:
import requests
import json

URLs = [
    # Some URLs that return JSON objects
    'http://httpbin.org/ip',
    'http://httpbin.org/user-agent',
    'http://httpbin.org/headers'
]

with open('result.json', 'w') as fp:
    json.dump([requests.get(url).json() for url in URLs], fp, indent=2)

rawDescription: Python 3 - Parse JSON from multiple API requests into a list and output to a file


code: res2 = (single[np.newaxis,:,:] / division[:,np.newaxis,:] * actg).sum(axis=-1)

rawDescription: Python: How to perform division according to its representation?


code: max(sequence, key=len)

rawDescription: Max() function does not return largest value in Python 3.4


code:
import csv
with open("master.csv") as m, open("update.csv") as u, open("out.csv", "w") as o:
    master = { line['ID']: line for line in csv.DictReader(m) }
    update = { line['ID']: line for line in csv.DictReader(u) }
    master.update(update)
    fields = csv.DictReader(open("master.csv")).fieldnames
    out = csv.DictWriter(o, fields)
    out.writeheader()
    out.writerows(master.values())

rawDescription: PYTHON - Comparing two different files; if a line containing an ID already exists then update else append the line


code:
#! /usr/bin/python
import sys
sys.stdout.write("In test2\n")
sys.stdout.write("Done")

rawDescription: defining timeout on execution of shell/python script

description: Defining timeout on execution of shell/python script


rawDescription: comparing column values based on other column values in pandas

description: Comparing column values based on other column values in pandas


code:
def iter_data(fileobj):
    for line in fileobj:
        yield from line.split()

def read_triangular_array(path):
    with open(path) as fileobj:
        n = len(fileobj.readline().split())

    count = int(n*(n+1)/2)

    with open(path) as fileobj:
        return np.fromiter(iter_data(fileobj), int, count=count)

rawDescription: Using numpy's genfromtxt to load a triangular matrix with python


code:
shapes = pd.read_csv('shapes.csv')
shapes.set_index(["shape_id", "shape_pt_sequence"], inplace=True)

rawDescription: Breaking down large dataset into organized index


code:
MACHINE = subprocess.check_output(['cut', '-d ', '-f1', 'file.txt']).split()
MACHINE

rawDescription: output as a list in Python

description: Output as a list in Python


rawDescription: Generate permutations of a list of lists with variable lengths


code:
A = [[1,1,1,2,3,1,2,3],[0.1,0.2,0.2,0.1,0.3,0.2,0.2,0.1]]
unq, unq_idx = np.unique(A[0], return_inverse=True)
unq_sum = np.bincount(unq_idx, weights=A[1])
unq_counts = np.bincount(unq_idx)
unq_avg = unq_sum / unq_counts
unq
unq_avg

rawDescription: average of all rows corresponing to all unique rows

description: Average of all rows corresponing to all unique rows


code: six

rawDescription: python setup.py sdist and custom setup keywords don't play together

description: Python setup.py sdist and custom setup keywords don't play together


code: TfidfVectorizer(**params)

rawDescription: Python Sklearn : Dynamically set parameters for TfIdfVectorizer


code:
from django.db.models.signals import post_save, pre_save, pre_delete

pre_save.connect(pre_save_checkout, Checkout)
pre_delete.connect(pre_save_checkout, Checkout)
post_save.connect(post_save_checkout, Checkout)

rawDescription: How can I get a total count of a model's related objects and the model's children's related objects?

description: Get a total count of a model's related objects and the model's children's related objects


rawDescription: regex - matching number with optional range

description: Regex - matching number with optional range


code:
# whichclient.py
from twisted.python.filepath import FilePath
from twisted.internet.endpoints import SSL4ServerEndpoint
from twisted.internet.ssl import PrivateCertificate, Certificate
from twisted.internet.defer import Deferred
from twisted.internet.task import react
from twisted.internet.protocol import Protocol, Factory

class ReportWhichClient(Protocol):
    def dataReceived(self, data):
        peerCertificate = Certificate.peerFromTransport(self.transport)
        print(peerCertificate.getSubject().commonName.decode('utf-8'))
        self.transport.loseConnection()

def main(reactor):
    pemBytes = FilePath(b"ca-private-cert.pem").getContent()
    certificateAuthority = Certificate.loadPEM(pemBytes)
    myCertificate = PrivateCertificate.loadPEM(pemBytes)
    serverEndpoint = SSL4ServerEndpoint(
        reactor, 4321, myCertificate.options(certificateAuthority)
    )
    serverEndpoint.listen(Factory.forProtocol(ReportWhichClient))
    return Deferred()

react(main, [])

rawDescription: Use TLS and Python for authentication

description: Use TLS and Python for authentication


code:
import inspect
def func(a,b,c=42, *args, **kwargs): pass
inspect.getargspec(func)

rawDescription: Can you list the keyword arguments a Python function receives?

description: List the keyword arguments a Python function receives


code:
from BeautifulSoup import BeautifulStoneSoup, Tag, NavigableString

soup = BeautifulStoneSoup('config-template.xml') # get the parser for the xml file
soup.contents[0].name
# u'root'

rawDescription: Editing XML as a dictionary in python?

description: Editing XML as a dictionary in python


code:
strs = "#define MOREOFTHESAME 1"
strs.split()
strs.split()[1:]

rawDescription: Create a specialized dictionary from a text file


code:
def consolidate(start, end):
    _start = start[:]                # Make a copy since we're modifying the list
    result = []
    for i in range(len(_start)-1):   # Iterate until the second-to-last pair
        if _start[i+1] == end[i]+1:  # If two pairs are contiguous,
            _start[i+1] = _start[i]  # replace the start value with the previous one
        else:                                  # Otherwise
            result.append((_start[i], end[i])) # add the current pair to the result
    result.append((_start[i+1], end[i+1]))     # Don't forget the ultimate pair
    return result

rawDescription: Python data manipulation for a particular data set


code:
from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

for grp in (grouper(my_list,3)):
    print("".join(grp))

rawDescription: How to retrieve groups of n items in list

description: Retrieve groups of n items in list


rawDescription: Shuffle groups of sublists in Python

description: Shuffle groups of sublists in Python


code:
#!/usr/bin/env python2
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.properties import ObjectProperty

Builder.load_string('''
#:kivy 1.6
[SideBar@BoxLayout]:
    content: content
    orientation: 'vertical'
    size_hint: ctx.size_hint if hasattr(ctx, 'size_hint') else (1, 1)
    Image:
        source: ctx.image
        size_hint: (1, None)
        height: root.width
    GridLayout:
        cols: 2
        # just add a id that can be accessed later on
        id: content

<Root>:
    content: sb.content
    Button:
        center_x: root.center_x
        text: 'press to add_widgets'
        size_hint: .2, .2
        on_press:
            sb.content.clear_widgets()
            root.load_content()
    SideBar:
        id: sb
        size_hint: .2, 1
        image: 'data/images/image-loading.gif'
''')

class Root(FloatLayout):

    content = ObjectProperty(None)
    '''This is initialised to None and in kv code at line 28
    above (the one with `content: sb.content`) a ref to the
    actual content is passed'''

    def load_content(self):
        content = self.content
        for but in range(20):
            content.add_widget(Button(
                                text=str(but)))

class MyApp(App):
    def build(self):
        return Root()

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

rawDescription: Kivy template with dynamic grid layout

description: Kivy template with dynamic grid layout


code:
number = [i[0] for i in data if i[1]==max_1]
number

rawDescription: Indexing Elements in a list of tuples

description: Indexing Elements in a list of tuples


code:
Number2, Type2, Card2 = None, None, None

def second_card():
    global Number2, Type2, Card2
    Number2 = random.choice(Numbers)
    Type2 = random.choice(Types)
    Card2 = Number2 + " of " + Type2
    if Card2 == Card:
        second_card()

second_card()

rawDescription: using global variables in a python game

description: Using global variables in a python game


code:
import string
allTheLetters = string.lowercase

rawDescription: How do I iterate through a string in Python?

description: Iterate through a string in Python


code:
import itertools, pprint
mylist = ["Eat","Sleep","Drink"]
my_combination = list(itertools.product(mylist, repeat = 2))
pprint.pprint (my_combination)

rawDescription: How to create a list or every permutation in a group of objects N-deep

description: Create a list or every permutation in a group of objects N-deep


rawDescription: (Python) Breaking an output text file into tokens


code:
df1 = pd.DataFrame({'c': ['A', 'A', 'B', 'C', 'C'],
                    'k': [1, 2, 2, 2, 2],
                    'l': ['a', 'b', 'a', 'a', 'd']})
df2 = pd.DataFrame({'c': ['A', 'C'],
                    'l': ['b', 'a']})

# create a column marking df2 values
df2['marker'] = 1

# join the two, keeping all of df1's indices
joined = pd.merge(df1, df2, on=['c', 'l'], how='left')
joined

rawDescription: pandas - filter dataframe by another dataframe by row elements

description: Pandas - filter dataframe by another dataframe by row elements


code: soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)

rawDescription: How to only print certain text using BeautifulSoup

description: Only print certain text using BeautifulSoup


code:
import random
import pprint
import time

# small sample maze
maze = ['.....',
        '...#.',
        '.#...',
        '.#.#.',
        '.#...']
# convert to boolean maze
maze_bin = [[True if cell == '.' else False for cell in line] for line in maze]

# uncomment to generate a random maze
# maze_size = 500
# threshold = 0.2
# maze_bin = [[1 if random.random() >= threshold else 0 for _ in range(maze_size)] for _ in range(maze_size)]

# take start time
t1 = time.time()

# rotate the maze (first column becomes first row, first row becomes first column)
maze_bin_rot = [[maze_bin[i][j] for i in range(len(maze_bin))] for j in range(len(maze_bin[0]))]

# horizontal_lengths is a two-dimensional list that contains the number of possible steps to the right for every cell.
horizontal_lengths = []
for line in maze_bin:
    num = 0
    line_lengths = []
    for i in reversed(line):
        line_lengths.append(i*num)
        num = i * (num + i)
    horizontal_lengths.append(tuple(reversed(line_lengths)))

# vertical_lengths is a two-dimensional list that contains the number of possible steps to the bottom for every cell.
vertical_lengths_rot = []
for line in maze_bin_rot:
    num = 0
    line_lengths = []
    for i in reversed(line):
        line_lengths.append(i*num)
        num = i * (num + i)
    vertical_lengths_rot.append(tuple(reversed(line_lengths)))
# do the rotation again to be back in normal coordinates
vertical_lengths = [[vertical_lengths_rot[i][j] for i in range(len(vertical_lengths_rot))] for j in range(len(vertical_lengths_rot[0]))]

# calculate the maximum size of a square that has it's upper left corner at (x, y).
# this is the minimum of the possible steps to the right and to the bottom.
max_possible_square = []
for y in range(len(maze_bin)):
    line = []
    for x in range(len(maze_bin[0])):
        line.append(min(horizontal_lengths[y][x], vertical_lengths[y][x]))
    max_possible_square.append(line)

# search for squares
results = []
max_size_square = (-1, -1, -1)
for y in range(len(max_possible_square)):
    for x in range(len(max_possible_square[0])):
        # start with maximum possible size and decrease size until a square is found.
        for size in reversed(range(1, max_possible_square[y][x]+1)):
            # look at the upper right (x+size,y) and bottom left corner (x,y+size).
            # if it's possible to make at least size steps to the right from the bottom left corner
            # and at least size steps to the bottom from the upper right corner, this is a valid square.
            if horizontal_lengths[y+size][x] >= size and vertical_lengths[y][x+size] >= size:
                results.append((x, y, size+1))
                if size+1 > max_size_square[2]:
                    max_size_square = (x, y, size+1)
                # break after the the largest square with upper left corner (x,y) has been found.
                break

t2 = time.time()

# comment this print section if you use larger grids
print('Maze:')
pprint.pprint(maze_bin)
print('\n')
print('Horizontal possible steps:')
pprint.pprint(horizontal_lengths)
print('\n')
print('Vertical possible steps:')
pprint.pprint(vertical_lengths)
print('\n')
print('Maximum possible size of square:')
pprint.pprint(max_possible_square)
print('\n')
print('Results:')
for square in results:
    print('Square: x={}, y={}, size={}'.format(*square))
print('\n')

# final results
print('Finished after {:.3f} seconds.'.format(t2-t1))
print('Result: {} squares found, maximum square (x={}, y={}, size={}).'.format(len(results), *max_size_square))

rawDescription: Finding the largest square in an n * n grid


code:
b = np.array(list_a)
b.min(axis=1)

rawDescription: Iteratively find minimum values in sub-lists


rawDescription: Difference between np.random.seed() and np.random.RandomState()


code:
for file in ('file.%5d' % i for i in xrange(0, 99999, 90)):
    ...

rawDescription: loop over files in python?

description: Loop over files in python


code:
def employee_detail(request, employee_id):
    return object_detail(
        request,
        queryset= Employee.objects.all(),
        extra_context ={"EC_list": EmergencyContact.objects.filter(employee__pk=employee_id)},
        object_id=employee_id)

rawDescription: Populate templates using list,detail generic views


code:
import sys
show_hidden_args = '--help-long' in sys.argv

opt = argparse.ArgumentParser()
opt.add_argument('--hidden-arg', help='...' if show_hidden_args else argparse.SUPPRESS)
opt.add_argument('--help-long', help='Show all options.', action='help')

args = opt.parse_args()

rawDescription: Show hidden option using argparse

description: Show hidden option using argparse


code: MODULES = dict([(s.key, s) for s in ALL_MODULES if s['enabled']])

rawDescription: Only include enabled objects in dict() - Python


rawDescription: django: how to get a substring?

description: Django: how to get a substring


code:
s = bytes(s, 'utf-8')    # Or other appropriate encoding
struct.pack("I%ds" % (len(s),), len(s), s)

rawDescription: packing and unpacking variable length array/string using the struct module in python

description: Packing and unpacking variable length array/string using the struct module in python


code: classifier_list = [c() for c in (ClassifierA, ClassifierB, ...)]

rawDescription: Fudging the line between classes and functions


code:
_Foo_default = object()
class Foo(object):
    def __init__(self, required_arg=_Foo_default):
        if required_arg is _Foo_default:
            raise ValueError("Expected a user-supplied value for required_arg")

rawDescription: Is there an elegant and pythonic way to require inputs for a class constructor?


code:
import re
hyphensplit = re.compile('(-[a-z]+)').split
images = ['pdf-one','gif-two','jpg-three']
[part for img in images for part in hyphensplit(img) if part]

rawDescription: How to split list element into two?

description: Split list element into two


code:
import numpy as np
x = np.arange(m+1)
y = np.arange(n+1)
X, Y = np.meshgrid(x, y)

rawDescription: Creation and usage coordinates grid

description: Creation and usage coordinates grid


code:
import subprocess
import os
p = subprocess.Popen(["unzip", "-tqq", "encrypted.zip"],
                     stdin=open(os.devnull), preexec_fn=os.setsid)
p.communicate()

rawDescription: prevent unexpected stdin reads and lock in subprocess

description: Prevent unexpected stdin reads and lock in subprocess


code:
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')

rawDescription: pandas - parsing column containing strings and column containing int into datetime

description: Pandas - parsing column containing strings and column containing int into datetime


code:
def gui(item):
    if item == 'a':
       pass # do something with a
    elif item == 'b':
       pass # do something with b

rawDescription: Python tkinter menu + variable

description: Python tkinter menu + variable


code:
import pandas as pd
import pdb, random

def multiYearData(data, start_y, until_y, fill_leap):
    def leapyr(n):
        if n % 4 != 0:
            return False
        elif n % 100 != 0:
            return True
        elif n % 400 != 0:
            return False
        else:
            return True

    multi_year = []
    for y in range(start_y,until_y):
        if leapyr(y):
            multi_year.extend( data[:60] + [fill_leap] + data[60:] )
        else:
            multi_year.extend(data)
    return multi_year

start_y = 1950
until_y = 1960

dates = pd.date_range(str(start_y)+'-01-01', str(until_y-1)+'-12-31', freq='D')

data  = [int(1000.*random.random()) for i in xrange(365)]
data = multiYearData(data, start_y, until_y, fill_leap=100000)

cum_data = pd.Series(data, index=dates)

rawDescription: Repeat pandas dataframe over time

description: Repeat pandas dataframe over time


code:
self.input_states = {self.PINPUT, self.PINPUTDOWN, self.PINPUTNONE}

# later
if value in self.input_states:
    do_something()

rawDescription: Pythonic way of checking bit values

description: Pythonic way of checking bit values


code:
for d in listA:
    d["score"] = scores[d["flag1"], d["flag2"]]

rawDescription: Assign scores based on truth table without the use of if-else constructs


rawDescription: Generating a string with python using loops with logic conditions issues against join function alternative?


code:
m = Member(yourargs)
m.save()

adress1 = AdressPL(yourargs)
adress1.member = m
adress1.save()

adress2 = AdressPL(yourargs)
adress2.member = m
adress2.save()

m = Member.objects.get(pk=m.pk)

m.adresses.all() # will output a list of BaseAdresse instances

rawDescription: Design pattern to solve different validations on Django Models


code:
def maybe_foo(value):
    if value > 1:
        return new_object(value)
    return None

rawDescription: return something other than the object on creation of object

description: Return something other than the object on creation of object


code: angle = (1-alpha)*(angle + gyro * dt) + (alpha)*(acc)

rawDescription: Complementary Filter Code Not Working

description: Complementary Filter Code Not Working


code:
for A in range(1,3):
    for B in range(4,6):
        for C in range(7,10):
            print(A,B,C)

rawDescription: how to output the result of a nested loop using Python

description: Output the result of a nested loop using Python


code:
lin = [i.strip().split(', ') for i in open(sys.argv[1]).readlines()]
lin = sorted(lin)

rawDescription: Pythonic Way to Sort a List of Comma Separated Numbers


code:
from django.conf.urls import patterns, include, url
import registration.backends.default.urls as regUrls
from registration.views import register
from userInfo.forms import  RegistrationFormEx

urlpatterns = patterns('',
url(r'^accounts/register/$', register, {'backend': 'registration.backends.default.DefaultBackend','form_class': RegistrationFormEx}, name='registration_register'),
(r'^accounts/', include('registration.backends.default.urls'))

)

rawDescription: how to use django's registration field(s) to custom table

description: Use django's registration field(s) to custom table


code:
{u'Carlton': [(u'Disposals', u'315'),
              (u'Kicks', u'224'),
              (u'Handballs', u'91'),
              (u'Free Kicks', u'22'),
              (u'Clearances', u'39'),
              (u'Centre', u'13'),
              (u'Stoppages', u'26'),
              (u'Inside 50', u'40'),
              (u'Marks in 50', u'8'),
              (u'Contested Possessions', u'127'),
              (u'Tackles', u'59'),
              (u'Hit-Outs', u'23'),
              (u'Interchanges', u'111')],
 u'Fremantle': [(u'Disposals', u'311'),
                (u'Kicks', u'190'),
                (u'Handballs', u'121'),
                (u'Free Kicks', u'14'),
                (u'Clearances', u'38'),
                (u'Centre', u'10'),
                (u'Stoppages', u'28'),
                (u'Inside 50', u'47'),
                (u'Marks in 50', u'13'),
                (u'Contested Possessions', u'124'),
                (u'Tackles', u'63'),
                (u'Hit-Outs', u'75'),
                (u'Interchanges', u'96')]}

rawDescription: Fetch Stats using Beautiful Soup

description: Fetch Stats using Beautiful Soup


code:
def closest_split_pair(p_x, p_y, delta, best_pair): # <- a parameter
    ln_x = len(p_x)
    mx_x = p_x[ln_x // 2][0]
    s_y = [x for x in p_y if mx_x - delta <= x[0] <= mx_x + delta]
    best = delta
    for i in range(len(s_y) - 1):
        for j in range(1, min(i + 7, (len(s_y) - i))):
            p, q = s_y[i], s_y[i + j]
            dst = dist(p, q)
            if dst < best:
                best_pair = p, q
                best = dst
    return best_pair

rawDescription: Closest Pair Implemetation Python

description: Closest Pair Implemetation Python


rawDescription: Pandas: drop rows with a column value, & remove for other subrows


code: cursor.executemany("INSERT INTO table VALUES(?,?,?,?,?)", manyargs)

rawDescription: Only inserting specific rows from csv file into Sqlite3 database using python


code:
self.imageCtrl = wx.StaticBitmap(self.panel, wx.ID_ANY,
                                  wx.BitmapFromImage(img))
self.imageCtrl.SetBitmap(wx.BitmapFromImage(img))

rawDescription: wxpython image doesn't fit on screen

description: Wxpython image doesn't fit on screen


code: tw.cellClicked.emit(row, column)

rawDescription: How to click a specific row in tablewidget using a function in Pyqt?

description: Click a specific row in tablewidget using a function in Pyqt


code:
response = requests.get('http://steamcommunity.com/market/search/render/?query=appid:730&start=0&count=3&currency=3&l=english&cc=pt')
html = response.json()['results_html']

rawDescription: BS4 get info from class with weird name

description: BS4 get info from class with weird name


code:
input = input.lower()
result = [item for item in all_names['all'] if item.lower() == input]

rawDescription: Python Search a Set using case-insensitive


code:
timer = QTimer()
timer.timeout.connect(QtCore.QCoreApplication.processEvents()) #This gets run every timer cycle
timer.start(1000)

rawDescription: QLCDNumber updating with processEvents() - Python 3


code: bar(x, y, width=30)

rawDescription: Controling bars width in matplotlib with per-month data


code:
def insert(path, data, node):
    if len(path) == 0:
        node["data"] = data
        return
    for child in node["children"]:
        if child["name"] == path[0]:
            insert(path[1:], data, child)
            return
    child = make_node()
    child["name"] = path[0]
    node["children"].append(child)
    insert(path[1:], data, child)

tree = make_node()
tree["name"] = "root"
for path, data in from_this:
    insert(path.split(path_sep), data, tree)
pprint.pprint(tree)

rawDescription: An idiomatic way to construct a tree in python from a list of locations / namespaces?


code:
result = set()
gen_strings(max_length, result=result)

rawDescription: Return a set from a recursive function

description: Return a set from a recursive function


code:
import pandas as pd
tables = pd.read_html('http://www.fdic.gov/bank/individual/failed/banklist.html')

rawDescription: Python Text Matrix using NumPy and pandas


code: obj = globals()[txtobj]()

rawDescription: Generating python data structures from parsed text without eval()


code:
separator = ","
userIDKey = "userID"
defaultValue = "No data"

data = {}
#collect the data
with open("data.csv", 'r') as dataFile:
    for line in dataFile:
        #remove end of line character
        line = line.replace("\n", "")

        userID, fieldName, value = line.split(separator)

        if not userID in data.keys():
            data[userID] = {userIDKey:userID}

        data[userID][fieldName] = value

#retrieve all the columns header in use
columnsHeaders = set()
for key in data:
    dataset = data[key]
    for datasetKey in dataset :
        columnsHeaders.add(datasetKey)

columnsHeaders.remove(userIDKey)
columnsHeaders = list(columnsHeaders)
columnsHeaders.sort()

def getValue(key, dic):
    if key in dic.keys():
        return dic[key]
    else:
        return defaultValue

#then export the result
with open("output.csv", 'w') as outputFile:
    #export first line of header
    outputFile.write(userIDKey)
    for header in columnsHeaders:
        outputFile.write(", {0}".format(header))
    outputFile.write("\n")
    #and export each line
    for key in data:
        dataset = data[key]
        outputFile.write(dataset[userIDKey])
        for header in columnsHeaders:
            outputFile.write(", {0}".format(getValue(header, dataset)))
        outputFile.write("\n")

rawDescription: reshaping csv by eliminating redundant row keys and merging fields using python

description: Reshaping csv by eliminating redundant row keys and merging fields using python


rawDescription: how to sort files by the value of a dictionary using python

description: Sort files by the value of a dictionary using python


code: d = pd.DataFrame(s.values.reshape(1000000, -1))

rawDescription: Splitting pandas series into multiple columns


code:
from itertools import combinations

list(combinations(terms, r=2))

rawDescription: Python create many-to-many relationships from a list


code:
x = 0
def outer():
    x = 1
    def inner():
        global x
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)

# inner: 2
# outer: 1
# global: 2

rawDescription: Python nonlocal statement

description: Python nonlocal statement


rawDescription: Find common rows of 2 dataframe for 2 columns


code: df1.index & df2.index

rawDescription: Finding common rows (intersection) in two Pandas dataframes


code:
('The singular of ', 'apples', ' is ', 'apple')
('The singular of ', 'sheep', ' is ', 'sheep')
('The singular of ', 'oranges', ' is ', 'orange')
('The singular of ', 'cats', ' is ', 'cat')
('The singular of ', 'people', ' is ', 'person')
('The singular of ', 'dice', ' is ', 'die')
('The singular of ', 'pence', ' is ', 'pence')

rawDescription: convert plural nouns to singular NLP

description: Convert plural nouns to singular NLP


code:
from foo import ModClass
ModClass.class_method()

rawDescription: In Python how do I use a class method without passing an instance to it?


rawDescription: Resample while keeping last date from input file (and not last day computed by `resample`)


code:
def Leading_White_Space(input_str):
  for i, c in enumerate(input_str):
    if c != ' ':
      return input_str[i:]

rawDescription: How to remove or strip off white spaces without using strip() function?

description: Remove or strip off white spaces without using strip() function


code:
class Foo(object):
    def __init__(self, val1):
        self.val1 = val1

class Goo(Foo):
    def __init__(self, val1, val2):
        super(val1)
        self.val2 = val2

f=Foo(1)
f.__class__
f.__class__ = Goo
f
type(f)

rawDescription: Python change self to inherited class

description: Python change self to inherited class


code:
[ i for i, substr in enumerate(list) if re.match("\d\.\d{4}", substr) ]
list[21:24]
status = list[20]
status

rawDescription: What is the most efficient method to parse this line of text?


rawDescription: Numpy quirk: Apply function to all pairs of two 1D arrays, to get one 2D array


code:
from django.template import loader
# downloaded from djangosnippets.com[942]
from my_project.snippets.template import render_block_to_string

def ajax_view(request):
    # some random context
    context = Context({'items': range(100)})
    # passing the template_name + block_name + context
    return_str = render_block_to_string('standard/subtemplate.html', 'results', context)
    return HttpResponse(return_str)

rawDescription: Rendering JSON objects using a Django template after an Ajax call


code:
d = defaultdict(dict)
d['a']['values'] = []
d['b']['values'] = []
d['a']['values'].append('a')
d['a']['values'].append('b')
print(d)

rawDescription: How to address a dictionary in a list of ordered dicts by unique key value?

description: Address a dictionary in a list of ordered dicts by unique key value


code:
# generate f values
def cToF(low=0, high=100):
    for c in range(low, high + 1):
        yield c * 9 / 5 + 32

# generate c values
def fToC(low=32, high=212):
    for f in range(low, high + 1):
        yield (f - 32) * 5 / 9

# iterate over pairs of f and c values
# will stop once cToF is exhausted since it generates fewer values than fToC
for f, c in zip(cToF(), fToC()):
    print('{}\t\t{}'.format(f, c))

rawDescription: Print two functions side by side

description: Print two functions side by side


code:
# inner is a default value so it could be omitted
df1.join(df2, df1.k == df2.k, joinType='inner')
sqlContext.sql('SELECT * FROM df1 JOIN df2 ON df1.k = df2.k')

rawDescription: How do you perform basic joins of two RDD tables in Spark using Python?

description: Perform basic joins of two RDD tables in Spark using Python


rawDescription: Simple way to toggle fullscreen with F11 in PyGTK


code: self.returncode = self.process.wait()

rawDescription: Best Approach to Threading/Spawning Multiple OS Commands and Getting Output at Various Points


rawDescription: Pandas dataframe with MultiIndex: check if string is contained in index level


code:
def guess_seq_len(seq):
    guess = 1
    max_len = len(seq) / 2
    for x in range(2, max_len):
        if seq[0:x] == seq[x:2*x] :
            guess = x

    return guess

rawDescription: Python finding repeating sequence in list of integers?


code:
from BeautifulSoup import BeautifulStoneSoup
xml = """<ns0:feed ns1:etag="W/"LIESANDCRAPfyt7I2A9WhHERE."" xmlns:ns4="http://www.w3.org/2007/app" xmlns:ns3="http://schemas.google.com/contact/2008" xmlns:ns2="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:ns1="http://schemas.google.com/g/2005" xmlns:ns0="http://www.w3.org/2005/Atom">
            <ns0:updated>2012-01-25T14:52:12.867Z</ns0:updated>
            <ns0:category term="http://schemas.google.com/contact/2008#profile" scheme="http://schemas.google.com/g/2005#kind"/>
            <ns0:id>domain.com</ns0:id>
            <ns0:generator version="1.0" uri="http://www.google.com/m8/feeds">Contacts</ns0:generator>
            <ns0:author>
                <ns0:name>domain.com</ns0:name>
            </ns0:author>
            <ns0:link type="text/html" rel="alternate" href="http://www.google.com/"/>
            <ns0:link type="application/atom+xml" rel="http://schemas.google.com/g/2005#feed" href="https://www.google.com/m8/feeds/profiles/domain/domain.com/full"/>
            <ns0:link type="application/atom+xml" rel="http://schemas.google.com/g/2005#batch" href="https://www.google.com/m8/feeds/profiles/domain/domain.com/full/batch"/>
            <ns0:link type="application/atom+xml" rel="self" href="https://www.google.com/m8/feeds/profiles/domain/domain.com/full?max-results=300"/>
            <ns2:startIndex>1</ns2:startIndex>
            <ns2:itemsPerPage>300</ns2:itemsPerPage>
            <ns0:entry ns1:etag=""CRAPQR4KTit7I2A4"">
                <ns0:category term="http://schemas.google.com/contact/2008#profile" scheme="http://schemas.google.com/g/2005#kind"/>
                <ns0:id>http://www.google.com/m8/feeds/profiles/domain/domain.com/full/nperson</ns0:id>
                <ns1:name>
                    <ns1:familyName>Person</ns1:familyName>
                    <ns1:fullName>Name Person</ns1:fullName>
                    <ns1:givenName>Name</ns1:givenName>
                </ns1:name>
                <ns0:updated>2012-01-25T14:52:13.081Z</ns0:updated>
                <ns1:organization rel="http://schemas.google.com/g/2005#work" primary="true">
                    <ns1:orgTitle>JobField</ns1:orgTitle>
                    <ns1:orgDepartment>DepartmentField</ns1:orgDepartment>
                    <ns1:orgName>CompanyField</ns1:orgName>
                </ns1:organization>
                <ns3:status indexed="true"/>
                <ns0:title>Name Person</ns0:title>
                <ns0:link type="image/*" rel="http://schemas.google.com/contacts/2008/rel#photo" href="https://www.google.com/m8/feeds/photos/profile/domain.com/nperson"/>
                <ns0:link type="application/atom+xml" rel="self" href="https://www.google.com/m8/feeds/profiles/domain/domain.com/full/nperson"/>
                <ns0:link type="application/atom+xml" rel="edit" href="https://www.google.com/m8/feeds/profiles/domain/domain.com/full/nperson"/>
                <ns1:email rel="http://schemas.google.com/g/2005#other" address="nperson@gapps.domain.com"/>
                <ns1:email rel="http://schemas.google.com/g/2005#other" primary="true" address="nperson@domain.com"/>
                <ns4:edited>2012-01-25T14:52:13.081Z</ns4:edited>
            </ns0:entry>
            <ns0:title>domain.com's Profiles</ns0:title>
        </ns0:feed>"""

rawDescription: Recursively search xml by entry

description: Recursively search xml by entry


code: decorated

rawDescription: How can I sort 2 lists of lists by column?

description: Sort 2 lists of lists by column


rawDescription: Delete a group after pandas groupby

description: Delete a group after pandas groupby


code:
p = Plan.objects.get(pk=1) # get a Plan
p.region.weather_set.all() # all "weathers" for the region for this plan
p.district.weather_set.all() # all "weathers" for the district for this plan

rawDescription: How to join the results of two tables in django python

description: Join the results of two tables in django python


code: l2 = map(lambda x: x / 25., l1)

rawDescription: python list average over bin sizes

description: Python list average over bin sizes


rawDescription: Python text processing: NLTK and pandas

description: Python text processing: NLTK and pandas


code:
with open('corpus.vert') as c:
    corpus = [CorpusEntry(*line.strip().split('\t')) for line in c
              if len(line.strip() > 1) and not line.startswith('<')]

def get_frequencies(lemma):
    lemma_indices = {index for index, entry in enumerate(corpus)
                     if entry.lemma == lemma}
    related_lemmas = {entry.lemma for index, entry in enumerate(corpus)
                      if lemma_indices & {index+1, index-1}}
    return Counter(entry.lemma for entry in corpus
                   if entry.lemma in related_lemmas)

rawDescription: How to count word frequency from a list in the whole file?

description: Count word frequency from a list in the whole file


code:
import base64
import struct

encoded = 'Dn3LQ3np ... 9BnKRA=='

# decode the string
data = base64.standard_b64decode(encoded)

# ensure that there's enough data for 32-bit floats
assert len(data) % 4 == 0

# determine how many floats there are
count = len(data) // 4

# unpack the data as floats
result = struct.unpack('<{0}f'.format(count), # one big structure of `count` floats
                       data)                  # results returned as a tuple

rawDescription: decoding, little endian, uncompressed and float array

description: Decoding, little endian, uncompressed and float array


code:
u';'.encode('utf-16be')
UDAT.name(u';')
hex(ord(u';'))
u'\u003b' == u'\N{SEMICOLON}'
u'\N{GREEK QUESTION MARK}' == u'\N{SEMICOLON}'

rawDescription: Produce unicode obj from string in python?


code:
from datetime import date
difference = date.today()
difference.strftime('%Y%m%d')

rawDescription: Two-Digit dates in Python

description: Two-Digit dates in Python


rawDescription: Returning Data from Python Function for use with Jinja2 Template (Flask)


code: writeToFile(haikuList)

rawDescription: Writing to a File, Adding an Additional Space


code:
from functools import partial
repeat(partial(bar, 42))

rawDescription: Python, how to pass an argument to a function pointer parameter?


code:
def test_added():
    assert added(4, 6, 7) == (13, 11, 10)

rawDescription: How to make a test function using pytest

description: Make a test function using pytest


code: dictionary = dict((d.pop('offer'), d) for d in list_of_dicts)

rawDescription: Python: Fastest way to make dict from list of dicts


code:
def runningMean(iterable):
    """A generator, yielding a cumulative average of its input."""
    num = 0
    denom = 0
    for x in iterable:
        num += x
        denom += 1
        yield num / denom

rawDescription: To stop finding running average once the condition fails?


code:
cv.SetImageROI(blue,(100,100,50,50))
cv.Copy(red, blue)
cv.ResetImageROI(blue)

rawDescription: IplImage inside IplImage

description: IplImage inside IplImage


code:
mywords = ['red', 'blue', 'red', 'green', 'blue', 'blue']
myletters=list("".join(mywords))
myletters
Counter(myletters)

rawDescription: Sorting a list by frequency of letter in python (decreasing order)


rawDescription: Issues ith loop is django

description: Issues ith loop is django


code:
banned_string = "word1 word2 word3"
banned_string.split()

rawDescription: IRC bot, making a list of banned words?

description: IRC bot, making a list of banned words


code:
#!/usr/bin/env python
import time
from flask import Flask, Response

app = Flask(__name__)

def stream_template(template_name, **context):
    # http://flask.pocoo.org/docs/patterns/streaming/#streaming-from-templates
    app.update_template_context(context)
    t = app.jinja_env.get_template(template_name)
    rv = t.stream(context)
    # uncomment if you don't need immediate reaction
    ##rv.enable_buffering(5)
    return rv

@app.route('/')
def index():
    def g():
        for i, c in enumerate("hello"*10):
            time.sleep(.1)  # an artificial delay
            yield i, c
    return Response(stream_template('index.html', data=g()))

if __name__ == "__main__":
    app.run(host='localhost', port=23423)

rawDescription: Streaming data with Python and Flask

description: Streaming data with Python and Flask


rawDescription: Python NumPy Arrays

description: Python NumPy Arrays


code:
import os, datetime
mydir = os.path.join(os.getcwd(), datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
os.makedirs(mydir)
with open(os.path.join(mydir, 'filename.txt'), 'w') as d:
    pass # ... etc ...

rawDescription: Creating a folder with timestamp

description: Creating a folder with timestamp


code:
years = range(2012, 2015)
yearly_month_stats = [dfts.xs(str(year)).groupby(lambda x : x.month).mean() for year in years]
df2 = pd.concat(yearly_month_stats, axis=1, keys = years)

rawDescription: Group by multiple time units in pandas data frame


code:
import numpy as np
a = np.array([[1,2,3], [4,5,6]])
a
a.ravel()

rawDescription: How do you unroll a Numpy array of (mxn) dimentions into a single vector

description: Unroll a Numpy array of (mxn) dimentions into a single vector


code:
[df[1:]]
df.as_matrix(columns=[df[1:]])

rawDescription: Convert Select Columns in Pandas Dataframe to Numpy Array


code:
import csv
filename = 'soc153.csv'
def get_names(filename):
    in_list = []
    with open(filename, 'r') as f:
        reader = csv.reader(f)
        header_line = next(reader)
        name_column = header_line.index('Name')
        for row in reader:
            in_list.append(row[name_column])
    return(sorted(in_list))
if input("Do you wish to view previous results for your class?") == 'y':
    name_list = get_names(filename)

rawDescription: Fixing outputting csv file in alphabetical order in python


code:
from fabric.api import task, env, run, cd
from fabric.context_managers import prefix

env.hosts = ('wf_username@wf_username.webfactional.com',)
env.forward_agent = True

MANAGEPY = '~/webapps/my_project/code/my_project/manage.py'
PY = '~/webapps/my_project/env/bin/python2.7'

@task
def deploy():
    with cd('~/webapps/my_project/code/'):
        with prefix('source production'):
            run('git pull --rebase origin master')
            run('pip install -r requirements.txt')
            run('{} {} migrate'.format(PY, MANAGEPY))
            run('{} {} collectstatic --noinput'.format(PY, MANAGEPY))
            run('touch my_project/my_project/wsgi.py')

rawDescription: Django Deployment Process to Webfaction.com


code:
sage: c = C()
sage: c.scale(3)
3
sage: c.scaling_method = "double"
sage: c.scale(3)
6

rawDescription: Changing dynamically one method of a class


code:
r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        for chunk in r:
            f.write(chunk)

rawDescription: How to download image using requests

description: Download image using requests


rawDescription: Django ORM Query to limit for the specific key instance


code:
def iCollide (self):
    for Ball in self.overlapping_sprites:

        #Extract the components of the slab's velocity
        slab_vx, slab_vy = self.iVelocity()

        #Compute relative components of slab velocity
        rel_vx, rel_vy = Ball.dx - slab_vx, Ball.dy - slab_vy

        #Determine the time of intersection and the normal direction
        #This is done to compute which face the ball hits
        #Initially suppose that the objects intersect at t=infinity
        t, nx, ny = 100000, 0, 0

        #Check left/right faces
        if rel_vx != 0:
            #Check if ball hits left face
            toi = (self.left - Ball.right) / rel_vx
            if toi < t:
                t, nx, ny = toi, -1, 0

            #Check if ball hits right face
            toi = (self.right - Ball.left) / rel_vx

            if toi < t:
                t, nx, ny = toi, 1, 0

        #Check top/bottom faces:
        if rel_vy != 0:

            #Check if ball hits top face
            toi = (self.top - Ball.bottom) / rel_vx
            if toi < t:
                t, nx, ny = toi, 0, -1

            #Check if ball hits right face
            toi = (self.bottom - Ball.top) / rel_vx
            if toi < t:
                t, nx, ny = toi, 0, 1

        #Check if impact force properly corrects velocity
        if Ball.dx * nx + Ball.dy * ny < 0:

            #Reflect the ball's position
            Ball.dx += Ball.dx * nx * 2.0
            Ball.dy += Ball.dy * ny * 2.0

        #Check if cursor movement is not pushing ball into paddle:
        if slab_vx * nx + slab_vy * ny < 0:
            Ball.dx += slab_vx
            Ball.dy += slab.vy

rawDescription: Debugging ping pong game in Python

description: Debugging ping pong game in Python


code:
# read a file
with  open("test.txt",'r') as f:
    lista_lekova = open("test.txt",'r').readlines()

# get a line number to change
izbrisanilek = input("Lek pod kojim brojem zelite da izmenite:  ")
izbrisaniLek = int(izbrisanilek)
izbrisaniLek = izbrisaniLek - 1

# here will be stored output lines
out_lines = []

#iterate for each line and change izbrisaniLek line
for k,lek in enumerate(lista_lekova):

    # the spliting can also be avoided, just to change False to True.
    # But you seem to do some reformatting of other values.
    deo = list(map(lambda v: v.strip(), lek.split('|')))

    # change False to True for the selected line.
    # it always makes it true. Not sure if you want to toggle the values, or just always have True there.
    if k == izbrisaniLek:
        deo[5] = 'True'

    ceoLek = "|".join(deo)
    #print(ceoLek)
    out_lines.append(ceoLek)

# save output files to a file
with open("lekovi_out.txt" , "w") as f:
    f.writelines(out_lines)

rawDescription: How to change only 1 parameter in file?

description: Change only 1 parameter in file


rawDescription: Reading a file to a dictionary

description: Reading a file to a dictionary


code: XGBClassifier(grid)

rawDescription: XGBoost XGBClassifier Defaults in Python


code:
#_private.py
from django.core.management.base import BaseCommand, CommandError

class SharedCommand(BaseCommand):
   def check_validity(self, color):
      ...

rawDescription: How to abstract away command code in custom django commands

description: Abstract away command code in custom django commands


code:
def name_gen():
    with open('C:/python/namessample.txt') as nameFile:
        for line in nameFile:
            for name in line.rstrip('\n').split(','):
                yield name.strip('"')

rawDescription: generating strings from a file

description: Generating strings from a file


rawDescription: python print a variable as a string from a list

description: Python print a variable as a string from a list


rawDescription: Python tkinter delete tuple tag

description: Python tkinter delete tuple tag


code:
def make_24_hosts(prefix):
    return (prefix + str(x) for x in range(1, 255))

rawDescription: Create list with for loop for incrementing IP address


code: return node

rawDescription: How can I abort an AST visitor and leave the original node unchanged?

description: Abort an AST visitor and leave the original node unchanged


code:
def updateFileAttributes(self, **file_attributes):
    m = models.FileAttributes(**file_attributes)
    m.save()

rawDescription: Is it possible to convert a variable as a string?


code: root = lxml.html.fromstring(content)

rawDescription: Problems with encoding while parsing html document with lxml


code:
parity = 0x7f
parities = [int(item,16) ^ parity for item in "4e 7f 2b".split()]
#or maybe
parities = [ord(item) ^ parity for item in "somestring"]

rawDescription: Python XOR on hex and string (parity check function)


code: plt.plot(a, np.log(1 + r*a[:,None]).mean(1))

rawDescription: Plot parametric mean in Python

description: Plot parametric mean in Python


code:
class MyClass:

    def __init__(self):
        self.display_name = self.__class__.__name__

rawDescription: Dynamically get class name at class level variable in python


code: lst = [x[2].strip()[0:11] for x in [line.split(',') for line in open(fname)]]

rawDescription: How to read, in a line, all characters from column A to B

description: Read, in a line, all characters from column A to B


code:
def mod_dice(trials, numbers):
    """A dice with 6 faces is thrown "numbers" times in each "trial"."""
    results = Counter()
    for attempt in range(trials):
        sum = 0
        for throw in range(numbers):
            sum += randint(1, 6)
        results[sum] += 1
    return results

rawDescription: Performing sum of dice and generating the percentage with histogram


rawDescription: Pandas HDFStore of MultiIndex DataFrames: how to efficiently get all indexes


code:
import os

def splitext(path):
    for ext in ['.tar.gz', '.tar.bz2']:
        if path.endswith(ext):
            return path[:-len(ext)], path[-len(ext):]
    return os.path.splitext(path)

assert splitext('20090209.02s1.1_sequence.txt')[1] == '.txt'
assert splitext('SRR002321.fastq.bz2')[1] == '.bz2'
assert splitext('hello.tar.gz')[1] == '.tar.gz'
assert splitext('ok.txt')[1] == '.txt'

rawDescription: What's the way to extract file extension from file name in Python?


rawDescription: Python: print unicode string stored as a variable


code:
from collections import defaultdict
d = defaultdict(list)
for x in data:
    d[x['author']].append(x)

rawDescription: How to initialize an a priori unknown number of list

description: Initialize an a priori unknown number of list


rawDescription: In python, how could I make this three line code into a one line code?


code:
import collections

s = 'xli uymgo fvsar jsb'
cnt = collections.Counter(s.replace(' ', ''))
for letter in sorted(cnt):
  print (letter, cnt[letter])

rawDescription: How to stop 's' from re-occurring twice in my loop?

description: Stop 's' from re-occurring twice in my loop


code:
class SometingModel(model.Model):

    def get_all_objects(self):
        queryset = self._meta.model.objects.all()
        # can use the below method also
        # queryset = self.__class__.objects.all()
        return queryset

rawDescription: how to get all objects by instance in django

description: Get all objects by instance in django


code:
key = raw_input("Enter name or number (i/p):")
result = streetno.get(key)

rawDescription: Retrieving Key and Values from Dictionary


code:
class Y:

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

    def __eq__(self, other):
        return self.value == other.value

rawDescription: Comparing two identical objects in Python (2.7) returns False


code:
def setUp(self):
    self.verificationErrors = []
    if self.www_address == None:
        self.selenium = selenium("localhost", 5555, "*chrome", "http://testpage.pl/")
    else:
        self.selenium = selenium("localhost", 5555, "*chrome", self.www_address)

rawDescription: How to input parameters into Selenium RC TestSuite?

description: Input parameters into Selenium RC TestSuite


rawDescription: Examples of open-source projects using Python 3 function annotations


code:
ET.tostring(root) # ElementTree
root.toxml() # minidom

rawDescription: How to modify a tag text value based on its sibling tag text value in xml with python?

description: Modify a tag text value based on its sibling tag text value in xml with python


rawDescription: getting day of years for each month in python

description: Getting day of years for each month in python


code:
while menu.menu != 'E':
    menu.Do()

rawDescription: swapping between menus in python

description: Swapping between menus in python


code: sum(sum(len(sent) for sent in inaugural.sents(fileids=[fileid])) / len(inaugural.sents(fileids=[fileid])) for fileid in inaugural.fileids()) / len(inaugural.fileids())

rawDescription: Average sentence length for every text in corpus (python3 & nltk)


code:
for sublist in thelist:
  sublist.insert(0, 9)

rawDescription: Modifying list contents in Python

description: Modifying list contents in Python


code:
url(r'^(?P<slug>[\w\-]+)-(?P<pk>\d+)/$', 'submit_deals.views.deal_page',
                                         name='deal_page'),

rawDescription: In Django how can I add the id in the slug title


code:
class Category(models.Model):
    name = models.CharField(max_length=30, unique=True)

    @models.permalink
    def get_absolute_url(self):
        return ('browser', (), {'category_id': self.id})

class Post(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=256)
    author = models.CharField(max_length=256)
    link = models.URLField(max_length=512)
    dt_published = models.DateTimeField()
    content = models.TextField()

    @models.permalink
    def get_absolute_url(self):
        return ('browser', (), {'category_id': self.category.id, 'post_id': self.id})

rawDescription: Multiple Django Model Queries Changing Independently in One View


code: lis[start : stop : step]  #default values : start = 0, stop = len(lis), step = 1

rawDescription: Selecting List Elements Periodically in Python 3


code:
def source(script, update=True):
    """
    http://pythonwise.blogspot.fr/2010/04/sourcing-shell-script.html (Miki Tebeka)
    http://stackoverflow.com/questions/3503719/#comment28061110_3505826 (ahal)
    """
    import subprocess
    import os
    proc = subprocess.Popen(
        ['bash', '-c', 'set -a && source {} && env -0'.format(script)],
        stdout=subprocess.PIPE, shell=False)
    output, err = proc.communicate()
    output = output.decode('utf8')
    env = dict((line.split("=", 1) for line in output.split('\x00') if line))
    if update:
        os.environ.update(env)
    return env

rawDescription: how to make subprocess called with call/Popen inherit environment variables

description: Make subprocess called with call/Popen inherit environment variables


code:
class Notepad(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Notepad, self).__init__(parent)
        ...

rawDescription: embedding a text editor into a widget

description: Embedding a text editor into a widget


code:
def is_prime(element):
    """ just a helper function! don't get religious about it! """
    if element == 2:
        return True
    elif element <= 1 or element % 2 == 0:
        return False
    else:
        return all(element % i for i in xrange(3, element, 2))

rawDescription: "exists" keyword in Python?

description: "exists" keyword in Python


rawDescription: Python: Omitting Content inside Capturing Regexes


code:
from ConfigParser import SafeConfigParser
class MyClass(object):
    def __init__(self, **kwargs):
        self.config = SafeConfigParser(defaults=kwargs).read('config.ini')

    def get_x(self):
        return self.config.get('constants', 'x')

rawDescription: python initialization of constants in separate file

description: Python initialization of constants in separate file


rawDescription: Reset List When Condition Met

description: Reset List When Condition Met


rawDescription: How to compress a data frame within a range?

description: Compress a data frame within a range


code:
ki
l
poutre
utre
ve

rawDescription: Converting a sed regular expression to python code


rawDescription: Sum up previous values of a column

description: Sum up previous values of a column


code:
header = HeaderStruct()
header.param1
memmove(addressof(header), b'\x01', 1)  # write LSB 0x01 in the boolean
header.param1
header.param1 == EBoolean.TRUE
header.param1 == 1   # as a special case compare against ints
header.param1.value

rawDescription: How to define C-Enumeration types in python

description: Define C-Enumeration types in python


rawDescription: Error in RK4 algorithm in Python

description: Error in RK4 algorithm in Python


code:
for ces in solutions:
    plot(t, ces[:, 0], 'b-')

rawDescription: Solve a ODE for arrays of parameters (Python)


rawDescription: Pythonic way to split math calculations

description: Pythonic way to split math calculations


code:
import csv
inputfile=['M1,After.Life,Agnieszka Wojtowicz-Vosloo,Agnieszka Wojtowicz-Vosloo,"Drama, Thriller",2009/10/2/,80\n']
list(csv.reader(inputfile))

rawDescription: How to prevent splitting by comma on expressions guarded by double quotes?

description: Prevent splitting by comma on expressions guarded by double quotes


rawDescription: Querying MongoDB (via pymongo) in case insensitive efficiently


code:
def append(l):
  for i in range(3):
    l.append(str(i))
l = []
append(l)
l

rawDescription: Python: issue in adding elements to a list


code: data4 = data4.merge(stock_df, how='left')

rawDescription: Python: Pandas: Speeding up an Apply Function


code:
import shmod

while True:
    cmd = raw_input('> ')
    args = shmod.parse_args(cmd)
    try:
        shmod.dispatch[args.function](*args.arguments)
    except KeyError:
        print('Invalid input: {!r}'.format(cmd))

rawDescription: Python - passing parameters in a command line app


code:
detA = Ix_Ix_blur * Iy_Iy_blur - Ix_Iy_blur**2
traceA = Ix_Ix_blur + Iy_Iy_blur
harmonic_mean = detA / traceA
for j, i in np.argwhere(harmonic_mean > thresh):
    cv2.circle(img, (i,j), 1, (0, 0, 255), -1, 8)

rawDescription: Speed up iteration over Numpy arrays / OpenCV cv2 image


code:
import datetime
def pprint(val):
   if val == 1:
      return '1 minute'
   x = str(datetime.timedelta(minutes=val))[:-3].split(':')
   r = ''
   if int(x[0]):
       r += x[0]+' hours' if int(x[0]) > 1 else x[0]+' hour'
   if int(x[1]):
       r += ' %s minutes' % int(x[1]) if int(x[1]) > 1 else ' %s minute' % int(x[0])
   return r.strip()

rawDescription: What is the best way to write a function that converts an integer of minutes into a string formatted in "X hour(s) Y minute(s)"?


code:
for line in data:
    print >>proc.stdin, line

rawDescription: using a python list as input for linux command that uses stdin as input

description: Using a python list as input for linux command that uses stdin as input


code:
screen.fill(GREEN)

circle_1 = pygame.draw.circle(screen, BLACK, [250, 230], 7, width_1)
circle_2 = pygame.draw.circle(screen, BLACK, [250, 260], 7, width_2)
circle_3 = pygame.draw.circle(screen, BLACK, [250, 290], 7, width_3)
circle_4 = pygame.draw.circle(screen, BLACK, [250, 320], 7, width_4)

rawDescription: pygame circle not changing

description: Pygame circle not changing


code:
def bytify(v):
  v, r = divmod(v, 256)
  yield r
  if v == 0:
     raise StopIteration
  for r in bytify(v):
    yield r

[x for x in bytify(0x12345678)]
bytes(bytify(0x12345678))
bytes(bytify(0x123456789098765432101234567890987654321))

rawDescription: Convert n-byte int to bytes in python3

description: Convert n-byte int to bytes in python3


code:
# Random data parameters
num_sample = (0, 100)
nb_sample = 1000
start_date = '2016-06-02'
freq = '2T'

random_state = np.random.RandomState(0)

# Generating random data
df = pd.DataFrame({'data': random_state.randint(num_sample[0], num_sample[1], nb_sample)},
                          index=random_state.choice(
                              pd.date_range(start=pd.to_datetime(start_date), periods=nb_sample * 3,
                                            freq=freq),
                              nb_sample))
# Removing duplicate index
df = df.groupby(df.index).first()
# Removing data for closed periods
df.loc[(df.index.hour >= 22) | (df.index.hour <= 7),'data'] = np.nan
# Resampling
df = df.resample('1T').ffill()
# Moving average by hours
df['avg'] = df['data'].rolling(window=60).mean()

ax = df.plot(kind='line', subplots=True)

rawDescription: Python Pandas - Moving Average with uneven period lengths


rawDescription: How to remove : after a + or - in python

description: Remove : after a + or - in python


code: a

rawDescription: append list of values to sublists

description: Append list of values to sublists


code:
def query_wrapper(orig_query_method):
    def _query(*args, **kwargs):
        traceback.print_tb(limit=2)
        #print(traceback.extract_stack(limit=2))
        return orig_query_method(*args, **kwargs)
    return _query

rawDescription: SQLAlchemy: Is there a way to track the line number and calling class of a query done through SQLAlchemy?


code:
@register.simple_tag(takes_context=True)
def user_is_attending(context, event):
    if type(event) != Event:
        raise template.TemplateSyntaxError("Must provide event")
    request = context['request']
    if event.attendee_set.filter(profile__user=request.user).exists():
        return 'attending'
    else:
        return 'not attending'

rawDescription: Same results within Django template tags


rawDescription: Trying to get data with BeautifulSoup

description: Trying to get data with BeautifulSoup


code:
thestr = "43 Lobsters and 3 Crabs"
y = 's'
x = thestr.count(y)

rawDescription: How do you get x amounts of y in one string and put it in another string in python?

description: Get x amounts of y in one string and put it in another string in python


code:
Demonstration
class MagicList(list):
    def __bool__(self): # Python 3 uses __bool__ instead of __nonzero__
        return any(self)
    __nonzero__=__bool__ # ensure Python 2 <-> 3 compatibility

rawDescription: Python, how to implement a list subclass that evaluates as False if its items evaluate False?


code: ret_group = matches.groupby(['year', 'winner']).apply(lambda x: x[(x['score'].str.contains('RET').fillna(False))].count())

rawDescription: create new dataframe based on group by and aggregates

description: Create new dataframe based on group by and aggregates


code: target.write("%s %s %s %s %s %s") % (line1, linebreak, line2, linebreak, line3, linebreak)

rawDescription: Total Python Noob: why doesn't this work?


code:
for d in data["screen"]:
    print ("https://",d["server"],"/test/test.php?=",d["code"],sep='')

rawDescription: python loop with JSON, rather then manually print out each match

description: Python loop with JSON, rather then manually print out each match