code:
table._cells[(i, j)]._text.set_fontsize(12)
table._cells[(i, j)]._text.set_color('red')

rawDescription: Matplotlib Table Row Label Font Color and Size


code:
import operator

class TwoPairs(set):
  def __hash__(self):
    return reduce(operator.xor, map(hash, self))

rawDescription: Efficient way to make two pairs in python


code:
def _get_editor(uiinfo, name):
    ui = uiinfo.ui
    if ui is None:
        return None
    for ed in ui._editors:
        if ed.name == name:
            return ed
    return None

class _OutputStreamViewHandler(Handler):

    def init(self, uiinfo):
        if ETSConfig.toolkit == 'qt4':
            ed = _get_editor(uiinfo, 'text')
            if ed is not None:
                # Make the text field read-only.
                ed.control.setReadOnly(True)
        return True

    def object_text_changed(self, uiinfo):
        ed = _get_editor(uiinfo, 'text')
        if ed is None:
            return

        if ETSConfig.toolkit == 'wx':
            # With wx, the control is a TextCtrl instance.
            ed.control.SetInsertionPointEnd()
        elif ETSConfig.toolkit == 'qt4':
            # With qt4, the control is a PyQt4.QtGui.QTextEdit instance.
            from PyQt4.QtGui import QTextCursor
            ed.control.moveCursor(QTextCursor.End)

rawDescription: Python TraitsUI - how to control scrollbar position of a 'String' trait editor/view


code:
def setup(app):
    app.add_index_to_domain('std', MyIndex)
    StandardDomain.initial_data['labels']['funcindex'] = ('std-funcindex', '', 'Function Index')
    StandardDomain.initial_data['anonlabels']['funcindex'] = ('std-funcindex', '')

rawDescription: How do I reference a custom index generated in my own sphinx extension?

description: Reference a custom index generated in my own sphinx extension


code:
import vobject

j = vobject.vCard()
o = j.add('fn')
o.value = "Meiner Einer"

o = j.add('n')
o.value = vobject.vcard.Name( family='Einer', given='Meiner' )

o = j.add('tel')
o.type_param = "cell"
o.value = '+321 987 654321'

o = j.add('tel')
o.type_param = "work"
o.value = '+01 88 77 66 55'

o = j.add('tel')
o.type_param = "home"
o.value = '+49 181 99 00 00 00'

print(j.serialize())

rawDescription: Creating a multiple phone vCard using vObject


code:
# 1st word, 4th letter    ("m")
#  + 2nd word, 1st letter ("e")
#  + 3rd word, 1st letter ("h")

print(x[0][3] + x[1][0] + x[2][0])

rawDescription: Python 2.5 list selection simple

description: Python 2.5 list selection simple


code:
from ast import literal_eval
from dateutil import parser

def guess_type(v):
    if v == '...':
        return 'Ellipsis'
    try:
        return type(literal_eval(v)).__name__
    except (SyntaxError, ValueError):
        try:
            return type(parser.parse(v)).__name__
        except ValueError:
            pass
        return 'string'

data = [
    'the book is on the table',
    '2014-03-14 22:10:00',
    'https://foo.com/bar.jpg',
    '23449',
    'True',
    'None',
    '{"foo": 1}',
    '{"foo"}',
    '...',
]

for i, item in enumerate(data):
    print('- Item{} -> {}'.format(i+1, guess_type(item)))

rawDescription: How to get content-type (or variable type) for a particular set of data in python?

description: Get content-type (or variable type) for a particular set of data in python


code: H = data.reshape(N,Nt,N).swapaxes(1,2)

rawDescription: Copy 2D array to a 3D one - Python / NumPy


rawDescription: Schedule `at` jobs with cygwin

description: Schedule `at` jobs with cygwin


code:
x = 'x'
y = 'y'
@hijack(lambda obj: 'hijacked!' if obj is x else obj)
def f():
    return (x, y)
f()

rawDescription: How to apply a decorator to subroutines in python

description: Apply a decorator to subroutines in python


code:
with open('eggs.json', 'w') as f:
    for thing in new_things:
        f.write(json.dumps(thing) + '\n')

rawDescription: Combining JSON values based on key

description: Combining JSON values based on key


code:
from unittest.mock import patch, MagicMock

mock = MagicMock()
mock.Pin().kernel_id = 'N21'
mock.Pin().set_value.return_value = True
mock.Pin().get_value.return_value = 3

modules = {
    'ablib': mock
}

patcher = patch.dict('sys.modules', modules)
patcher.start()

rawDescription: How to mock path like `module.Class`? using Python's Mock module?

description: Mock path like `module.Class`? using Python's Mock module


code:
import sys, re, os
from collections import deque
from bs4 import BeautifulSoup, Tag
from jsmin import jsmin
from csscompressor import compress

# html param
html = sys.argv[1]
# target param
target = sys.argv[2]
# path from html param
path = re.sub(r"[^\/]*$", "", html)
# open html file
soup = BeautifulSoup(open(html))
# find last script as anchorpoint
lastScript = soup.findAll("script", attrs = {"src" : True})[-1]
# get all scripts containing src attribute (= external scripts)
scripts = soup.findAll("script", attrs = {"src" : True})
# find last style link as anchorpoint
lastStylesheet = soup.findAll("link", attrs = {"rel" : "stylesheet"})[-1]
# get all links to css stylesheets
stylesheets = soup.findAll("link", attrs = {"rel" : "stylesheet"})

# create list of script srcs
print("\nRead Scripts:")
scriptsSrc = deque()
for script in scripts:
    scriptsSrc.append(path + script.attrs["src"])
    print("\t" + path + script.attrs["src"])

# create list of stylesheets srcs
print("\nRead Stylesheets:")
stylesheetsSrc = deque()
for stylesheet in stylesheets:
    stylesheetsSrc.append(path + stylesheet.attrs["href"])
    print("\t" + path + stylesheet.attrs["href"])

# merge scripts to temp.js
print("\nMerge Scripts:")
print("\t", end="")
with open("temp.js", "w") as outfileScript:
    for fname in scriptsSrc:
        # add space every script
        outfileScript.write("\n")
        print("~", end="")
        with open(fname) as infile:
            for line in infile:
                outfileScript.write(line)
print("\n");

# merge stylsheets to temp.css
print("Merge Stylesheets:")
print("\t", end="")
with open("temp.css", "w") as outfileCSS:
    for fname in stylesheetsSrc:
        # add space every script
        outfileCSS.write("\n")
        print("~", end="")
        with open(fname) as infile:
            for line in infile:
                outfileCSS.write(line)
print("\n");

# minify javascript
print("Minify temp.js\n\t~")
with open("temp.js") as js:
    minified_js = jsmin(js.read())

# minify css
print("\nMinify temp.css\n\t~")
with open("temp.css") as css:
    minified_css = compress(css.read())

# replace scripts with merged and min embed script / css
print("\nReplacing and deleting\n\t~")
tag = soup.new_tag("script")
tag["type"] = "text/javascript"
tag.append(minified_js)
lastScript.replace_with(tag)

tag = soup.new_tag("style")
tag["type"] = "text/css"
tag.append(minified_css)
lastStylesheet.replace_with(tag)

#remove script and style tags
for script in scripts:
    script.decompose()
for stylesheet in stylesheets:
    stylesheet.decompose()

#remove temp
os.remove("temp.js")
os.remove("temp.css")

#save html as target
file = open(target,"w")
file.write(soup.prettify())
file.close()

print("\nFIN\n")

rawDescription: Modify HTML file to embed all external Scripts and CSS into <script> and <style> tags


code:
class Config(object):

    the_one = None

    def __new__(cls, config):
        if cls.the_one is None:
            cls.the_one = Super(Config, cls).__new__(cls)
            # load and parse file, saving settings to `cls.the_one`
        return cls.the_one

rawDescription: Borg Design Pattern

description: Borg Design Pattern


code: driver = webdriver.PhantomJS(desired_capabilities={'phantomjs.page.settings.resourceTimeout': '5000'})

rawDescription: Setting timeout on selenium webdriver.PhantomJS


code:
def user_func(x, y, z):
    return anything_with(x, y, z)

rawDescription: Python: Passing function with arguments to a function


code:
hexstr = "12ab"
len(hexstr)
['"%s": %x' % (c, ord(c)) for c in hexstr]
i = 42
hex(i)
x = '{0:07b}'.format(i)
x
[hex(ord(c)) for c in x]
hex(ord('0')), hex(ord('1'))
import binascii
[hex(ord(c)) for c in binascii.unhexlify(hexstr)]

rawDescription: ascii txt file to binary bin file

description: Ascii txt file to binary bin file


code:
wnl = nltk.stem.WordNetLemmatizer()
...
for verb, adverb in pairs:
    verb = wnl.lemmatize(verb.lower(), "v")
    consolidated[verb].add(adverb)

rawDescription: How to extract the verbs and all corresponding adverbs from a text?

description: Extract the verbs and all corresponding adverbs from a text


code:
from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument('weeks', nargs='+', type=int, help='weeks numbers')
args = parser.parse_args()
print(args)

rawDescription: How to pass flexible amount of arguments using getopt in python?

description: Pass flexible amount of arguments using getopt in python


code:
if instance.is_logo:
    image_generator.setSizeParams(291, 167)
    result = image_generator.generate()
    new_image = os.path.join(settings.MEDIA_ROOT, instance.image.path.replace('.jpg','-logo.jpg'))
    dest = open(new_image, 'w')
    dest.write(result.read())
    dest.close()

rawDescription: Saving base64 string with Django

description: Saving base64 string with Django


code:
def transpose(m):
    return zip(*m)

a=[[1,2,3],[4,5,6],[7,8,9]]

print_row_maj( transpose(a) )

rawDescription: Invert the matrix values

description: Invert the matrix values


code:
from eventlet import wsgi
import eventlet

from pprint import pformat

def get_client_address(environ):
    try:
        return environ['HTTP_X_FORWARDED_FOR'].split(',')[-1].strip()
    except KeyError:
        return environ['REMOTE_ADDR']

def show_env(env, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return ['%s\r\n\r\nClient Address: %s\r\n' % (pformat(env), get_client_address(env))]

wsgi.server(eventlet.listen(('', 8090)), show_env)

rawDescription: Obtaining Client IP address from a WSGI app using Eventlet


code:
#! /usr/bin/python3.2

import re

class Sequence:
    def __init__ (self, raw): self.__raw = raw
    def __str__ (self): return 'Sequence {}'.format (self.__raw)
    def process (self): print ('Wolfing sequence {}'.format (self.__raw) )

class Option:
    def __init__ (self, raw): self.__raw = raw
    def __str__ (self): return 'Option {}'.format (self.__raw)
    def process (self): print ('Foxing option {}'.format (self.__raw) )

class Range:
    def __init__ (self, raw): self.__raw = raw
    def __str__ (self): return 'Range {}'.format (self.__raw)
    def process (self): print ('Bearing range {}'.format (self.__raw) )

class Slice:
    def __init__ (self, raw): self.__raw = raw
    def __str__ (self): return 'Slice {}'.format (self.__raw)
    def process (self): print ('Badgering slice {}'.format (self.__raw) )

class Stream:
    patterns = [ ('([0-9a-fA-F]+)', Sequence),
        ('(\\([0-9a-fA-F]+\\|[0-9a-fA-F]+\\))', Option),
        ('({[0-9a-fA-F]+})', Range),
        ('(\\[[0-9a-fA-F]+:[0-9a-fA-F]+\\])', Slice) ]

    def __init__ (self, stream):
        self.__tokens = []
        while stream:
            found = False
            for pattern, cls in self.patterns:
                m = re.match (pattern, stream)
                if m:
                    m = m.groups () [0]
                    self.__tokens.append (cls (m) )
                    stream = stream [len (m):]
                    found = True
                    break
            if not found: raise Exception ('Unrecognized sequence')

    @property
    def tokens (self): return (token for token in self.__tokens)

    def process (self):
        for token in self.__tokens: token.process ()

stream = Stream ('524946(46|58){4}434452[22:33]367672736E')
print ('These are the tokens:')
for idx, token in enumerate (stream.tokens):
    print ('{} at position {}.'.format (token, idx) )

print ('\nNow let\'s process them all:')
stream.process ()

rawDescription: Python: copying a repeating dictionary into a list - last dict item being duped to all list items


code:
stats = RawConfigParser.get('Section', 'option1').split(',')
iterations = int(stats[0]) # 6
duration = datetime.timedelta(seconds=float(stats[1])) # 0:00:09.520000

rawDescription: Correct way of getting time delta value from config file


rawDescription: numpy large array indexing crashes the interpreter

description: Numpy large array indexing crashes the interpreter


code:
def write_to_file(string, jlist):
    jdata = json.loads(string)
    jlist.append(jdata)
    with open("Data.json", "w") as outfile:
        json.dump(jlist,outfile, indent=4)
    return jlist

rawDescription: unexpected formatting when dumping to json

description: Unexpected formatting when dumping to json


code: yield line

rawDescription: Remove new line character from lines in Python


code:
Alist = create_matrix(file)
start_node(Alist)
check_neighbours(node, Alist)

rawDescription: python passing variables between functions

description: Python passing variables between functions


rawDescription: Kill all Pool workers in python multiprocess


code:
myrect = pygame.Rect(100, 0, 10, 10)
bounds = pygame.Rect(0, 0, 50, 50)
myrect.clamp_ip(bounds)

rawDescription: How to Make the Ball Bounce only if it Hits the Paddle in Python, Pygame (Breakout Recreation)


code: self.cb = ...

rawDescription: Python bind an event from a different file


code:
mult *= (1+data[i]/100)
test.append(mult)

rawDescription: Use Updated Value In Array

description: Use Updated Value In Array


rawDescription: Save a subdomain name to String

description: Save a subdomain name to String


code: join = lambda *args: os.path.join(*args).replace("\\", "/")

rawDescription: Why not os.path.join use os.path.sep or os.sep?


code:
def get_rec_vals(rec):
    ret_list = []
    for key,val in rec.items():
        if key == 'attributes': continue
        if isinstance(val, OrderedDict):
            # recursive call
            ret_list.extend(get_rec_vals(val))
        else:
            ret_list.append(val)
    return ret_list

output = [get_rec_vals(rec) for rec in od['records']]
print(output)

rawDescription: Nested OrderedDict to nested list with varying levels of nesting


code:
def funcprint(dir, *args):
    for f in args:
        with open('{}{}'.format(dir, f), 'r') as inp:
            ...

funcprint('C:/', 'file1.txt', 'file2.txt')

rawDescription: Python: unknown # of files as function arg


code:
index = random.randint(0, len(l)-1)
del l[index]

rawDescription: Calling "del" on result of Function call results in "SyntaxError: can't delete function call"


code:
import pandas as pd
pd.options.display.max_colwidth=100
df

rawDescription: How to Render Math Table Properly in IPython Notebook


code: subpeptides("ABCD")

rawDescription: How to generate subpeptides (special combinations) from a string representing a cyclic peptide?

description: Generate subpeptides (special combinations) from a string representing a cyclic peptide


code:
from tkinter import *
from tkinter.ttk import *

tk=Tk()
progress=Progressbar(tk,orient=HORIZONTAL,length=100,mode='determinate')

def bar():
    import time
    progress['value']=20
    tk.update_idletasks()
    time.sleep(1)
    progress['value']=50
    tk.update_idletasks()
    time.sleep(1)
    progress['value']=80
    tk.update_idletasks()
    time.sleep(1)
    progress['value']=100

progress.pack()
Button(tk,text='foo',command=bar).pack()
mainloop()

rawDescription: tk gui with progress bar

description: Tk gui with progress bar


code:
lock_acquired = False
while not lock_acquired:
    try:
        move(fh, fhtemp)
    except:
        sleep(3)
    else:
        lock_acquired = True
# do your writing
move(fhtemp, fh)
lock_acquired = False

rawDescription: Is this method of file locking acceptable?


rawDescription: Match all names with exactly 5 digits at the end


code:
links = ['http://stackoverflow.com/q/21515098/538284', # It's a html page
         'http://upload.wikimedia.org/wikipedia/meta/6/6d/Wikipedia_wordmark_1x.png', # It's a png file
         'http://commons.wikimedia.org/wiki/File:Typing_example.ogv', # It's a html page
         'http://upload.wikimedia.org/wikipedia/commons/e/e6/Typing_example.ogv'   # It's an ogv file
]

for link in links:
    print(guess_type_of(link))

rawDescription: How to check the url is either web page link or file link in python

description: Check the url is either web page link or file link in python


code:
class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "car":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
    return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

rawDescription: django admin - populate field with callable

description: Django admin - populate field with callable


code:
from __future__ import absolute_import

from celery import chain, chord, group
import celery
from cel_test.celery import app
from weather.parse_weather import parse_weather
from cel_test.common_tasks import qry
import cPickle as PKL
import csv
import requests

@app.task(ignore_results=False)
def write_the_csv(data, file_name, sql):
    with open(file_name, 'wb') as fp:
        a = csv.writer(fp, delimiter=',')
        for i in data:
            a.writerows(i)
    qry.delay(sql, True)
    return True

@app.task(ignore_result=False)
def idx_point_qry(DIR='/bar/foo/'):
    with open(''.join([DIR, 'thing.pkl']), 'rb') as f:
            a = PKL.load(f)
    return [(i, a[i]) for i in a]

@app.task(ignore_results=False)
def load_page(url):
    page = requests.get(url, **{'timeout': 30})
    if page.status_code == 200:
        return page.json()

@app.task(ignore_results=False)
def run_hourly(page, info):
    return parse_weather(page, info).hourly()

@app.task(ignore_results=False)
def pool_loop(info):
    data = []
    for iz in info:
        a = chain(load_page.s(url, iz), run_hourly.s())()
        data.append(a)
    return data

@app.task(ignore_results=False)
def run_update(file_name, sql, writing=True):
    chain(idx_point_qry.s(), pool_loop.s(file_name, sql), write_the_csv.s(writing, sql))()
    return True

rawDescription: Celery task PENDING

description: Celery task PENDING


code:
def move_ball_right_down():
    global x, y

    x, y = randrange(0, 400), randrange(0, 400)  # Randomize x and y (note that you should substitute your max and min canvas coordinate values if you want the ball to stay in view.

    can.coords(ball, x-r, y-r, x+r, y+r)

rawDescription: How can I randomly move a ball on a canvas in Python?

description: Randomly move a ball on a canvas in Python


code:
import os
print("hello world".center(os.get_terminal_size().columns))

rawDescription: Is it possible to align a print statement to the center in Python?


code:
sp_info = soup.select('.left-room-info')[i].text.strip()
if not sp_info:
    sp_info = "N/A"

rawDescription: Python - Crawl Multiple Classes within a Page Using BeautifulSoup


code:
for i in range(len(p)):
   if p[i] in p[i+1:]:
      return True
return False

rawDescription: Python Lists: How can I search for another element or duplicate item in a list


code:
dic={'25': {'Return of the Jedi (1983)': 5.0}, '42': {'Batman (1989)': 3.0, 'E.T. the Extra-Terrestrial (1982)': 5.0}, '8': {'Return of the Jedi (1983)': 5.0 }}
from collections import Counter
c=Counter(movie  for v in dic.values() for movie in v)
[k for k,v in c.items() if v>1] #returns the name of movies repeated more than once
c

rawDescription: Iterate and compare first item to all items in dictionary


code:
while len(outerlist) <= idx:
    outerlist.append([])

rawDescription: Building a list inside a list in python

description: Building a list inside a list in python


code:
...
# hide ticks of main axes
ax0 = plt.gca()
ax0.get_xaxis().set_ticks([])
ax0.get_yaxis().set_ticks([])

gs = gridspec.GridSpec(x, y, wspace=0, hspace=0)
plt.title('Example Plot')

for (j, k), img in np.ndenumerate(table):
    ax = fig.add_subplot(gs[x - j - 1, k])
    # hide ticks of gribspec axes
    ax.get_xaxis().set_ticks([])
    ax.get_yaxis().set_ticks([])

rawDescription: python matplotlib gridspec, unwanted arbitrary axis labels

description: Python matplotlib gridspec, unwanted arbitrary axis labels


rawDescription: Define the limits of my axes, but with an equal scale in both directions with matplotlib


code: cursor.execute("SELECT * from sometable LIMIT 0, 100")

rawDescription: offset/limit programmatically with python mysqldb

description: Offset/limit programmatically with python mysqldb


rawDescription: Pandas Time Index pick largest number/last number on given day


code: makeCustomDataframe(10, 10, c_idx_nlevels=2, r_idx_nlevels=2)

rawDescription: Creating random multi-index dataframes in Pandas


code:
class Level:
    def __init__(self, url_regex, title_regex, build_portion):
        self.url_regex = url_regex
        self.title_regex = title_regex
        self.build_portion = build_portion

    def method1(self):
        """use build_portion to do something"""
        self.build_portion.do_something()

    def method2(self):
        """use title_regex and url_regex to do something else"""
        x = self.title_regex + self.url_regex
        x.do_something_else()

rawDescription: Making a dynamic variable set

description: Making a dynamic variable set


rawDescription: Python - Split String Containing '\x'

description: Python - Split String Containing '\x'


rawDescription: Zipping lists within a list in Python

description: Zipping lists within a list in Python


code:
generator = ( item['value'] for item in test_data )

...

for i in generator:
    do_something(i)

rawDescription: How do I extract all the values of a specific key from a list of dictionaries?

description: Extract all the values of a specific key from a list of dictionaries


code:
def include_tagcloud(request):
    if request.path == '/tagcould/':
        tagcloud = Tags.objects.filter(active=True) #whatever
    return {'tagcloud': tagcloud}

def include_login(request):
    if request.user.is_authenticated():
        loginform = MyLoginForm(request.POST)
        #passing a Django form + POST data in the case of re-submit
    return {'loginform' : loginform}

rawDescription: How to realize a dynamic sidebar with Django?

description: Realize a dynamic sidebar with Django


rawDescription: Adding Vector Class Definition

description: Adding Vector Class Definition


code:
import json
from functools import wraps

def params_from_file(file):
    """Decorator to load params from json file."""
    def decorator(func_to_decorate):
        @wraps(func_to_decorate)
        def wrapper(self, *args, **kwargs):
            with open(file, 'r') as fh:
                kwargs = json.loads(fh.read())
                return func_to_decorate(self, **kwargs)
        return wrapper
    return decorator

rawDescription: How to dynamically create parameterized test from the file (json or yaml) in python

description: Dynamically create parameterized test from the file (json or yaml) in python


code:
RE_PROVIDER = re.compile(r'(?:sipout|\d+,)(?P<provider>(ilp|qtm|[A-Z\s]+))')
RE_PROVIDER.search(s1).groupdict()
RE_PROVIDER.search(s2).groupdict()
s3 = "182938,DOMINICAN REPUBLIC-MOBILE"
RE_PROVIDER.search(s3).groupdict()

rawDescription: How to print substring using RegEx in Python?

description: Print substring using RegEx in Python


code:
import numpy as np
A = np.array([[1, 2], [3, 4]])
b = np.array([1/2, 1/3])
print(A * b)

rawDescription: General Matrix computation in Python, TF-IDF


code:
random.choice(list)
random.choice(list)
random.choice(list)
random.choice(list)

rawDescription: How to print a random value name from a list?(python)

description: Print a random value name from a list?(python)


code:
import win32com.client

search_for = "This is some text in my file"
add_lines = "^pLine1^pLine2^pLine3"     # ^p creates a new line

word = win32com.client.Dispatch("Word.Application")
word.Visible = False
word.DisplayAlerts = False
doc = word.Documents.Open(r'c:\my_folder\my_file.docx')
const = win32com.client.constants

find = doc.Content.Find
find.ClearFormatting()
find.Replacement.ClearFormatting()
find.Execute(Forward=True, Replace=const.wdReplaceAll, FindText=search_for, ReplaceWith=search_for+add_lines)

word.ActiveDocument.SaveAs(r'c:\my_folder\my_file_output.docx')
word.Quit()

rawDescription: How can I open a docx file, find a particular string occurring at multiple places and add two lines after that in the whole document using python?

description: Open a docx file, find a particular string occurring at multiple places and add two lines after that in the whole document using python


code:
for fieldname, value in form.data.items():
    pass

rawDescription: Iterating over submitted form fields in Flask?


rawDescription: Assign scientific notation to variable in Python


code:
sum_score = 0

for one_score in all_scores:
    sum_score = sum_score + one_score

print( sum_score / len(all_scores) )

rawDescription: Looping test scores in file input/output


code:
locallist = ['Ann-Marie, the butcher (1)', 'Bella, the flourist (2)', 'Caitlyn, the painter(3)', 'Daniel, the scientist (4)', 'Lauren, the Zookeeper (5)']

pick = 'Ann-Marie, the butcher (1)'
locallist.remove('Ann-Marie, the butcher (1)')
print(locallist)

pick = 1
locallist.pop(1)
print(locallist)

['Bella, the flourist (2)', 'Caitlyn, the painter(3)', 'Daniel, the scientist (4)', 'Lauren, the Zookeeper (5)']
['Bella, the flourist (2)', 'Daniel, the scientist (4)', 'Lauren, the Zookeeper (5)']

rawDescription: Removing a item from a list and updating it python


code: self.data = self.data[1:]

rawDescription: Confusion over how to share and modify class level data between instances.


code:
for a in attributes:
    object.attr(a).set(1.5)

rawDescription: Set attribute without string concatination


code:
text_we_want = ['\t'.join((nodes_we_want[h].text.strip('\r\n'),
                 nodes_we_want[h+1].text.replace('\r\n              ','')))
                 for h in range(0,len(nodes_we_want)-1,2)]

rawDescription: How can I find my desired table inside a set of nested tables, using bs4/python, if there are no class or id attributes?

description: Find my desired table inside a set of nested tables, using bs4/python, if there are no class or id attributes


code:
class File(models.model):
    user = models.ForeignKey(User, related_name='files', null=False)
    filename = models.CharField(max_length=255, blank=False, null=False)

rawDescription: View function is not being called in Django


code:
C_b
simplify(C_b)

rawDescription: Sympy library solve to an unknown variable


rawDescription: Interleaving two numpy index arrays, one item from each array


code:
fileOutput = [(finalScore, "-", name, currentTime)]
with open("highscores.txt", "a") as f:
    for t in fileOutput:
        line = ' '.join(str(x) for x in t)
        f.write(line + "\n")

rawDescription: Write to file python - Linebreak issue (\n)


code:
with open("words.txt") as f:
    words = frozenset(f.read().lower().split("\n"))
    # frozenset for speed
def get_most_likely_encoding(s, delimiter=" "):
    alpha = "abcdefghijklmnopqrstuvwxyz" + delimiter
    for punctuation in "\n\t,:; .()":
        s.replace(punctuation, delimiter)
    s = "".join(c for c in s if c.lower() in alpha)
    word_count = [sum(w.lower() in words for w in encode(
            s, enc).split(delimiter)) for enc in range(26)]
    return word_count.index(max(word_count))

rawDescription: Determine ROT encoding

description: Determine ROT encoding


code:
t = int(raw_input())

string_list = [raw_input() for _ in range(t)]
common = set.intersection(*map(set,string_list))
print(len(common))

rawDescription: How to approach this loop?

description: Approach this loop


code:
import datetime

db.test.aggregate([
    { "$group": {
        "_id": {
            "$add": [
               { "$subtract": [
                   { "$subtract": [ "$date", datetime.datetime.utcfromtimestamp(0) ] },
                   { "$mod": [
                       { "$subtract": [ "$date", datetime.datetime.utcfromtimestamp(0) ] },
                       1000 * 60 * 60 * 24
                   ]}
               ]},
               datetime.datetime.utcfromtimestamp(0)
           ]
        },
        "count": { "$sum": 1 }
    }},
    { "$sort": { "_id": 1 } }
])

rawDescription: pymongo group by datetime

description: Pymongo group by datetime


code:
columns = ['LAND1','SEA1','OCEAN1','CITY1',...]
for col in columns:
    df[col] = (df[col].str.replace('\W+', '')
                      .str.lower().astype(str))

rawDescription: Is there any more pythonic way to do the following repetitive code


code:
for row in reader:
    row = [int(x) if re.match(r'-?\d+$', x) else x for x in row]
    writer.writerow(row)

rawDescription: Read a CSV file and put double quotes around data items


code:
pivoted.columns = "price" + pivoted.columns.astype(str)
pivoted

rawDescription: Pivot each group in Pandas

description: Pivot each group in Pandas


code:
df.set_index('filename', inplace=True)
df2.set_index('filename', inplace=True)
df.update(df2)
df

rawDescription: How to update values in a specific row in a Python Pandas DataFrame?

description: Update values in a specific row in a Python Pandas DataFrame


rawDescription: Nature of Python Values, need a clarification


code:
def vote_op(angle, belong, THRES_THETA, lines_lengths_vstacked, max_line_length):
    intermediate = (0.3 * (1-(angle[belong]/THRES_THETA)) + 0.7 * (lines_lengths_vstacked[belong]/max_line_length))
    b_rows = np.sum(belong, axis=1)
    b_ind = np.hstack([0, np.cumsum(b_rows)])[:-1]
    intermediate = np.hstack([intermediate, 0])
    votes = np.add.reduceat(intermediate, b_ind)
    votes[b_rows == 0] = 0
    return votes

rawDescription: numpy 2d boolean array indexing with reduce along one axis

description: Numpy 2d boolean array indexing with reduce along one axis


code:
httpbin.org
from json import load
from urllib2 import urlopen

my_ip = load(urlopen('http://httpbin.org/ip'))['origin']

rawDescription: How can I get the public IP using python2.7?

description: Get the public IP using python2.7


code:
othertab = self.parent.GetPage(1)
othertab.jaddbutton.Disable()

rawDescription: Problem with Classes in Python

description: Problem with Classes in Python


code: raise Exception('exit')

rawDescription: How to exit a script in Spyder?

description: Exit a script in Spyder


code:
import numpy
import gdal
from gdalconst import *

dataset = gdal.Open("/path/image.x", GA_ReadOnly )
image_array = ds.ReadAsArray()
image_array[pix_y,pix_x,band] = 10

rawDescription: Read ERDAS Imagine Images into Individual Variables as Matrices


code:
class Foo:
    ls = []

rawDescription: some confusion with variables declared by python class

description: Some confusion with variables declared by python class


rawDescription: How to convert a string to its Base-10 representation?

description: Convert a string to its Base-10 representation


code: [['Project1', ['Andrew']]]

rawDescription: best way to do list comprehension matching when there are multiple matches

description: Do list comprehension matching when there are multiple matches


code:
import numpy as np
lam = 227 - 62
phi = -2*np.pi * 62 / lam
A = 1.2499 / np.sin(2*np.pi*145/165. + phi)

rawDescription: Python matplotlib sine function with some fixed points


code:
def foo(): pass
foo = argument_decorator(True)(foo)

rawDescription: Python dynamic decorators - why so many wraps?


code:
from datetime import datetime,timedelta

today = datetime.today()
dt = "09/08/2015"

fut = datetime.strptime(dt, "%d/%m/%Y")
diff = 0
while today <= fut:
    mon = today.month
    today += timedelta(days=1)
    if today.month != mon:
        diff += 1
print(diff)
6

rawDescription: How to calculate months left to particular date?

description: Calculate months left to particular date


code: lambda: widgets.foobar.onSave()

rawDescription: Specifying TkInter Callbacks In Dictionary For Display Launcher Function


code: df.apply(lambda row: row.first_valid_index(), axis=1)

rawDescription: First column name with non null value by row pandas


code: [i*j for i in a for j in b]

rawDescription: Efficient way to multiply/add/devide each element of a list with each element of another list in Python


code:
idx = dist.idxmin(axis=1)
idx

rawDescription: indexing a pandas DataFrame

description: Indexing a pandas DataFrame


code:
def find(words, *sources):
    if isinstance(words, str):
        words = [words]  # make it a list
    # Treat words as a sequence in the rest of the function

rawDescription: Python: "Multiple" multiple arguments in function


code:
new_d = {}
for k,v in d.items():
    new_d[v] = new_d.get(v, tuple()) + (k,)

new_d

rawDescription: Fliping dictionary key value Python

description: Fliping dictionary key value Python


code:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    filter_horizontal = ['filter fields']  # example: ['tlf', 'country',...]
    verbose_name_plural = 'profiles'
    fk_name = 'user'

class UserAdmin(UserAdmin):
    inlines = (ProfileInline, )
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
    list_filter = ('is_staff', 'is_superuser', 'is_active')

admin.site.unregister(User)  # Unregister user to add new inline ProfileInline
admin.site.register(User, UserAdmin)  # Register User with this inline profile

rawDescription: Django: Add another field to django-registration


code:
price.to_json(date_format='iso', orient='records')
price.to_json('foo.json', date_format='iso', orient='records')  # save as json file

rawDescription: How do you convert time series data with pandas and show graph via highstock

description: Convert time series data with pandas and show graph via highstock


rawDescription: Remove focus from Entry widget

description: Remove focus from Entry widget


rawDescription: Python Pandas value-dependent column creation


code: from django.utils import simplejson

rawDescription: passing unicode strings from django to javascript

description: Passing unicode strings from django to javascript


code:
class ClassB:

    def __init__(self):

            # some state
            print("Creating state in B")
            self.X = 1.
            self.Y = 2.

def singleton(cls):
    obj = cls()
    # Always return the same object
    cls._instance = obj
    cls.__new__ = staticmethod(lambda cls: cls._instance)
    # Disable __init__
    cls.__init__ = (lambda self: None)
    return cls

@singleton
class SingletonB(ClassB):
    pass

rawDescription: singleton design pattern in Python with state

description: Singleton design pattern in Python with state


code:
#!/usr/bin/env python3

def create_pattern(pattern_size):
    # Create our list that'll be storing this info
    pattern = []

    # first_x and last_x are "memory" so we know where to place the Xes.
    first_x = 0
    last_x = pattern_size - 1

    # Next, create an inner list for each line
    for level in range(0, pattern_size):

        # start our new line
        pattern.append([])

        # Now place the Xes where they belong
        for x in range(0, pattern_size):
            if x == first_x or x == last_x:
                pattern[level].append("x")
            else:
                pattern[level].append(".")

        # Move the Xes to the new positions
        first_x += 1
        last_x -= 1
    return pattern

# see 'help(list.pop)' and 'help(list.insert)' for more details
def right_shift(line):
    buf = line.pop()
    line.insert(0, buf)
    return line

# This function just acts upon each line of a pattern
def shift_pattern(pattern):
    for line in range(0, len(pattern)):
        line = right_shift(pattern[line])
    return pattern

if __name__ == "__main__":
    original = create_pattern(7)
    for j in range(len(original)):
        if j != 0:
            original = shift_pattern(original)
        for i in range(len(original)):
            print("".join(original[i]))

        print()

rawDescription: detect position in pattern and shift

description: Detect position in pattern and shift


rawDescription: Euclidean distance in Python

description: Euclidean distance in Python


rawDescription: pandas: Rolling correlation with fixed patch for pattern-matching

description: Pandas: Rolling correlation with fixed patch for pattern-matching


code:
def wrapper(*args, **kwargs):
        ...
        if some_condition:
            request.new_content = new_content
        return operation(request, param, more_param)
return wrapper

rawDescription: What information do Python/Django decorators have access to?


code:
alist = ['A','B','C','D']
anotherList = ['A','C','B','D']
def smyFunction(aList,anotherList):
    return sorted(aList) == sorted(anotherList)
smyFunction(alist, anotherList)

rawDescription: Efficiently test if two lists have the same elements and length


code:
df1 = pd.crosstab(df['node'], df['precedingWord'])
df1
df2 = pd.crosstab(df['node'], df['comp'])

rawDescription: Turn dataframe into frequency list with two column variables in Python


rawDescription: unpacking a list in python

description: Unpacking a list in python


code:
def filter_cost(cost_lists, threshold):
    cost = [[i for i in ilist if i[0] <= threshold] for ilist in cost_lists]
    # the algorithm requires that we remove any lists that have become empty
    return [ilist for ilist in cost if ilist]

def _combi(cost_lists, k, start, depth, subtotal, threshold):
    if depth == k:
        for i in xrange(start, len(cost_lists)):
            for value in cost_lists[i]:
                if value[0] + subtotal > threshold:
                    break
                yield (value,)
    else:
        for i in xrange(start, len(cost_lists)):
            for value in cost_lists[i]:
                if value[0] + subtotal > threshold:
                    break
                for c in _combi(cost_lists, k, i+1, depth+1,
                                value[0]+subtotal, threshold):
                    yield (value,) + c

def combinations_product(cost_lists, k, threshold):
    for i in xrange(len(cost_lists)-k+1):
        for value in cost_lists[i]:
            if value[0] > threshold:
                break
            for comb in _combi(cost_lists, k, i+1, 2, value[0], threshold):
                temp = (value,) + comb
                cost, ilists, ith_items = zip(*temp)
                yield sum(cost), ilists, ith_items

def find_smallest_sum_permutations(lists):
    minima = [min(x) for x in lists]

    cost_local = []
    cost_global = []
    for i, ilist in enumerate(lists):
        if len(ilist) > 1:
            first = ilist[0]
            diff = [(num-first, i, j) for j, num in enumerate(ilist[1:], 1)]
            cost_local.append(diff)
            cost_global.extend(diff)
    cost_global.sort()

    threshold_index = len(lists) - 2
    cost_threshold = cost_global[threshold_index][0]
    cost_local = filter_cost(cost_local, cost_threshold)
    for k in xrange(2, len(lists)):
        group_combinations = tuple(combinations_product(cost_local, k,
                                                        cost_threshold))
        if group_combinations:
            cost_global.extend(group_combinations)
            cost_global.sort()
            cost_threshold = cost_global[threshold_index][0]
            cost_local = filter_cost(cost_local, cost_threshold)
        else:
            break

    permutations = [minima]
    for k in xrange(N-1):
        _, ilist, ith_item = cost_global[k]
        if type(ilist) == int:
            permutation = [minima[i]
                           if i != ilist else lists[ilist][ith_item]
                           for i in xrange(N)]
        else:
            # multiple nonminimal values combination
            mapping = dict(zip(ilist, ith_item))
            permutation = [minima[i]
                           if i not in mapping else lists[i][mapping[i]]
                           for i in xrange(N)]
        permutations.append(permutation)
    return permutations

rawDescription: Find the permutations that sums to the three smallest numbers


code:
#!/usr/bin/env python
from collections import defaultdict
from BeautifulSoup import BeautifulSoup

d = defaultdict(list) # data structure to hold the result
soup = BeautifulSoup(html)
i = 0
for el in soup.p.contents:
    if getattr(el, 'name', None) == 'b':
       i += 1  # switch to next <b> element
    else:
       d[i].append(el)

import pprint
pprint.pprint(dict(d))

rawDescription: Parsing HTML Tags and trailing information


code:
def _get_modules_from_db(d):
    if isinstance(d, Mapping) and d.keys() != {'path_to_file', 'sha512sum'}:
        for v in d.values():
            yield from _get_modules_from_db(v)
    else:
        yield d

rawDescription: Recursive function in Python: Best way to get a list of specific nested items


code:
def represent_none(self, data):
    return self.represent_scalar(u'tag:yaml.org,2002:null',
                                 u'null')

rawDescription: Can I dump blank instead of null in yaml/pyyaml?

description: Dump blank instead of null in yaml/pyyaml


code:
dynamic_section = ["IOADAPT","NETERROR","NET","NETPACKET","JFSFILE","JFSINODE"]

for section in dynamic_section:

    # counter
    count = 0

    for line in data:

        # Extract sections, and write to output
        myregex = r'^' + section + '\,(T\d+)\,(.+)\n'
        find_section = re.match( myregex, line)
        if find_section:

            # increment
            count += 1

    if count > 2:

        # Set output file (will be opened for writing after data transposition)
        currsection_output = DATA_DIR + HOSTNAME + '_' + day + '_' + month + '_' + year + '_' + hour + minute + second + '_' + section + '.nmon.csv'

        # Open StringIO for temp in memory
        buffer = cStringIO.StringIO()

        # counter
        count = 0

        for line in data:

            # Extract sections, and write to output
            myregex = r'^' + section + '[0-9]*' + '|ZZZZ.+'
            find_section = re.match( myregex, line)

            if find_section:

                # csv header

                # Replace some symbols
                line=re.sub("%",'_PCT',line)
                line=re.sub(" ",'_',line)
                line=re.sub("\+",'',line)
                line=re.sub("\(",'_',line)
                line=re.sub("\)",'_',line)
                line=re.sub(" ",'_',line)

                # Extract header excluding data that always has Txxxx for timestamp reference
                myregex = '(' + section + ')\,([^T].+)'
                fullheader_match = re.search( myregex, line)

                if fullheader_match:
                    fullheader = fullheader_match.group(2)

                    # Replace "." by "_" only for header
                    fullheader=re.sub("\.",'_',fullheader)

                    header_match = re.match( r'([a-zA-Z\-\/\_0-9]+,)([a-zA-Z\-\/\_0-9\,]*)', fullheader)

                    if header_match:
                        header = header_match.group(2)

                        # Write header
                        buffer.write('ZZZZ' + ',' + header + '\n'),

                # Extract timestamp

                # Nmon V9 and prior do not have date in ZZZZ
                # If unavailable, we'll use the global date (AAA,date)
                ZZZZ_DATE = '-1'
                ZZZZ_TIME = '-1'

                # For Nmon V10 and more

                timestamp_match = re.match( r'^ZZZZ\,(.+)\,(.+)\,(.+)\n', line)
                if timestamp_match:
                    ZZZZ_TIME = timestamp_match.group(2)
                    ZZZZ_DATE = timestamp_match.group(3)

                    # Convert month names to numbers
                    month_to_numbers = {'JAN': '01', 'FEB': '02', 'MAR': '03', 'APR': '04', 'MAY': '05', 'JUN': '06', 'JUL': '07', 'AUG': '08', 'SEP': '09', 'OCT': '10', 'NOV': '11', 'DEC': '12'}

                    for k, v in month_to_numbers.items():
                        ZZZZ_DATE = ZZZZ_DATE.replace(k, v)

                    ZZZZ_timestamp = ZZZZ_DATE + ' ' + ZZZZ_TIME

                # For Nmon V9 and less

                if ZZZZ_DATE == '-1':
                    ZZZZ_DATE = DATE
                    timestamp_match = re.match( r'^ZZZZ\,(.+)\,(.+)\n', line)
                    if timestamp_match:
                        ZZZZ_TIME = timestamp_match.group(2)

                        # Convert month names to numbers
                        month_to_numbers = {'JAN': '01', 'FEB': '02', 'MAR': '03', 'APR': '04', 'MAY': '05', 'JUN': '06', 'JUL': '07', 'AUG': '08', 'SEP': '09', 'OCT': '10', 'NOV': '11', 'DEC': '12'}

                        for k, v in month_to_numbers.items():
                            ZZZZ_DATE = ZZZZ_DATE.replace(k, v)

                        ZZZZ_timestamp = ZZZZ_DATE + ' ' + ZZZZ_TIME

                # Extract Data
                myregex = r'^' + section + '\,(T\d+)\,(.+)\n'
                perfdata_match = re.match( myregex, line)
                if perfdata_match:
                    perfdata = perfdata_match.group(2)

                    # Write perf data
                    buffer.write(ZZZZ_timestamp + ',' + perfdata + '\n'),

        # Open final for writing
        with open(currsection_output, "w") as currsection:

            # Rewind temp
            buffer.seek(0)

            writer = csv.writer(currsection)
            writer.writerow(['type', 'serialnum', 'hostname', 'ZZZZ', 'device', 'value'])

            # increment
            count += 1

            for d in csv.DictReader(buffer):
                ZZZZ = d.pop('ZZZZ')
                for device, value in sorted(d.items()):

                    # increment
                    count += 1

                    row = [section, SN, HOSTNAME, ZZZZ, device, value]
                    writer.writerow(row)

            # End for

        # Show number of lines extracted
        result = section + " section: Wrote" + " " + str(count) + " lines"
        print (result)
        ref.write(result + "\n")

        # Discard memory buffer
        buffer.close()

    # End for

rawDescription: Python - Enter the loop only if match data exists


code: Joe

rawDescription: Create Python class where the attributes is defined dynamically


rawDescription: Counting len() of BTree saved in ZODB takes much time


code:
re.split(r'\(|\)',s)
[[int(i) if i.isdigit() else i for i in j] if isinstance(j,list) else j for j in new]

rawDescription: How to convert a Python string to a dimensional array or list

description: Convert a Python string to a dimensional array or list


code: data = data.reshape((21, -1, 3)).swapaxes(1,2)

rawDescription: Python matplotlib animation randomly jumping to initial position


rawDescription: Input into tuple that goes into list

description: Input into tuple that goes into list


rawDescription: Understanding performance difference

description: Understanding performance difference


code:
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.template.context import RequestContext

#...
def index(request):
   # this will only render the template with the form
   searchData = searchForm() # an unbound form
   return render_to_response(
        'index.html',
        context_instance=RequestContext(
            request,{'form':searchData,}
        )
    )

def search(request):
   if request.method == 'POST': # If the form has been submitted...
     form = searchForm(request.POST)# A form bound to the POST data
     if form.is_valid():
        searchData = form.cleaned_data['searchField']
        # do whatever you want to process the search with
        # searchada, maybe populate some variable
        return render_to_response(
            'search.html',
            context_instance=RequestContext(
                request,{'form':searchData,} # maybe add here the populated variable with the search
            )
        )
   else:
     # request.GET, just show the unbound form
     searchData = searchForm() # an unbound form

   return render_to_response(
        'search.html',
        context_instance=RequestContext(
            request,{'form':searchData,}
        )
    )

rawDescription: HTTP Response problems with Django form

description: HTTP Response problems with Django form


code:
#!/usr/bin/env python
from itertools import chain

dict1 = {'key_1': 10, 'key_2': 14, 'key_m': 321}
dict2 = {'key_1': 15, 'key_2': 12, 'key_m':2, 'key_n':34}

dict3 = {}

# Go through all keys in both dictionaries
for key in set(chain(dict1, dict2)):

    # Find the key in either dictionary, using an empty
    # string as the default if it is not found.
    dict3[key] = [dict.get(key, "")
                  for dict in (dict1, dict2)]

print(dict3)

rawDescription: merging arrays in python

description: Merging arrays in python


rawDescription: Python Order list of strings by content

description: Python Order list of strings by content


rawDescription: Scipy: Do sparse matrices support advanced indexing?


code:
def create_inner_list(string):
    prev = 0
    mainlist = []
    sublist = []
    for each in string:
        if int(each) <= prev:
            prev = int(each)
            sublist.append(int(each))
        else:
            if sublist:
                mainlist.append(sublist)
            sublist = []
            mainlist.append(int(each))
            prev = int(each)
    if sublist:
        mainlist.append(sublist)
    return mainlist

rawDescription: python list within list - why is the sublist repeated

description: Python list within list - why is the sublist repeated


rawDescription: Fully vectorise numpy polyfit

description: Fully vectorise numpy polyfit


code:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(6,4))
df
# just assigns sequential letters to the column
df[4] = [chr(i+ord('A')) for i in range(6)]
df
# here we reindex the headers and return a copy
# using this form of indexing just requires you to provide
# a list with all the columns you desire and in the order desired
df2 = df[[4, 1, 2, 3]]
df2
df2.to_csv('a.txt', index=False, header=False)
with open('a.txt') as f:
    print(f.read())

rawDescription: Python: Printing dataframe to csv

description: Python: Printing dataframe to csv


rawDescription: assign the result of an list operation to var

description: Assign the result of an list operation to var


code: valuesA = {(A['a'][x], A['b'][x]): A['value'][x] for x in range(len(A['a']))}

rawDescription: Merge dictionaries with key combinations


code:
from PyQt4 import QtGui

if __name__ == '__main__':
    app = QtGui.QApplication([])
    label = QtGui.QLabel()
    label.setPixmap(app.style().standardPixmap(QtGui.QStyle.SP_MessageBoxWarning))
    label.show()
    app.exec_()

rawDescription: How do I add StandardPixmap to a layout?

description: Add StandardPixmap to a layout


code:
reg = re.compile(r'''
                ^            # Match the start of the string
                (?=.*[a-z])  # Check if there is a lowercase letter in the string
                (?=.*[A-Z])  # Check if there is a uppercase letter in the string
                (?=.*[0-9])  # Check if there is a digit in the string
                .*           # Match the string
                $            # Match the end of the string
                '''
                , re.X)      # eXtented option whitespace is not part of he pattern for better readability

rawDescription: Searching an input string for occurences of integers and characters using a single regular expression in Python


rawDescription: Using prepared data for Sci-kit classification


rawDescription: What is the difference between a function, an unbound method and a bound method?


rawDescription: Sampling a datetime from lines for days and columns for hours


code:
# handle_click will be called with button and can access button.url
button.url = url
button.connect('clicked', handle_click)

rawDescription: Storing custom information in a widget, gobject-introspect


code:
a
indices = np.argmax(a, axis=2)
m,n,r = a.shape
a

rawDescription: Index multiple dimensions of a multi-dimensional array with another - NumPy/ Python


code:
monty = {
    ('parrot','spam','cheese_shop'): 'sketch',
    ('Cleese', 'Gilliam', 'Palin') : 'actors',
}

rawDescription: Python many-to-one mapping (creating equivalence classes)


code:
import re
retval = subprocess.Popen(['rsync', '--list-only', source],
                           stdout=subprocess.PIPE,
                           env={'RSYNC_PASSWORD': password}).communicate()[0]
retval = re.sub('^.+?\d+:\d+:\d+\s+(\S+.+)', '\g<1>', retval)

rawDescription: Remove file permissions, creation date from rsync listing command in python?


code:
if __name__ == '__main__':
    from threading import Thread, Lock
    import record_usage

    lock = Lock()
    t = Thread(target=record_usage.record, args=[lock])
    t.daemon = True
    t.start()

    run(lock)

rawDescription: Run a script with web server and maintain data to be used later


code:
def sequify(func):
    def wrapped(f, seq):
        it = func(f, seq)
        try:
            len(seq)
        except:
            return it
        else:
            return type(seq)(it)
    return wrapped

rawDescription: `map`-like function preserving sequence-type


rawDescription: python breaking numbers in to 10s 5s 1s and .1s

description: Python breaking numbers in to 10s 5s 1s and .1s


code:
if not bias:
    can_correct = (n > 2) & (m2 > 0)
    if can_correct.any():
        m2 = np.extract(can_correct, m2)
        m3 = np.extract(can_correct, m3)
        nval = ma.sqrt((n-1.0)*n)/(n-2.0)*m3/m2**1.5
        np.place(vals, can_correct, nval)
return vals

rawDescription: How does pandas calculate skew

description: How does pandas calculate skew


code: len(set(b for a in ListA for b in ListB if a.lower() in b.lower()))

rawDescription: Given two lists of strings, find the total number of strings in the second list which contains any string in the first list as substring


code: sorted(a.items(), key=lambda pair: a_list.index(pair[0]))

rawDescription: How to sort a dictionary based on a list in python

description: Sort a dictionary based on a list in python


code:
dict = {
    "a" : "Apple",
    "b" : "Banana",
}

rawDescription: Curly braces in Python?

description: Curly braces in Python


rawDescription: Return index position in array based on a partial string in Python


code: tail -f /tmp/display_data

rawDescription: Creating a new terminal/shell window to simply display text


code:
a0 = np.array([[1,2],[3,4]]).astype(np.float32)
a = tf.Variable(a0)
b = tf.square(tf.matrix_determinant(a))
init_op = tf.initialize_all_variables()
sess = tf.InteractiveSession()
init_op.run()

minimization_steps = 50
learning_rate = 0.001
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
train_op = optimizer.minimize(b)

losses = []
for i in range(minimization_steps):
  train_op.run()
  losses.append(b.eval())

rawDescription: matrix determinant differentiation in tensorflow

description: Matrix determinant differentiation in tensorflow


code:
df.set_index('Name')

df.set_index('Name')
df.set_index('Name')

rawDescription: How could I count item based on each index by using pandas in python?


code:
import matplotlib.pyplot as plt

plt.plot(arr, y)

rawDescription: plotting the sum of an array array[0:i] vs i

description: Plotting the sum of an array array[0:i] vs i


code:
self.value = StringVar('', value="  Load GCODE file to find volume, \n weight and price of used filament.")
l = Label(self, textvariable=self.value)

rawDescription: How to display the variable in a tkinter window?

description: Display the variable in a tkinter window


rawDescription: How to "convert" a dequed object to string in Python?


code:
def pairwiseScore(seqA, seqB):
   # final score to keep track of the matches in DNA
   score = 0
   # String helper this will tell us if a match happened previously
   #  and it will be used to show the relationships between the seqA and seqB
   prevMatch = ""
   # https://docs.python.org/2/library/functions.html#zip
   # zip will transpose the two lists (char lists) into tuples based on their indices
   #  the we can use A,B to determine likeness of the two strings.
   for (A,B) in zip (seqA,seqB): # sync run through the lists (char lists)
      if  A == B :
         # if the string prevMatch has at least one character
         #  and the last one is a '|' +3 otherwise +1
         score += 3 if len(prevMatch) > 0 and prevMatch[-1] == '|' else 1
      else :
         #strings don't match -1
         score -= 1
      # add the bar for the equal chars in strings. to output and
      #  test for previous Match '| || |' etc...
      prevMatch += '|' if ( A == B ) else ' '

   # basically asking for that string seqA, matches, seqB, score : #
   #  return a string
   # GATAT    // seqA
   # | ||     // prevMatch
   # GCTAC    // seqB
   # Score: 3 // score
   return "{}\n{}\n{}\nScore: {}".format(seqA,prevMatch,seqB, score)

rawDescription: Pyschools Topic 3 Q 11 - DNA parity check


code: import HTMLParser

rawDescription: HTML parser in Python

description: HTML parser in Python


code:
mydict = {1:5,2:7,3:9,4:9,7:7,8:0,111:43,110:77}
partial_duplicate_destroyer(mydict, 2)
partial_duplicate_destroyer(mydict, 20)
partial_duplicate_destroyer(mydict, 200)
mydict

rawDescription: Compare a dict to itself and remove similar keys efficiently


code:
pivoting = pd.pivot_table(df,
                          index=['SOURCE OF BUSINESS'],
                          values=['INCOME'],
                          aggfunc=np.mean)

rawDescription: Summing column values in panda and attaching or merging total to dataframe?


code:
class Foo(object):
    def __init__(self, arg1, arg2):
        pass

rawDescription: Can a class in python behave like a specified class based on a passed parameter?


code:
job_flow_id = response['JobFlowId']
print("Job flow ID:", job_flow_id)

step_response = client.add_job_flow_steps(JobFlowId=job_flow_id, Steps=SomeMoreSteps)

step_ids = step_response['StepIds']

print("Step IDs:", step_ids)

rawDescription: How do you automate pyspark jobs on emr using boto3 (or otherwise)?

description: Automate pyspark jobs on emr using boto3 (or otherwise)


code:
prefs.add('python_path', '/path/to/site-packages')
prefs.add('python_path', '/path/to/your/project')

rawDescription: How to configure sublimerope to auto complete python code?

description: Configure sublimerope to auto complete python code


code: matrix_result = (matrix_a.tocsr() + matrix_b.tocsr()).tolil()

rawDescription: How to efficiently add sparse matrices in Python

description: Efficiently add sparse matrices in Python


code:
def convert_pair(p):
    p0, p1 = convert(p[0]), convert(p[1])
    return [str(p0), str(p1)]

rawDescription: Converting time from (mm:ss.ddd) to (ss.ddd)


code:
#! /usr/bin/python3

class Tree:
    def __init__ (self, weight, children):
        self.weight = weight
        self.children = children [:]

    def distances (self, curDistance = .0, acc = None):
        if acc is None: acc = []
        for child in self.children:
            child.distances (self.weight + curDistance, acc)
        return acc

    def collapse (self, limit):
        self.children = [child.collapse (limit) for child in self.children]
        distances = self.distances (-self.weight)
        avg = sum (distances) / len (distances)
        if avg > limit: return self
        return Node (self.weight, ''.join (self.descendants () ) )

    def descendants (self):
        descendants = []
        for child in self.children:
            descendants.extend (child.descendants () )
        return descendants

    def __repr__ (self):
        return '({}):{}'.format (','.join (str (child) for child in self.children), self.weight)

class Node:
    def __init__ (self, weight, name):
        self.weight = weight
        self.name = name

    def distances (self, curDistance, acc):
        acc.append (curDistance + self.weight)

    def collapse (self, limit):
        return self

    def descendants (self):
        return [self.name]

    def __repr__ (self):
        return '{}:{}'.format (self.name, self.weight)

class Stack (list):
    def pop (self):
        e = self [0]
        del self [0]
        return e

    def push (self, e):
        self.insert (0, e)

def parse (tree):
    buff = ''
    stack = Stack ()
    while True:
        c = tree [0]
        if c == ';': break
        tree = tree [1:]

        if c == '(':
            stack.push (c)
            continue

        if c in ':,':
            if buff: stack.push (buff)
            buff = ''
            continue

        if c == ')':
            if buff: stack.push (buff)
            buff = ''
            popped = ''
            children = []
            while True:
                weight = stack.pop ()
                if weight == '(': break
                weight = float (weight)
                child = stack.pop ()
                if isinstance (child, Tree):
                    child.weight = weight
                else:
                    child = Node (weight, child)
                children.append (child)
            stack.push (Tree (0, children) )
            continue

        buff += c

    return stack.pop ()

t = parse ('((A:0.9,(B:0.2,C:0.3):0.3,(E:0.05,F:0.08):0.1):0.6);')
print ('Input tree is {}'.format (t) )
for limit in range (1, 6):
    limit = limit / 10
    print ('Collapsed by {} is {}'.format (limit, t.collapse (limit) ) )

rawDescription: Collapse sub-trees in a tree with average distance to tips < x


code:
with StreamLogger(logging.INFO) as out:
    with StreamLogger(logging.ERROR) as err:
        subprocess.Popen("ls", stdout=out, stderr=err, shell=True)

rawDescription: Decorate \ delegate a File object to add functionality


code:
for k in defaults:
    params.setdefault(k, defaults[k])

rawDescription: Provide default values for python dictionary while keeping reference to original object


rawDescription: Matplotlib polar bar-plot legend

description: Matplotlib polar bar-plot legend


rawDescription: Numpy normalization code is strangely slow


code:
from pydub import AudioSegment
second_of_silence = AudioSegment.silent() # use default
second_of_silence = AudioSegment.silent(duration=1000) # or be explicit

rawDescription: Generating Silence with pyDub

description: Generating Silence with pyDub


code: dict_compare(dict_a, dict_b)

rawDescription: Python: Tool to compare pairs of dicts of varying deepness?


code:
@app.route("/folder/<folder_name>/")
def folder(folder_name):
    # do something with folder_name
    pass

rawDescription: Calling python functions in HTML file in Flask


code:
import pandas as pd
df = pd.DataFrame({'N': [1, 1, 2, 3],
                   'start': ['08/01/2014 9:30:02',
                             '08/01/2014 10:30:02',
                             '08/01/2014 12:30:02',
                             '08/01/2014 4:30:02']})
df['start'] = pd.to_datetime(df['start'])
df = df.reindex(np.repeat(df.index.values, df['N']), method='ffill')
df['start'] += pd.TimedeltaIndex(df.groupby(level=0).cumcount(), unit='h')

rawDescription: pandas: for each row in df copy row N times with slight changes

description: Pandas: for each row in df copy row N times with slight changes


code: is_64bits = sys.maxsize > 2**32

rawDescription: How to determine 'word' size in Python

description: Determine 'word' size in Python


code: weekly = db.BooleanProperty()

rawDescription: How to create a new property in google app engine

description: Create a new property in google app engine


code: comm = st.intersection(message.split())

rawDescription: Output the specific word (from a list) that was found in a string


code:
class Pork(object):
    def __init__(self, name, mult):
        self.name = name
        self.mult = mult

    @property
    def bar(self):
        return self.name * self.mult

    def __repr__(self):
        return self.name

class Foo(object):
    def __init__(self, spam='spam', ham='ham'):
        self.spam = Pork(spam, 2)
        self.ham = Pork(ham, 3)

rawDescription: Is there a way to pass arguments using the dot operator in python?


code:
from itertools import chain
try:
    # Python 2
    from itertools import izip_longest as zip_longest
except ImportError:
    # Python 3
    from itertools import zip_longest

def alt_iterative(s, t):
    return ''.join(chain.from_iterable(zip_longest(s, t, fillvalue='')))

rawDescription: Return Alternating Letters in Two Strings of Different Lengths


code: np.array(['Hello', 'World'], dtype='S')

rawDescription: ASCII string as dtype for numpy array of strings in Python 3


code: set(csv1) == set(csv2)

rawDescription: Python comparing two CSV files when order of rows doesn't matter


code:
def kwargs_for_func(func, kwargs, omit_none=False):
    arg_count = func.func_code.co_argcount
    func_kwargs = func.func_code.co_varnames[:arg_count]
    new_kwargs = {}
    for k in kwargs:
        if k not in func_kwargs:
            continue
        val = kwargs[k]
        if not (omit_none and val is None):
            new_kwargs[k] = val
    return new_kwargs

def apply_with_valid_kwargs(func, *args, **kwargs):
    return func(*args, **kwargs_for_func(func, kwargs))

def main(*args, **kwargs):
    apply_with_valid_kwargs(f1, *args, **kwargs)
    apply_with_valid_kwargs(f2, *args, **kwargs)

def f1(x, key1=None):
    pass # different def to emphasize changed output from f2

def f2(x, key1=42, key2=None):
    print(x, key1, key2)

main(1)            # f2 prints (1, 42, None)
main(1, key1=None) # f2 prints (1, None, None)

rawDescription: Pass keyword argument to another function where the keyword has a default value


code:
# You can use get instead of catching KeyError
s1 = set(lookup_tbl.value.get(from_id, set()))
s2 = set(lookup_tbl.value.get(to_id, set()))
common_items = s1.intersection(s2)

rawDescription: Using Large Lookup Table in Single MultiCore Machine with PySpark


rawDescription: Creating a dummy index list from a list of repeating inegers


code:
def decode_rfc2047_header(h):
    return ' '.join(s.decode(charset or 'ascii')
                   for s, charset in email.header.decode_header(h))

rawDescription: Get python getaddresses() to decode encoded-word encoding


code:
fig = figure()

ax1 = plt.subplot(111)
ax2 = ax1.twinx()

ln2, = ax2.plot([1, 2, 3], [0.3, 0.2, 0.1], 'r', label='ax2')
ln1, = ax1.plot([1, 2, 3], [1, 2, 3], 'b', label='ax1')

interesting_lines = [ln1, ln2]

fig.legend(*zip(*[(il, il.get_label()) for il in interesting_lines]), loc=2)

plt.show()

rawDescription: Legend transparency, when using secondary axis


code: EF = pd.ExcelFile('path/to/file.xlsx')

rawDescription: Loop through Dataframes in Dict of Dataframes


code:
df = pd.read_csv("bondstack.csv")
df["b"] = np.nan
df["b"][df["MA10"] > df["MA100"]] = df["open"].shift(-1)

rawDescription: Pandas list comprehension in a dataframe


code:
def solve_grid(self, grid, row=0, col=0):
    row, col = self.find_next(grid, row, col)
    result = (row == -1)
    num = 0
    while num < 9 and not result:
        num += 1
        if self.isValid(grid, row, col, num):
            grid[row][col] = num

            if self.solve_grid(grid, row, col):
                result=True
            else:
                grid[row][col] = 0

    return result

rawDescription: splitting multiple return statements into different functions

description: Splitting multiple return statements into different functions


code:
a = """
one
two

three
"""

rawDescription: Set the wrap width for python docs in a terminal


code:
def tokenize(self, text):
    for regexp in self.CONTRACTIONS2:
        text = regexp.sub(r'\1 \2', text)
    for regexp in self.CONTRACTIONS3:
        text = regexp.sub(r'\1 \2 \3', text)

    # Separate most punctuation
    text = re.sub(r"([^\w\.\'\-\/,&])", r' \1 ', text)

    # Separate commas if they're followed by space.
    # (E.g., don't separate 2,500)
    text = re.sub(r"(,\s)", r' \1', text)

    # Separate single quotes if they're followed by a space.
    text = re.sub(r"('\s)", r' \1', text)

    # Separate periods that come before newline or end of string.
    text = re.sub('\. *(\n|$)', ' . ', text)

    return text.split()

rawDescription: Consequences of abusing nltk's word_tokenize(sent)


code: B = B - np.dot(np.dot( inv(np.dot(Jft,Jf)),Jft),r)

rawDescription: Python - Gauss Newton Method Wiki example implementation


rawDescription: Relation between the length of the list and the math formula


code:
@jit(nopython=True)
def numba2(vec_obj, vec_ps, cos_maxsep):
    nps = vec_ps.shape[0]
    nobj = vec_obj.shape[0]
    dim = vec_obj.shape[1]
    found = np.zeros(nobj, np.bool_)
    for i in range(nobj):
        for j in range(nps):
            cos = 0.0
            for k in range(dim):
                cos += vec_obj[i,k] * vec_ps[j,k]
            if cos > cos_maxsep:
                found[i] = True
                break
    return found.nonzero()

rawDescription: Numpy optimization with Numba

description: Numpy optimization with Numba


code:
import scipy.optimize as opt

popt,pcov = opt.curve_fit(lambda t,x,y,z: h(x,y,z,t), t_meas, y_meas, p0=[x0,y0,z0])

rawDescription: Reducing difference between two graphs by optimizing more than one variable in MATLAB/Python?


code:
class Auction(models.Model):
    ...
    def _get_increment(self):
        """ add some logic to base incrementing amount on starting price """
        ...

    @property
    def current_auction_price(self):
        price = self.starting_amount
        bid_increment = self._get_increment()

        """ If there is more than 1 bid present, take the second highest value and add the bid increment. """
        if self.bid_set.count() > 1:
            price = self.bid_set.order_by('bid_amount')[-2].bid_amount + bid_increment

        return price

rawDescription: Creating an auction model a la eBay max bid style


code:
picture = CarPicture(title="Some Title", image=request.FILES['image'])
picture.save()

rawDescription: moving a function out of my method in django

description: Moving a function out of my method in django


code:
from django.utils.functional import SimpleLazyObject
from functools import partial

def get_wedd_or_none(id_):
    try:
        return Wedding.objects.get(id=id_)
    except Wedding.DoesNotExist:
        return None

def add_wedding_context(request):
    id_ = request.GET.get('wedding_id', None)
    if id_ is not None:
        lazy = SimpleLazyObject(partial(get_wedd_or_none, id_))
        return {'wedding': lazy}
    else:
        return {'wedding': None}

rawDescription: Context Processor for Django Site

description: Context Processor for Django Site


rawDescription: python combinators list with constraints without itertools

description: Python combinators list with constraints without itertools


code:
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from requests import session

payload = {
    r"Login1$UserName": "myusername",
    r"Login1$Password": "thepassword",
    r"Login1$RadioButtonList_Type": "Tuna",
    r"Login1$LoginButton": u"登入"
}
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36'}

with session() as s:
    s.headers = headers
    response = s.get('http://elogbook.ofdc.org.tw/')

    soup = BeautifulSoup(response.content)

    for input_name in ['__EVENTTARGET', '__EVENTARGUMENT', '__VIEWSTATE', '__VIEWSTATEGENERATOR', '__EVENTVALIDATION']:
        payload[input_name] = soup.find('input', {'name': input_name}).get('value', '')

    s.post("http://elogbook.ofdc.org.tw/", data=payload)

    req = s.get("http://elogbook.ofdc.org.tw/Member/CatchReportTuna.aspx")
    print(req.content)

rawDescription: Login to a website with a radio button using python's request module


code:
winner = [self.player,self.enemy][self.player.side == side]
winner.score += 1

rawDescription: What are some interesting alternatives to line-by-line if/else statements?


rawDescription: Dynamic number of loops

description: Dynamic number of loops


rawDescription: Specific Python pattern for the string that can help to slice


code:
print(vowelCount('its a death trap its a suicide rap'))
{'mostlyVowels': ['a', 'a', 'suicide'], 'halfVowels': [], 'mostlyConsonant': ['its', 'death', 'trap', 'its', 'rap']}

rawDescription: Counting vowels and appending to a dictionary


code:
class MyTests(unittest.TestCase):
    #  ....
    def shortDescription(self):
        doc = self._testMethodDoc
        return doc

rawDescription: Python unittest, how to display TestCase's methods' docstring in report?


code:
crlf: 1123
lfcr: 0
cr: 0
lf: 0

rawDescription: Get newline stats for a text file in Python


rawDescription: Python: Extracting Sentences From Line - Regex Needed Based on Criteria


code:
for value in ddict:
    print("Sub1:{0} Sub2:{1}\n".format(value["**subkey1**"], value["**subkey2**"]));

rawDescription: Change json.dumps dictionary values in python


code:
class Device(object):
    def connect(self, kind):
        if kind == 'cli':
            target = self._target = SSH()
        elif kind == 'netconf':
            target = self._target = Netconf()
        else:
            raise ValueError('Unknown device {!r}'.format(kind))
        return target.connect(kind)

    def __getattr__(self, name):
        return getattr(self._target, name)

class SSH(object):
    def connect(self, kind):
        print('SSH.connect called with kind {!r}'.format(kind))
    def execute(self, cmd):
        print('SSH.execute called with cmd {!r}'.format(cmd))

class Netconf(object):
    def connect(self, kind):
        print('Netconf.connect called with kind {!r}'.format(kind))
    def execute(self, cmd):
        print('Netconf.execute called with cmd {!r}'.format(cmd))

d = Device()
d.connect('cli')
d.execute('cmd1')
d.connect('netconf')
d.execute('cmd2')

rawDescription: Calling Class methods

description: Calling Class methods


code:
class Pokemon(object):
    def __init__(self,name,hp,damage):
        self.name = name     #pokemon name
        self.hp = hp         #hit-points of this particular pokemon
        self.damage = damage #amount of damage this pokemon does every attack

    def fight(self,other):
        if(self.hp > 0):
            print("%s did %d damage to %s"%(self.name,self.damage,other.name))
            print("%s has %d hp left"%(other.name,other.hp))

            other.hp -= self.damage
            return other.fight(self)  #Now the other pokemon fights back!
        else:
            print("%s wins! (%d hp left)"%(other.name,other.hp))
            return other,self  #return a tuple (winner,loser)

pikachu=Pokemon('pikachu', 100, 10)
pidgy=Pokemon('pidgy', 200, 12)
winner,loser = pidgy.fight(pikachu)

rawDescription: Python: Pokemon battle (classes, functions)


code:
def newlines():
    print()
    print()
    print()

question = "Which online Course you have signed up, dude?"
response = "Good Luck to you, dude!"

print(question), newlines(), input(), newlines(), print(response)

rawDescription: Why the return value of functions being printed in Python?


code:
import re
def tokenize(text):
    tokens = re.split(r'(month|year|day|hour|minute|second|[^\w\s]+)', text)
    return list(filter(None, tokens))

tokenize('month/year/day T hour:minute')
tokenize('month.year somestring')
tokenize('year-month-day hour:minute.second')

rawDescription: parsing dates and times

description: Parsing dates and times


code:
class Wrapper(object):
    """Wrapper class that provides proxy access to an instance of some
       internal instance."""

    __wraps__  = None
    __ignore__ = "class mro new init setattr getattr getattribute"

    def __init__(self, obj):
        if self.__wraps__ is None:
            raise TypeError("base class Wrapper may not be instantiated")
        elif isinstance(obj, self.__wraps__):
            self._obj = obj
        else:
            raise ValueError("wrapped object must be of %s" % self.__wraps__)

    # provide proxy access to regular attributes of wrapped object
    def __getattr__(self, name):
        return getattr(self._obj, name)

    # create proxies for wrapped object's double-underscore attributes
    class __metaclass__(type):
        def __init__(cls, name, bases, dct):

            def make_proxy(name):
                def proxy(self, *args):
                    return getattr(self._obj, name)
                return proxy

            type.__init__(cls, name, bases, dct)
            if cls.__wraps__:
                ignore = set("__%s__" % n for n in cls.__ignore__.split())
                for name in dir(cls.__wraps__):
                    if name.startswith("__"):
                        if name not in ignore and name not in dct:
                            setattr(cls, name, property(make_proxy(name)))

rawDescription: How can I intercept calls to python's "magic" methods in new style classes?

description: Intercept calls to python's "magic" methods in new style classes


rawDescription: Python + pygtk generate table of checkboxes from database


code:
class MyTest2(object):
  def bar(self, x):
    return x*x + self.x
  x = 1

import dill
with open('test2.pkl', 'wb') as s:
  dill.dump(MyTest2, s)

rawDescription: Pickle python class instance plus definition


code:
def compress(x):
    if len(x) > 1:
        return x
    elif not x:
        return ''
    else:
        return x[0]

def parse(s):
    return compress([
        compress([
            compress(b.split(',')) for b in a.split(';')
        ]) for a in s.split('|')
    ])

rawDescription: Cleaner method for list comprehension clean-up


code:
year = member("1", "2") + digit*3
month = either("Jan", "Feb", "Mar")
day = digit*2
hour_mins = digit*2 + ":" + digit*2

date = month + " " + day + ", " + year + ", " + hour_mins

rawDescription: Composable Regexp in Python

description: Composable Regexp in Python


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--a-long', help='a help')
parser.add_argument('-b', '--b-long', help='b help')
args = parser.parse_args()

rawDescription: What is the canonical way of handling sys arguments in Python?


code:
#===inside driver.py===
import connections

params = parseFile(sys.argv) #get parameters from the csv file that is passed to the command line
connections.connect(params)  #pass them to whatever method you need to call from connections

rawDescription: Pass command line variables between Python files. Totally stuck


code:
@receiver(post_delete, sender=PostImage)
def post_delete_user(sender, instance, *args, **kwargs):
    instance.image.delete(save=False)
    instance.image_thumb.delete(save=False)
    instance.image_web.delete(save=False)
    instance.image_infowindow.delete(save=False)

rawDescription: Deleting files associated with model - django


code:
def build_dict(seq, key):
    return dict((d[key], dict(d, index=index)) for (index, d) in enumerate(seq))

info_by_name = build_dict(lst, key="name")
tom_info = info_by_name["Tom"]
# {'index': 1, 'id': '2345', 'name': 'Tom'}

rawDescription: Find the index of a dict within a list, by matching the dict's value


code:
import operator as op

class FuzzyDict(object):
    def __init__(self, iterable=(), float_eq=op.eq):
        self._float_eq = float_eq
        self._dict = dict(iterable)

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

    def __setitem__(self, key, val):
        self._dict[key] = val

    def __iter__(self):
        return iter(self._dict)

    def __len__(self):
        return len(self._dict)

    def __contains__(self, key):
        return key in self._dict

    def __eq__(self, other):
        def compare(a, b):
            if isinstance(a, float) and isinstance(b, float):
                return self._float_eq(a, b)
            else:
                return a == b
        try:
            if len(self) != len(other):
                return False
            for key in self:
                if not compare(self[key], other[key]):
                    return False
            return True
        except Exception:
            return False

    def __getattr__(self, attr):
        # free features borrowed from dict
        attr_val = getattr(self._dict, attr)
        if callable(attr_val):
            def wrapper(*args, **kwargs):
                result = attr_val(*args, **kwargs)
                if isinstance(result, dict):
                    return FuzzyDict(result, self._float_eq)
                return result
            return wrapper
        return attr_val

rawDescription: Comparing Python dicts with floating point values included


code:
class Event(models.Model):
    title = models.CharField(max_length=200)

class Person(models.Model):
    name = models.CharField(max_length=30)

class Article(models.Model):
    title = models.CharField(max_length=200)
    publishDate = models.DateTimeField(blank=True, null=True)
    event = models.ForeignKey(Event, related_name='articles')
    persons = models.ManyToManyField(Person, related_name='articles')

rawDescription: How to make a filtering annotation with ManyToMany relation in Django?

description: Make a filtering annotation with ManyToMany relation in Django


code:
import re
p = re.compile(r'(?=((\w+)\s*->\s*(\w+)))')
test_str = "a->b->c"

re.findall(p, test_str)

rawDescription: Regex help for matching multiple consecutive groups


code:
a = None
def foo():
    a = 5  # local 'a' shadows global 'a'

rawDescription: What does list[:] = process_list(list) does in python?


code:
def f(a=[]):
    pass
f.func_defaults
f.func_code.co_varnames

rawDescription: Where is the default parameter in Python function


rawDescription: How to allow whitespaces in tag names using django-tagging-0.3.1?

description: Allow whitespaces in tag names using django-tagging-0.3.1


code:
import os
for root, dirs, files in os.walk("/mydir"):
    for file in files:
        if file.endswith(".txt"):
             print(os.path.join(root, file))

rawDescription: Find all files in directory with extension .txt in Python


code:
def sendnext(packets):
    for i in range(len(packets)):
        if not packets[i][2]:
            sendsegment(packets[i][0], packets[i][1])
            packets[i] = (packets[i][0], packets[i][1], True)
            break

rawDescription: Changing a single element of a list while iterating in python


code: [x for x in lst if re.search(".*".join(map(re.escape, strings_to_match)), x)]

rawDescription: Find sublist of strings that match a regex that requires ordered inclusion from another list


code:
import io
import re
from IPython.nbformat import current

def parse_into_cells(py_file):
    with io.open(py_file, 'r', encoding='utf-8') as f:
        data = f.readlines()
    in_cell = True
    cell = ''
    for line in data:
        if line.rstrip() == '':
            # If a blank line occurs I'm out of the current cell
            in_cell = False
        elif re.match('^\s+', line):
            # Indentation, so nope, I'm not out of the current cell
            in_cell = True
            cell += line
        else:
            # Code at the beginning of the line, so if I'm in a cell just
            # append it, otherwise yield out the cell and start a new one
            if in_cell:
                cell += line
            else:
                yield cell.strip()
                cell = line
                in_cell = True
    if cell != '':
        yield cell.strip()

def convert(py_file, ipynb_file):
    # Create an empty notebook
    notebook = current.reads('', format='py')
    # Add all the parsed cells
    notebook['worksheets'][0]['cells'] = list(map(current.new_code_cell,
                                                  parse_into_cells(py_file)))
    # Save the notebook
    with io.open(ipynb_file, 'w', encoding='utf-8') as f:
        current.write(notebook, f, format='ipynb')

convert('convert.py', 'convert.ipynb')

rawDescription: Is there a IPython notebook api?

description: Is there a IPython notebook api


code:
common_bits = [(address & myaddress).bits() for address in addresses]
common_bits
common_bit_counts = [bits.count('1') for bits in common_bits]
common_bit_counts

rawDescription: python netaddr find closest Ip address match

description: Python netaddr find closest Ip address match


rawDescription: Expand a Tuple Into Semi-Repeating Pairs


code:
from Tkinter import *

class App(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.pack()

        frame = Frame()
        frame.pack()

        self.instruction = Label(frame, text="Password:")
        self.instruction.pack()

        self.button = Button(frame, text="Enter", command=self.reveal)
        self.button.pack()

    def reveal(self):
        # Do something.
        pass

root = Tk()
root.title("Password")
root.geometry("350x250")
App(root)
root.mainloop()

rawDescription: Tkinter widgets not appearing

description: Tkinter widgets not appearing


rawDescription: How to convert a sympy polynomial into a list?

description: Convert a sympy polynomial into a list


code: content

rawDescription: Python 2.7.1, codecs, and MySQLdb; why is setting file encoding not needed


code:
import re
s = "1) there is a problem 2) There appears to be a bug 3) stuck on start screen.";
print ([x for x in re.split(r"\d+\)\s*", s) if x]);
# => ['there is a problem ', 'There appears to be a bug ', 'stuck on start screen.']

rawDescription: regex - retrieve text between delimiters

description: Regex - retrieve text between delimiters


rawDescription: Sum of 2^x using elements of a list as exponents


code:
import networkx as nx
G = nx.DiGraph()
G.add_path([1,2,3,4])
G.add_path([10,11,12])

rawDescription: Largest weakly connected component in networkX


code:
def is_netfile(fname, netfs):
    fname = path.realpath(fname)
    netfs = path.realpath(netfs)
    if path.commonprefix([ netfs, fname ]) == netfs:
        return True
    else:
        return False

rawDescription: Detect whether file is on a network drive in python


code: context['my_json_data'] = json.dumps(my_python_data, cls=CustomJSONEncoder)

rawDescription: python structure JSON serializing issue

description: Python structure JSON serializing issue


code:
for result in result:
    french, english, prob = result
    # do something with this particular french, english, prob

rawDescription: Python: separate results of re.findall

description: Python: separate results of re.findall


rawDescription: Using variable as keyword passed to **kwargs in Python


code:
import json, re
line = re.compile('("[^"]*")\s*=\s*("[^"]*");')
result = '''\
{
    "original-purchase-date-pst" = "2012-06-28 02:46:02 America/Los_Angeles";
    "original-transaction-id" = "1000000051960431";
    "bvrs" = "1.0";
    "transaction-id" = "1000000051960431";
    "quantity" = "1";
    "original-purchase-date-ms" = "1340876762450";
    "product-id" = "com.x";
    "item-id" = "523404215";
    "bid" = "com.x";
    "purchase-date-ms" = "1340876762450";
    "purchase-date" = "2012-06-28 09:46:02 Etc/GMT";
    "purchase-date-pst" = "2012-06-28 02:46:02 America/Los_Angeles";
    "original-purchase-date" = "2012-06-28 09:46:02 Etc/GMT";
}
'''
line = re.compile(r'("[^"]*")\s*=\s*("[^"]*");')
trailingcomma = re.compile(r',(\s*})')
corrected = trailingcomma.sub(r'\1', line.sub(r'\1: \2,', result))
json.loads(corrected)

rawDescription: How to parse Apple's IAP receipt mal-formatted JSON?

description: Parse Apple's IAP receipt mal-formatted JSON


code:
from itertools import groupby
from operator import itemgetter

def inner_join(a, b):
    L = a + b
    L.sort(key=itemgetter(0)) # sort by the first column
    for _, group in groupby(L, itemgetter(0)):
        row_a, row_b = next(group), next(group, None)
        if row_b is not None: # join
            yield row_a + row_b[1:] # cut 1st column from 2nd row

rawDescription: How do I merge two lists of tuples based on a key?

description: Merge two lists of tuples based on a key


rawDescription: Python 3.x - Seperating Long Binary String to Short


code: print("Hello","SO!")

rawDescription: Using print() in Python2.x

description: Using print() in Python2.x


code:
def add_tracked(event):
    if tracking:
        # Get coordinated of the event and use the master window method to determine
        # wich widget lays inside these.
        widget = tk.winfo_containing(event.x_root, event.y_root)
        # Since 'Motion' creates many events repeatedly, you have to convert this
        # list into a set to remove duplicates.
        widgets.append(widget)

rawDescription: Avoid event grab during motion in Tkinter


code: y=Normal(mu, sigma, observed=somedata)

rawDescription: pymc3 generate stochastic variables with array of parameters

description: Pymc3 generate stochastic variables with array of parameters


code:
from collections import defaultdict

class Char:
    def __init__(self, c):
        self._c = c

    def match(self, obj): return obj.match_c(self._c)

    def match_c(self, cc):
        return self._c == cc

    def match_w(self): return True

class WildCard:
    def __init__(self):
        pass

    def match(self, obj): return obj.match_w()

    def match_c(self, cc): return True

    def match_w(self): return True

class TransUnit(object):
    def __init__(self, key, s):
        self._val = s
        self._arr = [WildCard() if c == '-' else Char(c) for c in s]
        self._key = key
        self._matches = 0
        self._has_wildcard = any(map(lambda x: isinstance(x, WildCard), self._arr))

    @property
    def has_wildcard(self): return self._has_wildcard

    @property
    def val(self): return self._val

    def found_match(self): self._matches += 1

    def match(self, obj):
        if isinstance(obj, str):
            return TransUnit(None, obj).match_arr(self._arr)
        return obj.match_arr(self._arr)

    def match_arr(self, arr):
        if len(self._arr) != len(arr): return False
        for i in range(len(arr)):
            if not self._arr[i].match(arr[i]):
                return False
        return True

    def compare(self, obj):
        return -obj.compare_arr(self._arr)

    def compare_arr(self, arr):
        if not self.match_arr(arr): raise Exception()
        for i in range(len(arr)):
            if not isinstance(self._arr[i], WildCard) and isinstance(arr[i], WildCard):
                return -1
            elif not isinstance(arr[i], WildCard) and isinstance(self._arr[i], WildCard):
                return 1
        return 0

    def __str__(self):
        if self._has_wildcard:
            if self._matches <= 1:
                return '(' + self._key + ')'
            else:
                return '[' + self._key + ']'
        else:
            return self._key

    __repr__ = __str__

def group(dct):
    trans = [TransUnit(k, dct[k]) for k in dct]
    wilds = [t for t in trans if t.has_wildcard]
    nonwilds = [t for t in trans if not t.has_wildcard]
    grouper = defaultdict(list)
    for n in nonwilds:
        grouper[n.val].append(n)

    notmatched = []
    for w in wilds:
        matched = False
        for k, lst in grouper.items():
            if w.match(k):
                w.found_match()
                lst.append(w)
                matched = True
        if not matched:
            notmatched.append(w)

    return (grouper, notmatched)

rawDescription: How to merge dictionaries and group by value in python?

description: Merge dictionaries and group by value in python


code: abbrevDict = dict((country, abbrev) for abbrev, country in firstArray)

rawDescription: Comparing Two Arrays resulting into Third Array


code:
class Foo(object):
    def __init__(self, a, b):
        self.superVar = {'subVar1' : a, 'subVar2' : b}

bar = Foo('one', 'two')
bar.superVar.values()
# ['one', 'two']

rawDescription: Is it possible to assign variables within the assignment of another variable?


rawDescription: Regex to match space and a string until a forward slash


code:
from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

with open(filename, 'r') as inputfile:
    key_def_pairs = list(pairwise(inputfile))

rawDescription: Linking two items from two seperate lists together. python


code:
import threading
x = 0
def foo():
    global x
    for i in xrange(1000000):
        x += 1
threads = [threading.Thread(target=foo), threading.Thread(target=foo)]
for t in threads:
    t.daemon = True
    t.start()
for t in threads:
    t.join()
print(x)

rawDescription: why using multiple threading to get the sum is correct?

description: Why using multiple threading to get the sum is correct


code: filter(lambda s: s not in string.punctuation, "O João foi almoçar :) .".split())

rawDescription: Split a string into a list, leaving accented chars and emoticons but removing punctuation


code: c.executemany('INSERT INTO q1_person_name(first_name, last_name) VALUES (?,?)', data_person_name)

rawDescription: Python-sqlite3 - Auto-increment of not null primary key?


code:
fig = plt.figure(figsize=(17.5,8.0))
left = 0.1
bottom = 0.03
width = 0.3
height = 0.6

# let us create third axes with the figure coordinates:
ax3 = plt.axes([0, 0, 1, 1], frameon=False, zorder=10)

ax1 = plt.axes([left, bottom, width, height])
ax3.add_artist(plt.Rectangle((left, bottom), width, height, facecolor=(1,0,0,.5), edgecolor='none'))

left += (width+0.12)
ax2 = plt.axes([left, bottom, width, height])
ax3.add_artist(plt.Rectangle((left, bottom), width, height, facecolor=(1,0,0,.5), edgecolor='none'))

rawDescription: matplolib: what are the units in the axes positioning [l,b,w,h] (imshow involved)?

description: Matplolib: what are the units in the axes positioning [l,b,w,h] (imshow involved)


code:
lst = [str(dj) for dj in DJ.objects.all()]
with open('data.txt', 'w+') as outfile:
    json.dump(lst, outfile)

rawDescription: creating a json array in python

description: Creating a json array in python


code:
a = ['dog','cat','mouse']
from itertools import combinations
['-'.join(el) for el in combinations(a, 2)]

rawDescription: Pythonic way to build a Combination String


code:
z=zip(sub,l,regons)
out={i :{'repeat':i.count(j),'region':reg} for i,j,reg in z}
out

rawDescription: A more complex version of "How can I tell if a string repeats itself in Python?"


code: all(search not in s for s in myList)

rawDescription: Check if none of list elements contain searched substring


code:
def __init__(self):
    HTMLParser.__init__(self)
    self.__text = []
    self.hosts = set()

rawDescription: Python: Returning only hosts/a href with my HTML parser


code:
a = [8, 8, 1, 1, 5, 8, 9]
d = {}
for i in a:
    d[i] = d.get(i, 0) + 1
popularity = sorted(d, key=d.get, reverse=True)

rawDescription: Take a list, sort by popularity and then remove duplicates


code: f = interp1d(x, y, axis=2)

rawDescription: Interpolating an array within an astropy table column


code:
def phone_split(x, format=[4,3,2,2]):
  parts = []
  reduce(lambda x, y: parts.append(x[:y]) or x[y:], format, x)
  return ' '.join(parts)

rawDescription: how to make phone number mask on Django?

description: Make phone number mask on Django


code:
from somewhere import MyUsefulFunction

# in templatetags:
@register.filter(name='CallingTemplateTagFunction')
def CallingTemplateTagFunction(price):
    return MyUsefulFunction(price)

# in views:
def Test(request):
   MyUsefulFunction(50)

rawDescription: Calling django template tags from a normal function


code:
#  mPlotDATEs.date2num.__doc__
#
#     *d* is either a class `datetime` instance or a sequence of datetimes.
#
#     Return value is a floating point number (or sequence of floats)
#     which gives the number of days (fraction part represents hours,
#     minutes, seconds) since 0001-01-01 00:00:00 UTC, *plus* *one*.
#     The addition of one here is a historical artifact.  Also, note
#     that the Gregorian calendar is assumed; this is not universal
#     practice.  For details, see the module docstring.

rawDescription: matplotlib: marker size / color as extra dimension

description: Matplotlib: marker size / color as extra dimension


code: np.c_[a, b, c]

rawDescription: combining vectors as column matrix in numpy

description: Combining vectors as column matrix in numpy


code:
def deleteContent(fd):
    os.ftruncate(fd, 0)
    os.lseek(fd, 0, os.SEEK_SET)

rawDescription: How to delete only the content of file in python

description: Delete only the content of file in python


code:
b="".join(a)  # doesn't do anything useful since `a` is already a string
lst=list(b)   # this is converting the string to a list of characters

rawDescription: Inquiry about removing duplicates

description: Inquiry about removing duplicates


code:
def __setattr__(self, name, value):
    super(MyStore, self).__setattr__(name, value)
    self._data[name] = value

rawDescription: Python class as datastore

description: Python class as datastore


code: mask = (df['ratio'] >= 1+tol) | (df['ratio'] <= 1-tol)

rawDescription: Portfolio rebalancing with bandwidth method in python


code:
#dummying up a dataframe
cf['A'] = 5*[5]
cf['C'] = range(5)
cf['B'] = list('qwert')
#putting together two columns into a new one -- EDITED so string formatting is OK
cf['D'] = map(lambda x: str(x).zfill(5), 1000*cf.A + cf.C)
# use it as the index
cf.index = cf.D
# we don't need it as a column
cf.drop('D', axis=1, inplace=True)
print(cf.to_csv())

rawDescription: Creating new complex index with pandas Dataframe columns


code:
funcs = [lambda a, b, i=i:func(a, b, c=i) for i in xrange(5)]
funcs[0](1, 2)
funcs[1](1, 2)

rawDescription: Define a list of functions from a generic function


code: module = __import__("actions.foo")

rawDescription: Python importing a function with file's name contained in a variable


code:
from random import randint

def roll_dice(count, sides=6):
    if count == 0: return (0, 0) # we need to guard against infinite recursion.
    initial = [randint(1, sides) for die in range(count)]
    initial_mins = initial.count(1)
    initial_maxes = initial.count(sides)
    # Add up all the dice that weren't maximum.
    subtotal = sum(result for result in initial if result != sides)
    # Recurse to re-roll the maxed-out dice.
    ignored, reroll = roll_dice(2 * initial_maxes, sides)
    return (initial_mins, subtotal + reroll)

rawDescription: How can I keep track of specific values rolled in a dice-rolling script?

description: Keep track of specific values rolled in a dice-rolling script


code:
def convertVector(numbers):
    totes = []
    for i, number in enumerate(numbers):
        if number != 0:
            totes.append((i, number))
    return dict((totes))

rawDescription: Python: is index() buggy at all?

description: Python: is index() buggy at all