code:
def print_hierarchy(root, indent=None, dec=None, zeroes=False):
    if indent is None:
        indent = []
    elif isinstance(indent, str):
        indent = [indent]
    if dec is None:
        dec = []
        zeroes = False
    elif isinstance(dec, int):
        dec = [str(dec)]
    elif isinstance(dec, str):
        dec = [dec]
    print(' '.join([''.join(indent),
                    '.'.join(dec + ["0"] if root.children and zeroes else dec),
                    root.name]))
    for index, child in enumerate(root.children, 1):
        print_hierarchy(child,
                        indent + [indent[0]] if indent else indent,
                        dec + [str(index)] if dec else dec,
                        zeroes)

print_hierarchy(root, "\t", 1, True)

rawDescription: Printing a numbered outline of a hierarchical tree


rawDescription: Matplotlib table formatting

description: Matplotlib table formatting


code:
import random

def roll_die(die_type, roll_times, print_op=False):
    total_roll = 0              # you need to use an iterable to iterate over
    for _ in range(roll_times): # range is made for this
        roll_result = random.randint(1, die_type)
        total_roll += roll_result # you mixed these up
        if print_op:
            print(roll_result)
    if print_op:
        print(total_roll)
    return total_roll # don't forget to return your result

rawDescription: Die roller using python

description: Die roller using python


code:
for k,v in c.items():
    print(k,v)

rawDescription: Fastest way to count the occurance of a string


code:
import wilma
count = 4
def main():
    wilma.pr('Hello')

rawDescription: Breaking Python Circular Imports

description: Breaking Python Circular Imports


rawDescription: Static lists in Python for arithmetic manipulations


code:
def render_js(self):
    return [u'<script type="text/javascript" src="%s"></script>' % self.absolute_path(path) for path in self._js]

rawDescription: Django: accessing raw urls of form media in templates


code:
class SubDict(dict):
    def __init__(self, *args, **kw):
        super(SubDict, self).__init__(*args, **kw)
        for key, value in self.iteritems():
            if isinstance(value, dict):
                self[key] = SubDict(value)

rawDescription: Subclassing dict and nested dicts in it

description: Subclassing dict and nested dicts in it


rawDescription: Accessing file path in the os

description: Accessing file path in the os


code: var = 2

rawDescription: Importing same variable from multiple libraries


code:
import requests
metadata_server = "http://metadata/computeMetadata/v1/instance/"
metadata_flavor = {'Metadata-Flavor' : 'Google'}
gce_id = requests.get(metadata_server + 'id', headers = metadata_flavor).text
gce_name = requests.get(metadata_server + 'hostname', headers = metadata_flavor).text
gce_machine_type = requests.get(metadata_server + 'machine-type', headers = metadata_flavor).text

rawDescription: Get the name or ID of the current Google Compute Instance


code: self.ie = iewin.IEHtmlWindow(self, -1, style =wx.NO_FULL_REPAINT_ON_RESIZE)

rawDescription: Wxpython cut copy paste and openfiledialog


code:
web_API_gain_value = 0.5

gain_in_db = ratio_to_db(web_API_gain_value)

sound_after_gain = sound.apply_gain(gain_in_db)

rawDescription: Recreating Web Audio API GainNode behaviour


code: del df['sortby']

rawDescription: Pandas MultiIndex levels custom sort

description: Pandas MultiIndex levels custom sort


code: from . import mybp

rawDescription: Using route decorator in a Flask blueprint's submodule


code:
calc_routes = []
futures = {}
with FuturesSession(executor=ThreadPoolExecutor(max_workers=1000)) as session:
    # Submit all the requests and process in background
    for i in range(len(url_routes)):
        url_in, qid = url_routes[i]  # url |query-id
        future = session.get(url_in, background_callback=lambda sess, resp: ReqOsrm(sess, resp))
        futures[future] = qid

    # this was indented under the code in section B of the question
    # process the futures as they become copmlete
    for future in as_completed(futures):
        r = future.result()
        try:
            row = [futures[future]] + r.data

        except Exception as err:
            print('No route')
            row = [futures[future], 999, 0, 0, 0, 0, 0, 0]
        print(row)
        calc_routes.append(row)

rawDescription: Python requests - threads/processes vs. IO


code:
"""
main_program.py: a chemical program
"""
from database import login_info
import mysql.connector

conn = mysql.connector.Connect(**login_info)
curs = conn.cursor()

# STORE
curs.execute("""INSERT INTO table_name(row1,row2) VALUES("foo","bar")""")
conn.commit()

# RETRIVE
curs.execute("""SELECT * FROM table_name""")
results = curs.fetchall()
for result in results:
    print(result)

rawDescription: Simplest way to have my python program store/retrieve information from an online database?


code:
import os
outws = wd+"Stacked_Images_Folder/"
os.makedirs(outws)
arcpy.CompositeBands_management(raster_list, outws + "stacked_img.tif")

rawDescription: Batch processing raster images with Arcpy


code:
extra_context = {
    'foo': 'bar',
    # etc
}
urlpatterns = patterns('django.views.generic.simple',
    (r'^$', 'direct_to_template', {'template': 'index.html', 'extra_context': extra_context }),
)

rawDescription: Django index page best/most common practice


code:
import mytimer
import module1

mytimer.stop(msg="Timer from module1:")

# restart timer
mytimer.start()
# .. do something here
# and then get timer with specific message
mytimer.stop(msg='Finished at')

rawDescription: Python creating timestamps at different locations/classes to log function block run time


code:
sloc2 = set(loc2)
loc3 = [ item for item in loc1 if item in sloc2 ]  #still O(m)

rawDescription: python: Find matching tuples in the list

description: Python: Find matching tuples in the list


rawDescription: Importing Python modules from a distant directory


code: [['BODYSTRUCTURE', ['text', 'plain', ['charset', 'ISO-8859-1'], None, None, 'quoted-printable', 1207, 50, None, None, None, None]]]

rawDescription: parsing parenthesized list in python's imaplib

description: Parsing parenthesized list in python's imaplib


code:
import dis
def use_int(n):
    return int(n)

def use_floordiv(n):
    return n // 1

dis.dis(use_int)
dis.dis(use_floordiv)

rawDescription: Which is the efficient way to convert a float into an int in python?


rawDescription: Python call a package submodule with variable module name


code: import it

rawDescription: Suggestions for writing this small piece of code more elegantly


code:
import re

def remove_commas_and_quotes(mystring):
    return re.sub(r'","|",|"', ',', re.sub(r'(?:(\d+?),)',r'\1',mystring))

rawDescription: Cleaning up commas in numbers w/ regular expressions in Python


code:
from django.db.models import Sum

class DepositAdmin(admin.ModelAdmin):

    def changelist_view(self, request, extra_context=None):
        aggregates = Deposit.objects.aggregate(Sum('money_re'))
        context = {'total_deposit': aggregates['money_re__sum']}
        if extra_context:
            context.update(extra_context)
        return super(DepositAdmin, self).changelist_view(request, context)

rawDescription: Django admin aggregation

description: Django admin aggregation


code:
def start_requests(self):
    yield Request("http://epgd.biosino.org/"
                  "EPGD/search/textsearch.jsp?"
                  "textquery={}"
                  "&submit=Feeling+Lucky".format(self.term))

rawDescription: How to pass parameters to scrapy spiders in program?

description: Pass parameters to scrapy spiders in program


code: TestEntry = Entry(self, text="", width = 100).grid(row=4,columnspan=6)

rawDescription: grid_remove on an Entry widget

description: Grid_remove on an Entry widget


code:
from timeit import timeit
from cProfile import runctx
from dis import dis

def analyse(*args):
    victim = 'detartrated'
    number = 1000
    for func in args:
        print('\n%s\n' % ('#' * 50))
        name = func.__name__
        print('test: %s(%r): %r' % (name, victim, func(victim)))
        code = '%s(%r)' % (name, victim)
        duration = timeit(
            code, 'from __main__ import %s' % name, number=number)
        usec = 1000000 * duration / number
        print('time: %s: %.2f usec/pass\n' % (code, usec))
        runctx(code, globals(), locals())
        dis(func)

def check_palin1(victim):
    """ check progressively inner chars """
    x = 0
    # len/2 is num of iter needed for guarantee
    while x < (len(victim)/2):
        # on pass n, compare nth letter and nth to last letter
        if victim[x+0] is victim[-(1+x)]:
            # then increment the n counter
            x += 1
        else:
            return False
    return True

def check_palin2(victim):
    """ check first and last chars repeatedly """
    tmp = []
    for i in victim:
        # convert string into list
        tmp.append(i)
    # if 1 or 0 char left, palin is guaranteed
    while len(tmp) > 1:
        # if the first and last characters are the same letter
        if tmp[0] is tmp[-1]:
            # remove them both
            tmp.pop(0)
            tmp.pop(-1)
        else:
            return False
    return True

def check_palin3(victim):
    """ reverse string and compare to original using a loop """
    tmp = ""
    # for every letter
    for i in victim:
        # cat it to the beginning, not append
        tmp = i + tmp
    return tmp == victim

def check_palin4(victim):
    """ reverse string and compare to original using slice syntax """
    return victim == victim[::-1]

analyse(check_palin1, check_palin2, check_palin3, check_palin4)

rawDescription: Performance of Various Methods to Test for a Palindrome [Python]


rawDescription: Pandas - group by consecutive ranges

description: Pandas - group by consecutive ranges


code:
food = ("Bread")
Bread = {"name": "Bread", "foodvalue": 10}
inv = []
# put the object (dict) in the inventory, not the string
inv.append(Bread)

rawDescription: Python: using dictionaries in conjunction with input


code:
list1 = [['a', 1], ['b', 2], ['c', 3], ['h', 5]]
list2 = [['d', 1], ['e', 2], ['f', 3], ['g', 4]]
mapping = {}
for a, b in list2:
    mapping.setdefault(b, []).append(a)

[[a, b] + mapping[b] for a, b in list1 if b in mapping]

rawDescription: Mapping 2 lists in Python 2.7

description: Mapping 2 lists in Python 2.7


code:
# Python 3
s = 'pingüino' # Unicode string
s
repr(s)
print(repr(s))
ascii(s)
print(ascii(s))
# Python 2
s = u'pingüino'
s
repr(s)
print(repr(s))

rawDescription: How to convert *any* Python object into a string?

description: Convert *any* Python object into a string


code: [[int(x) for x in line.split()] for line in Inputstring.splitlines()]

rawDescription: Format for arrays in Python

description: Format for arrays in Python


code: CAT('Line 1', BR(), 'Line 2')

rawDescription: multi line headers with web2py's SQLFORM.grid

description: Multi line headers with web2py's SQLFORM.grid


code:
def func(input_strings):
    # Make the input_strings iterable
    if isinstance(input_strings, str):
        input_strings = (input_strings, )
    # Do something
    for input_string in input_strings:
        analyze_string(input_string)
    return

rawDescription: Count number of strings

description: Count number of strings


code:
def center_ylabels(ax1, ax2):

    pos2 = ax2.get_position()
    right = pos2.bounds[0]

    pos1 = ax1.get_position()
    left = pos1.bounds[0] + pos1.bounds[2]

    offset = ((right - left) / pos2.bounds[2]) * -0.5

    for yt in ax2.get_yticklabels():
        yt.set_position((offset, yt.get_position()[1]))
        yt.set_ha('center')

        plt.setp(ax2.yaxis.get_major_ticks(), pad=0)

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(10,2))
fig.subplots_adjust(wspace=0.5)

ax1.barh(y, diff, align='center')
ax1.set_yticks(y)
ax1.yaxis.set_major_formatter(matplotlib.ticker.NullFormatter())

ax2.barh(y, data, align='center')
ax2.set_yticks(y)
ax2.set_yticklabels(['reference', 'something', 'something else', 'nothing'])

center_ylabels(ax1, ax2)

rawDescription: Matplotlib: Center tick-labels between subplots


rawDescription: Decorating a function with a method (with arbitrary arguments)


rawDescription: Zip Two dict contain a list in Python

description: Zip Two dict contain a list in Python


code:
NH08OTR, 2008, Vauxhall, Corsa, Blue, In
NH08OTY, 2008, Vauxhall, Corsa, Blue, Out
NH08OTZ, 2008, Vauxhall, Corsa, Blue, In

rawDescription: Overwriting/changing a field on a CSV in Python


code:
@composed(dec1, dec2)
def some(f):
    pass

rawDescription: Can I combine two decorators into a single one in Python?

description: Combine two decorators into a single one in Python


code:
a = numpy.arange(12)
a

rawDescription: Difference between numpy.array shape (R, 1) and (R,)


code:
for r in np.linspace(r_a, r_b, circles):
    pylab.gca().add_patch(pylab.Circle(origin, radius=r,
                                       fill=False, color='black'))

rawDescription: Creating a 2d mesh in python

description: Creating a 2d mesh in python


code:
import threading

class YourClass:
    def __init__(self):
        #...
        self.local = threading.local()  # Thread local storage for db handles
        self.db_file = "/path/to/db"
        #...
    def db_open(self):
        if not getattr(self.local, "db", None):
            self.local.db = sqlite3.connect(self.db_file)
        return self.local.db

rawDescription: A database for python 3?

description: A database for python 3


code:
df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
df
df.ix[1, 'foo']

rawDescription: Pandas - Get first row value of a given column


code:
import importlib

cls = "somemodule.Test"
module_name, class_name = cls.split(".")

somemodule = importlib.import_module(module_name)

print(getattr(somemodule, class_name))

rawDescription: Get python class object from string

description: Get python class object from string


code:
'{:<15}'.format('Spams spam and spam'[:15])
'{:<15}'.format('viking inc'[:15])

rawDescription: A simple way to pad and slice to get a fixed length string


rawDescription: Python multiprocessing for expensive operation with 2D array


code:
def f():
    return f.x

rawDescription: how can python function access its own attributes?

description: How can python function access its own attributes


code: [word for word in MyWords.split() if word.upper() not in SpamWords]

rawDescription: Python String Method Conundrum

description: Python String Method Conundrum


code: seen=set(i.strip() for i in open('infile.txt'))

rawDescription: Use regular expression to delete duplicate strings with python


code:
def finder(s):
   seen,yields=set(),set()
   for i in s:
     if i in seen:
        if i not in yields:
           yield i
           yields.add(i)
        else :
           yields.add(i)
     else:
         seen.add(i)

list(finder(a))

rawDescription: Testing whether a string has repeated characters


code:
solution = sy.solve(equations)
# {c: 5, b: 10, a: 15}

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

description: Evaluate an expression-tree in sympy


code:
import numpy as np
a = np.matrix([[1,2],[3,4]])
b = np.matrix([[1,1],[1,1]])
a * b

rawDescription: How to pack the elements of product of matrix multiplication back

description: Pack the elements of product of matrix multiplication back


code: str(contents).replace(r'\t', ' ')

rawDescription: How to treat \t as a regular string in python

description: Treat \t as a regular string in python


code:
from .filters import filter_factory

def product_list(request):
    lookup_type_user = request.GET.get('lookup_type', 'exact')
    ProductFilter = filter_factory(lookup_type_user)
    filtered_data = ProductFilter(request.GET, queryset=Product.objects.all())
    return render(request, 'template.html', {'f': filtered_data})

rawDescription: Taking unrelated code out of views.py

description: Taking unrelated code out of views.py


code:
try:
    import simplejson as json
except ImportError:
    import json

rawDescription: Run all my doctests for all python modules in a folder without seeing failures because of bad imports


code:
def get_names(fle):
    with open(fle,"a") as f:
        while True:
            inp = input("Enter a name or 'q' to quit :")
            if inp == "q":
                return
            f.write("{}\n".format(inp))

def read_names(fle):
    # open names file
    with open(fle) as f:
        # iterate over the file
        # printing a name/line at a time
        for name in f:
            print(name)

rawDescription: Python 3.3 - Formatting Issue

description: Python 3.3 - Formatting Issue


code:
class AtomicJob:
    def __init__(self, a, b, c, d):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self._do_atomic_job()

    def _do_atomic_job(self):
        ...
        self.result_1 = 42
        self.result_2 = 23
        self.result_3 = 443

rawDescription: Overriding an inner function of a method in python


code:
from flask import Flask, render_template
from yourMySqlLibrary import connect_to_mysql

conn = connect_to_mysql()
# This is only executed when you start the script
data = conn.execute("SELECT * FROM MySemiRegularlyUpdatedTable")

app = Flask(__name__)

@app.route("/")
def view_data():
    return render_template("view_data.html", data=data)

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

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


code:
import os

def is_directory_traversal(file_name):
    current_directory = os.path.abspath(os.curdir)
    requested_path = os.path.relpath(file_name, start=current_directory)
    requested_path = os.path.abspath(requested_path)
    common_prefix = os.path.commonprefix([requested_path, current_directory])
    return common_prefix != current_directory

rawDescription: Does my code prevent directory traversal?


code:
df['Roster ID'] = df['EmployeeID'] + df['Short Date'].map(str)
df

rawDescription: Strip time from an object date in pandas


code:
b_object = B.objects.get(name='Bob')
A.objects.filter(bs=b_object)

rawDescription: Django getting related objects in a many-to-many relationship


code:
keys = ['proxy_host', 'proxy_port', 'proxy_protocol']
if all(settings.get(k) for k in keys):
    print("Settings good!")
else:
    print("Missing setting!")

rawDescription: One liner conditional, multiple variables and check that all of them are not false?


code: from myapp.fields import SeparatedValuesField

rawDescription: where to save the custom field class in django?

description: Where to save the custom field class in django


code:
from django.db.models.functions import Substr
m = Request.objects.filter(Q(type__icontains='4'), Q(wt__in =['giga','mega']))
context['all_items'] = m.annotate(mysubstring=Substr('type1',1,2)).order_by('type1')

rawDescription: How to get Substr of values

description: Get Substr of values


code:
entry_points = """\
[paste.app_factory]
main = myapp:main
[paste.filter_app_factory]
raven = myapp.sentry:sentry_filter_factory
""",

rawDescription: How do I report the currently logged in user to Sentry?

description: Report the currently logged in user to Sentry


code: #!/usr/bin/env python

rawDescription: Asynchronous stdin read in Python

description: Asynchronous stdin read in Python


code:
L4 = [ n for n in L1 if (n not in L2) and (n not in L3) ]  # parens for clarity

tmpset = set( L2 + L3 )
L4 = [ n for n in L1 if n not in tmpset ]

rawDescription: Python - removing items from lists

description: Python - removing items from lists


code: food_entry = Text(new_window_entry, width = 55, height = 2, wrap = WORD).grid(sticky = W, columnspan = 2)

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


rawDescription: Python: Getting the top 4 Highest Values in a 2d List


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


code:
def readFile(self):

    lookup = input("Type in a contact REFERENCE name.\n")

    with open('contacts.txt') as myFile:
        my_file_iter = iter(myFile)
        for num, line in enumerate(my_file_iter, 1):
            if lookup.upper() in line:

                print(line)
                print(next(my_file_iter))
                print(next(my_file_iter))
                print(next(my_file_iter))
                print(next(my_file_iter))
                break
        else:
            print("Contact not found.")
    self.managerMenu()

rawDescription: Python Not finding phrase on any line other than first?


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


code:
def add_default_meta(name, bases, attrs):
    cls = type(name, bases, attrs)
    cls.default = cls()
    return cls

rawDescription: Create current class default instance in its base class


code:
self._action_group = gtk.ActionGroup("ExamplePyPluginActions")
self._action_group.add_actions([("ExamplePy", None, _("Clear document"),
         None, _("Clear the document"),
         self.on_clear_document_activate)])
manager.insert_action_group(self._action_group, -1)

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

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


code:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('
Category: a link
')
soup.find('a')
soup.find('a').previousSibling

rawDescription: Use BeautifulSoup to extract text before the first child tag


code:
fig = plt.figure()
ax1 = plt.subplot(131)
ax2 = plt.subplot(132)
ax3 = plt.subplot(133)

ax1 = test1_pie.plot(kind='pie', y=test1, ax=ax1)
ax1.axis('equal')

ax2 = test2_pie.plot(kind='pie', y=test2, ax=ax2)
ax2.axis('equal')

ax3 = test3_pie.plot(kind='pie', y=test3, ax=ax3)
ax3.axis('equal')

rawDescription: Creating Pie Subplots of Circular Type in Python


code: actor = Actor(image_getter=SurfaceCapsule(resource_manager, key))

rawDescription: How should I serialize game objects containing pygame surfaces?


code:
import asyncio

# `coroutine_read()` generates some data:
i = 0
async def coroutine_read():
    global i
    i += 1
    await asyncio.sleep(i)
    return i

# `f()` is asynchronous iterator.
# Since we don't raise `StopAsyncIteration`
# it works "like" `while True`, until we manually break.
class f:
    async def __aiter__(self):
        return self

    async def __anext__(self):
        return await coroutine_read()

# Use f() as asynchronous iterator with `async for`:
async def main():
    async for i in f():
        print(i)
        if i >= 3:
            break

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

rawDescription: Lazy iterators (generators) with asyncio


code:
with open("A") as textfile:
    text = textfile.read()

rawDescription: Python string comparison whilst in loop

description: Python string comparison whilst in loop


code:
def test(argline):
    namespace = parser.parse_args(argline.split())
    kind,value = namespace.request
    print(namespace.vehicle, kind, value)

rawDescription: Advice for using argparse

description: Advice for using argparse


code: LOGIN_URL = '/login/'

rawDescription: Redirecting Django built-in login View to a URL taking user's pk as argument


code:
import pandas as pd
dict_data = [{'duration': 0.7, 'project_id': 3, 'resource': u'Arya Stark', 'activity': u'Development'},
{'duration': 0.9, 'project_id': 4, 'resource': u'Ned Stark', 'activity': u'Development'},
{'duration': 2.88, 'project_id': 7, 'resource': u'Robb Stark', 'activity': u'Development'},
{'duration': 0.22, 'project_id': 9, 'resource': u'Jon Snow', 'activity': u'Support'},
{'duration': 0.3, 'project_id': 9, 'resource': u'Jon Snow', 'activity': u'Support'},
{'duration': 2.15, 'project_id': 3, 'resource': u'Arya Stark', 'activity': u'Practise'},
{'duration': 3.35, 'project_id': 4, 'resource': u'Sansa Stark', 'activity': u'Development'},
{'duration': 2.17, 'project_id': 9, 'resource': u'Rickon Stark', 'activity': u'Development'},
{'duration': 1.03, 'project_id': 4, 'resource': u'Benjan Stark', 'activity': u'Design'},
{'duration': 1.77, 'project_id': 4, 'resource': u'Bran Stark', 'activity': u'Testing'},
{'duration': 1.17, 'project_id': 4, 'resource': u'Ned Stark', 'activity': u'Development'},
{'duration': 0.17, 'project_id': 9, 'resource': u'Jon Snow', 'activity': u'Support'},
{'duration': 1.77, 'project_id': 3, 'resource': u'catelyn stark', 'activity': u'Development'},
{'duration': 0.3, 'project_id': 9, 'resource': u'Jon Snow', 'activity': u'Support'},
{'duration': 0.45, 'project_id': 9, 'resource': u'Jon Snow', 'activity': u'Support'}]

df = pd.DataFrame(dict_data)
dfg = df.groupby(['project_id','resource','activity']).sum()
dfg.to_html('result.html')

rawDescription: List of dictionary in python as HTML Table format


code:
np.where(data != data.round())
(array([2, 3]),)

rawDescription: How can I get index of elements which are not integer

description: Get index of elements which are not integer


code:
def flash(self, count):
        try:
            self.correctMessage.undraw()
            self.incorrectMessage.undraw()

            diameter = 50
            centers = ((55,55),  (170,55), (285,55),  (55,170), (170,170),
                   (285,170), (55,285), (170,285), (285,285))
            circles = list()
            for point in centers:
                c = Circle(Point(point[0], point[1]), diameter)
                circles.append(c)
                c.setFill("blue")
                c.draw(self.win)
            circles[count].setFill("yellow")
            mouseClick = self.win.getMouse()

            leftX  = centers[count][0] - diameter
            rightX = centers[count][0] + diameter
            upperY = centers[count][1] - diameter
            lowerY = centers[count][1] + diameter
            if (upperY < mouseClick.y < lowerY) and (leftX < mouseClick.x < rightX):
                self.correctMessage.draw(self.win)
            else:
                self.incorrectMessage.draw(self.win)

        except:
            self.win.exit(0)

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


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


code:
from endless_pagination.views import AjaxListView
class EntryList(AjaxListView):
    model = Entry
    context_object_name = 'entry_list'
    page_template = 'entry.html'

rawDescription: django-endless with class based views example

description: Django-endless with class based views example


rawDescription: Python: How to find path to the script running a python script


code:
def f(): return 23+100

dis.dis(f)

rawDescription: What optimizations does Python do without the -O flags?


code:
func_dict = {}

def collected_func(func):
    func_dict[func.__name__] = func
    return func

rawDescription: python function that returns a function from list of functions

description: Python function that returns a function from list of functions


code:
l = []
l.extend("hello, world")
l
l = []
l.extend("hello, world".split(", ")) # right
l

rawDescription: Python3 input() floats list

description: Python3 input() floats list


code:
from collections import Counter
Counter([1, 1, 2, 3, 3, 1, 2]).values()
Counter(["a", "a", "b", "c", "c"]).values()

rawDescription: Construct list of numbers of occurrences in list


code:
from matplotlib.pyplot import show

from hcluster import pdist, linkage, dendrogram
import numpy
from numpy.random import rand

X = rand(10,100)
X[0:5,:] *= 2
Y = pdist(X)
Z = linkage(Y)
dendrogram(Z)

show()

rawDescription: Dendrogram generated by scipy-cluster does not show


code: x = {"DB{0}".format(row[0] + 1): row[1][u"name"] for row in enumerate(cursor)}

rawDescription: Assign variables to dictionary items with same key


code: res = eval(s.replace('x', '*'))

rawDescription: Resolve variables from a string

description: Resolve variables from a string


code:
try:
    import sys
    for trial in range(1):
        if raw_input('Password:') == 'password':
            break
    else:
        raise SystemExit #or just sys.exit()
    print ("Welcome in")
except SystemExit:
    pass  #when the program throws SysExit do nothing here,i.e end silently

rawDescription: How to stop a program in Idle, python 3.2

description: Stop a program in Idle, python 3.2


code:
data = """1467153  12309
1466231  21300
1478821  10230
"""
l = sorted([list(map(int, line.split())) # convert each pair to integers
            for line                     # iterate over lines in input
            in data.split("\n")          # split on linebreaks
            if line],                    # ignore empty lines
    key=lambda x: x[0])                  # sort by firt element of pair
print(l)

rawDescription: sorting a list of two columns based on one column python

description: Sorting a list of two columns based on one column python


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

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


code: button = Button(admin, text='Press', command=sequence(o, t))

rawDescription: tkinter call two functions

description: Tkinter call two functions


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

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


code:
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= str(ladder_data[f][1]))
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )

rawDescription: Access a specific sizer from wxFormBuilder in Python


code:
import itertools
import operator

for g, inds in itertools.groupby(enumerate(A), key=operator.itemgetter(1)):
    ...

rawDescription: groupby on sparse matrix with scipy

description: Groupby on sparse matrix with scipy


code:
colors = fields.Selection('get_colors', 'Colors')

@classmethod
def get_colors(cls):
   #You can access the pool here.
   User = Pool.get('res.user')
   users = User.search([])
   ret = []
   for user in users:
      if user.email:
         ret.append(user.email, user.name)
   return ret

rawDescription: how fill Selection field in tryton

description: How fill Selection field in tryton


code:
def func(x):
    return pd.Series({'Obs': len(x)
                    , 'Sum': x.price.sum()
                    , 'Zeros': len(x[x.price==0])})

rawDescription: How to combine different data sets in Pandas (python 3)?

description: Combine different data sets in Pandas (python 3)


code:
someobj = None
@pytest.fixture(scope='session', autouse=True)
def prep_someobj(request):
    someobj = SomeObj()

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

description: Share object from fixture to all tests using pytest


rawDescription: Unable to retrieve element of desired XPATH using BeautifulSoup


code:
[
{'company': {'employee': {'age': 20, 'name': 'john', 'others': {'grade': 'A'}}}},
{'company': {'employee': {'age': 20, 'name': 'john', 'others': {'grade': 'B'}}}},
{'company': {'employee': {'age': 20, 'name': 'tom', 'others': {'grade': 'A'}}}},
{'company': {'employee': {'age': 20, 'name': 'tom', 'others': {'grade': 'B'}}}},
{'company': {'employee': {'age': 30, 'name': 'john', 'others': {'grade': 'A'}}}},
{'company': {'employee': {'age': 30, 'name': 'john', 'others': {'grade': 'B'}}}},
{'company': {'employee': {'age': 30, 'name': 'tom', 'others': {'grade': 'A'}}}},
{'company': {'employee': {'age': 30, 'name': 'tom', 'others': {'grade': 'B'}}}}
]

rawDescription: Generate all combinations from a nested python dictionary and segregate them


rawDescription: python how to find exact match of a number in a string

description: Python how to find exact match of a number in a string


code:
for element in islice(items, 0, limit):
    ...

rawDescription: How can I limit iterations of a loop in Python?

description: Limit iterations of a loop in Python


code:
for unread_row in unread_answers:
    row_id = unread_row.get_attribute("id")
    m = re.search('answer_row_\d*', row_id)
    row_number = m.group(1)

rawDescription: python - how can I select a class and get the number of another class with whitespace between them using selenium

description: Python - how can I select a class and get the number of another class with whitespace between them using selenium


code:
import numpy as np
import scipy.spatial.distance

coords_arr = np.array([['pt1', 2452130.000, 7278106.000, 25.000],
                       ['pt2', 2479539.000, 7287455.000, 4.900],
                       ['pt3', 2479626.000, 7287458.000, 10.000],
                       ['pt4', 2484097.000, 7292784.000, 8.800],
                       ['pt5', 2484106.000, 7293079.000, 7.300],
                       ['pt6', 2484095.000, 7292891.000, 11.100]])

dists = scipy.spatial.distance.pdist(coords_arr[:,1:3], 'euclidean')

# Create a shortcut for `coords_arr.shape[0]` which is basically
# the total amount of points, hence `n`
n = coords_arr.shape[0]

# `a` and `b` contain the indices of the points which were used to compute the
# distances in dists. In this example:
# a = [0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4]
# b = [1, 2, 3, 4, 5, 2, 3, 4, 5, 3, 4, 5, 4, 5, 5]
a = np.arange(n).repeat(np.arange(n-1, -1, -1))
b = np.hstack([range(x, n) for x in xrange(1, n)])

min_d = 1000
max_d = 10000

# Find out which distances are in range.
in_range = np.less_equal(min_d, dists) & np.less_equal(dists, max_d)

# Define the datatype of the structured array which will be the result.
dtype = [('a', '<f8', (3,)), ('b', '<f8', (3,)), ('dist', '<f8')]

# Create an empty array. We fill it later because it makes the code cleaner.
# Its size is given by the sum over `in_range` which is possible
# since True and False are equivalent to 1 and 0.
result = np.empty(np.sum(in_range), dtype=dtype)

# Fill the resulting array.
result['a'] = coords_arr[a[in_range], 1:4]
result['b'] = coords_arr[b[in_range], 1:4]
result['dist'] = dists[in_range]

print(result)

# In caste you don't want a structured array at all, this is what you can do:
result = np.hstack([coords_arr[a[in_range],1:],
                    coords_arr[b[in_range],1:],
                    dists[in_range, None]]).astype('<f8')
print(result)

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


rawDescription: How to get the calling class name inside a function

description: Get the calling class name inside a function


code:
# ... insert example code in OP's SO link to get client object

# uploading
s = 'This is a line\n'
s += 'This is another line'
response = client.put_file('/magnum-opus.txt', s)

rawDescription: Read and Write Dropbox Files without External Files


code:
#!/usr/bin/env python3
from time import monotonic as timer
from tkinter import font, Tk, ttk

distance = 100 # meters
START, STOP = 'start', 'stop'

class Stopwatch(object):
    def __init__(self, parent):
        self.parent = parent
        # create a button, run `.toggle_button` if it is pressed
        self.button = ttk.Button(parent,text=START, command=self.toggle_button)
        self.button.grid(sticky='nwse') # lays out the button inside the parent

    def toggle_button(self, event=None):
        if self.button is None: # close parent window
            self.parent.destroy()
        elif self.button['text'] == START: # start timer
            self.start = timer()
            self.button['text'] = STOP
        elif self.button['text'] == STOP: # stop timer, show result
            elapsed = timer() - self.start
            self.button.destroy()
            self.button = None
            text = "Speed {:.2f} m/s".format(distance / elapsed)
            ttk.Label(self.parent, text=text, anchor='center').grid()

root = Tk() # create root window
root.protocol("WM_DELETE_WINDOW", root.destroy)  # handle root window deletion
root.bind('<Return>', Stopwatch(root).toggle_button) # handle <Enter> key
root.mainloop()

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

description: Use a button as an input in python


code:
foobar
foobaz

rawDescription: changing values inside a local space by a function in that local space

description: Changing values inside a local space by a function in that local space


code:
d = pd.Series(["aaa","bbb","ccc","ddd"])
d
d.str.title()
d.str.title().str.replace("Cc","RRR")

rawDescription: Replacing certain values in a pandas dataseries?


code:
import os
from docx import getdocumenttext, opendocx
from lxml import etree

## load the xml tree from word document ##
# EITHER:
tree = opendocx('/path/to/my/file.docx')

# OR
xml_content = """<?xml version="1.0" encoding="utf-8"?>
<w:document mc:Ignorable="w14 w15 wp14" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mo="http://schemas.microsoft.com/office/mac/office/2008/main" xmlns:mv="urn:schemas-microsoft-com:mac:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">
 <w:body>
  <w:p>
   <w:r>
    <w:t>0 things and stuff</w:t>
   </w:r>
  </w:p>
  <w:p>
   <w:r>
    <w:t>1 things and stuff</w:t>
   </w:r>
  </w:p>
 </w:body>
</w:document>
"""
tree = etree.fromstring(xml_content)
##

paragraphs = getdocumenttext(tree)
print(os.linesep.join(paragraphs))

rawDescription: Preserve newlines when pulling text from xml


code:
line = raw_input()
num1, _, num2 = line.partition('+')
print(int(num1) + int(num2))

rawDescription: Splitting input into two with for-loop

description: Splitting input into two with for-loop


code:
path = os.environ["PATH"] # a ':'-separated string
path += ":/var/custom/bin"
os.environ["PATH"] = path

rawDescription: PATH variable in Python

description: PATH variable in Python


code:
workers = 2
bind = 'unix:/tmp/my_project_name.sock'  # Binds to a unix socket rather than ip/port
errorlog = '/path/to/logs/gunicorn.error.log'

def when_ready(server):
    from django.core.management import call_command
    call_command('validate')

rawDescription: Adding a hook to Gunicorn for raven-python (sentry client)


code:
users = data.set_index('date')['user_id']
visits = pd.get_dummies(users)

rawDescription: Using DataFrame to get matrix of identifiers


code:
import requests
from BeautifulSoup import BeautifulSoup
r = requests.get('http://vtv.vn/')
r.encoding = "utf-8"
raw_html = r.text
soup = BeautifulSoup(raw_html)
soup.findAll("option")

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


code: result = df.groupby(['G', 'User'])['C'].value_counts()

rawDescription: pandas - group and count nunique values

description: Pandas - group and count nunique values


code:
def words(stream):
    for line in stream:
        yield line[:max(line.find(' '), 0) or None]

rawDescription: Python: read one word per line of a text file


code:
def readFile():
    # with is used when a resource is only needed in a certain context.
    # we'll use it for opening files so they close automatically.
    with open("myFile.txt", "r") as f:
        return f.readlines()

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

description: Split a file into seperate lines in python


code:
def index() :
    return render_template('index.html', obj = "object", data = "a223jsd" );

rawDescription: How to return multiple values in render_template in Flask

description: Return multiple values in render_template in Flask


code:
chars_to_remove = [u'δ', u'Γ', u'ж']
subj = u'AжBδCΓ'
dd = {ord(c):None for c in chars_to_remove}
subj.translate(dd)

rawDescription: Removing a list of characters in string

description: Removing a list of characters in string


rawDescription: How to add a plus sign before an int in Python?

description: Add a plus sign before an int in Python


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

description: Find specific video html tag using beautiful soup


code: pairs = lines.map(myParser).filter(lambda x: x != ((-1, -1), -1))

rawDescription: Remove elements from Spark RDD

description: Remove elements from Spark RDD


code:
set_b = set(b)
c = [i for i in a if i not in set_b]

rawDescription: Find items not in common between lists in Python


code:
def change_type(my_var):
    try:
        if float(my_var[0]) > 0:
            my_var[0] = float(my_var[0])
    except ValueError:
        pass

some_var = ['0.5']
change_type(some_var)
print(type(some_var[0]))

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


code:
if __name__ == '__main__':
    import sys
    kernel32 = WinDLL('kernel32')

    hFile = kernel32.CreateFileW(sys.exec_prefix,
                                 0x80000000,      # GENERIC_READ
                                 1,               # FILE_SHARE_READ
                                 None,
                                 3,               # OPEN_EXISTING
                                 0x02000000,      # BACKUP_SEMANTICS
                                 None)

    fdilist = []
    iosb = IO_STATUS_BLOCK()
    info = (c_char * 512)()
    while True:
        status = NtQueryDirectoryFile(hFile,
                                      None,
                                      None,
                                      None,
                                      byref(iosb),
                                      byref(info),
                                      sizeof(info),
                                      FileDirectoryInformation,
                                      False,
                                      None,
                                      False)
        if (iosb.Information == 0 and status >= 0 or
            status == STATUS_BUFFER_OVERFLOW):
            info = (c_char * (sizeof(info) * 2))()
        elif status == STATUS_NO_MORE_FILES:
            break
        elif status >= 0:
            fdilist.extend(FILE_DIRECTORY_INFORMATION.listbuf(info))
        else:
            raise NTError(status)

    kernel32.CloseHandle(HANDLE(hFile))

    for fdi in fdilist:
        print(fdi.FileName)

rawDescription: Python NtQueryDirectoryFile (File information structure)


code: my_list.sort(key=lambda x: x[1])

rawDescription: Sort tuples based on second parameter

description: Sort tuples based on second parameter


code:
timeit.Timer("'A' in l", "from string import ascii_letters, digits, whitespace; l = list(ascii_letters + digits + whitespace)").timeit(999999)
timeit.Timer("'A' in s", "from string import ascii_letters, digits, whitespace; s = set(ascii_letters + digits + whitespace)").timeit(999999)
timeit.Timer("'A' in s", "from string import ascii_letters, digits, whitespace; s = ascii_letters + digits + whitespace").timeit(999999)

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


code:
def items(self, section):
    try:
        d2 = self._sections[section]
    except KeyError:
        if section != DEFAULTSECT:
            raise NoSectionError(section)
        d2 = self._dict()
    d = self._defaults.copy()
    d.update(d2)
    if "__name__" in d:
        del d["__name__"]
    return d.items()

rawDescription: Why does ConfigParser items() give raw strings while get() returns bool/float/etc?


code:
ugDict = {}

for row in rows:
  mergedGroup = set(row) & valid
  for user in row:
    if user in ugDict:
      mergedGroup |= ugDict[user]
  for user in mergedGroup:
    ugDict[user] = mergedGroup

rawDescription: Sorting rows into groups based on shared values


code: C = ffi.dlopen('spreadsort.so')

rawDescription: How to sort an array of integers faster than quicksort?

description: Sort an array of integers faster than quicksort


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

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


code: [double_middle_items(l) for l in list_of_lists]

rawDescription: Double all columns except for the first and the last one


code:
#I contain a link.
#blah
#blah2

rawDescription: Get bulletted list in lxml

description: Get bulletted list in lxml


code: plink = link[-3:]

rawDescription: Split and take n words from the end

description: Split and take n words from the end


code:
import ast
all_odds['-5.00'] = ast.literal_eval(all_odds['-5.00'])

rawDescription: Removing nested dict items with dict comprehension


code:
import numpy as np

def get_value(dt):
    left = dt.tree_.children_left
    right = dt.tree_.children_right
    value = dt.tree_.value
    leaves = np.argwhere(left == -1)[:, 0]

    def visit(node):
        if node in leaves:
            return
        visit(left[node])
        visit(right[node])
        value[node, :] = value[left[node], :] + value[right[node], :]

    visit(0)
    return value

rawDescription: How to get pos/neg instance counts for all nodes of a scikit-learn decision tree?

description: Get pos/neg instance counts for all nodes of a scikit-learn decision tree


code:
my_filter = (color for idx, color in list_of_tuples if idx in items_to_pick)
next(my_filter)
next(my_filter)
next(my_filter)
next(my_filter)
next(my_filter)

rawDescription: Python, to pick specific elements from a list of tuples


rawDescription: Slice numpy array based on x number of other arrays


code:
import re

escaped = re.sub(r'\\U([a-zA-Z0-9]{4})', r'\\u\1', inputstring)
result = escaped.decode('unicode_escape')

rawDescription: Problems with Unicode like string

description: Problems with Unicode like string


code:
data = []
# Extract the second row from the input file
# and store it in data
with open('input') as in_file:
    csv_reader = csv.reader(in_file, delimiter='\t')
    for row in csv_reader:
       data.append(row[1])

# The first two values in data is the suffix
# for the rest of your output file
suffix = ','.join(data[:2])

# Append the suffix to the rest of the values
# and write it out to the output file.
with open('output') as op_file:
    for item in data[2:]:
        op_file.write('{},{}\n'.format(suffix, item))

rawDescription: Convert text file into csv format

description: Convert text file into csv format


code:
def localx():
    if localpick == 1:
        mathschallenge()
    if localpick == 2:
        whaleq()

def mathschallenge():
    print('maths challenge yolo')
    quest = input('What is 10+10?')
    if quest == '20':
        print('correct')
    else:
        print('incorrect')

def whaleq():
    mammal = input('What is the largest mammal?')
    if mammal == 'whale':
        print('correct')
    else:
        print('incorrect')

print('The first thing you should think about doing is asking the locals if they have seen     anything!')

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

localpick = int(input('Type the number of the local you want to talk to '))
localx()
input('Press the enter key to exit')

rawDescription: defining variables and exectuing a variable python

description: Defining variables and exectuing a variable python


code:
with open('asdxk.csv', 'w') as outfile:
    fields = ['postcode', 'upline', 'cit_state', 'contact_person', 'contact_no','nominal_level', 'credit', 'level', 'account_holder', 'merchantid', 'email', 'bank', 'reg_date' ,'address','acc_no','company_name']
    writer = csv.DictWriter(outfile, fieldnames=fields)
    writer.writeheader()
    for x in cursor:
        writer.writerow(x)

rawDescription: Writing Data Into CSV Format File

description: Writing Data Into CSV Format File


code:
class Rectangle():
    def __init__(self,height=2, width=2):
        self.height = height
        self.width = width
    def setHeight(self, height):
        if type(height)!=int:
            self.height = 2
        else:
            self.height = height
    def setWidth(self, width):
        if type(width)!=int:
            self.width = 2
        else:
            self.width = width

    def getHeight(self):
        return self.height
    def getWidth(self):
        return self.width

    def perimeter(self):
        perimeter = ((2*self.height)+(2*self.width))
        return perimeter

    def area(self):
        return self.height * self.width

    def getStats(self):
        print("Width: {}".format(self.width))
        print("Height: {}".format(self.height))
        print("Area: {}".format(self.area()))
        print("Perimeter: {}".format(self.perimeter()))

def main():
    print ("Rectangle a:")
    a = Rectangle(5,7)
    print ("area: {}".format(a.area()))
    print ("perimeter: {}".format(a.perimeter()))
    print ()
    print ("Rectangle b:")
    b = Rectangle()
    b.width = 10
    b.height = 20
    b.getStats()

main()

rawDescription: Python: print statements not finding values in 2nd half, printing method bound?


rawDescription: Producing pdf report from python with bullet points


code:
import numpy as np

def gradient_descent(x, y, t0, t1, alpha, num_iters):

    m_num = len(x);

    for j in range(num_iters):
        t0_sum = 0
        t1_sum = 0

        for i in range(m_num):
            t0_sum += ((t1*x[i])+t0 - y[i])
            t1_sum += (((t1*x[i])+t0 - y[i])*(x[i]))

        t0 = t0 - ( alpha/m_num * (t0_sum) )
        t1 = t1 - ( alpha/m_num * (t1_sum) )

    return t0, t1

def norm_equation(x, y):
    m = len(x);
    x = np.asarray([x]).transpose()
    y = np.asarray([y]).transpose()

    x = np.hstack((np.ones((m, 1)), x))

    t = np.dot(np.dot(np.linalg.pinv(np.dot(x.transpose(), x)), x.transpose()), y)
    return t

x = [6, 5, 8, 7, 5, 8, 7, 8, 6, 5, 5, 14]
y = [17, 9, 13, 11, 6, 11, 4, 12, 6, 3, 3, 15]

t0 = 0
t1 = 0
alpha = 0.008
num_iters = 10000

t0, t1 = gradient_descent(x, y, t0, t1, alpha, num_iters)
print("Gradient descent:")
print("t0 = " + str(t0) + "; t1 = " + str(t1))

print

t = norm_equation(x, y)
print("Normal equation")
print("t0 = " + str(t.item(0)) + "; t1 = " + str(t.item(1)))

rawDescription: Non-vectorized Gradient Descent

description: Non-vectorized Gradient Descent


code:
def new_function_file(file_name, fun_name, arguments):

    f = open(file_name + ".py", 'w')

    # expand the arguments and join with "," separators:
    args = ", ".join(arguments)
    # use formatted print to put it all together nicely:
    write_string = "\tdef {fn}(self, {ar}):\n".format(fn=fun_name, ar=args)

    f.write(write_string)

rawDescription: Function arguments in creating function file dynamically


code:
import itertools
all_list_something = all(itertools.imap(is_valid, list_something))

rawDescription: Python - How to check Booleans inside a for loop?


code:
def sq(n):
    """
    Return the square of n, accepting all numeric types:

    >>> sq(10)
    100

    >>> sq(10.434)
    108.86835599999999

    Raises a TypeError when input is invalid:

    >>> sq(4*'435')
    Traceback (most recent call last):
      ...
    TypeError: can't multiply sequence by non-int of type 'str'

    """
    return n*n

rawDescription: What is the standard Python docstring format?


code: big_df.set_index(['period', 'id'])

rawDescription: Pandas: Dict of data frames to unbalanced Panel


code:
def swap(x):
    """Given a tuple (x1, x2) return (x2, 1)"""
    return (x[1], 1)

def filter_source(x):
    """Check if s1 < s2 in (x, (s1, s2))"""
    return x[1][0] < x[1][1]

def reshape(kv):
    """Reshape ((k1, k2), v) to get final result"""
    ((k1, k2), v) = kv
    return (k1, (k2, v))

rawDescription: Alternatives to cartesian in Spark?

description: Alternatives to cartesian in Spark


rawDescription: matplotlib problems plotting logged data and setting its x/y bounds

description: Matplotlib problems plotting logged data and setting its x/y bounds


code: np.apply_along_axis(example_func, 0, test_array, test_array2)

rawDescription: Numpy apply_along_axis function

description: Numpy apply_along_axis function


code: dict([(e[0], int(e[1])) for e in lst])

rawDescription: How to convert this list into a dictionary

description: Convert this list into a dictionary


code:
root = lxml.html.fromstring(lxml.etree.tostring(root))
root.cssselect('a.here')

rawDescription: lxml: Converting XML to HTML through XSLT and get HtmlElements

description: Lxml: Converting XML to HTML through XSLT and get HtmlElements


code:
from scipy import interpolate
hfunc = interpolate.interp2d(xi,yi,height)

pointheights = np.zeros(dat_so2["xp"].shape)
for i,(x,y) in enumerate(zip(dat_so2["xp"],dat_so2["yp"])):
    pointheights[i]=hfunc(x,y)

rawDescription: How to obtain the contour plot data for each scatter points?

description: Obtain the contour plot data for each scatter points


code:
for v1 in s1 : # Iterate over string1
    if v1 in vowels: # Check if each letter is a vowel
        if v1 in d1: # If the vowel is in dict1
            d1[v1] += 1 # Add 1 to the actual value
        else:
            d1[v1] = 1 # Add the vowel to dict1

rawDescription: Python- Using dictionaries to compare two lists


code:
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('save.txt')

countryName = config.get('Countries', 'MyCountry')

rawDescription: How can I save data to/load data from a text file as variables in Python?

description: Save data to/load data from a text file as variables in Python


code:
import sys
sys.path.append('.')

import sourcename
JINJA_FILTERS = {'sourcename':sourcename.tosource}

OPENCONTENT = "open:///pelican/knowledge_blog/content"

rawDescription: With Pelican, how to set or access variables between Python code and themes?


rawDescription: Vectorize haversine distance computation along path given by list of coordinates


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

import os
import sys
sys.path(os.path.join(os.path.dirname(sys.argv[0]), "lib"))
import docutils

rawDescription: Easy Deploying of Python and application in one Bundle , For Linux


code: ['Hi Dervin', 'This is the way to grab', 'Different divs with the same prefix in @class attribute']

rawDescription: Extracting divs with regular expressions


code:
import datetime
(datetime.date(1970,9,21) - datetime.date(1970, 1, 1)).days * 86400000

rawDescription: Equivalent of date.utc in python

description: Equivalent of date.utc in python


code:
from pyspark.sql import Row
from pyspark.mllib.linalg import Vectors
from pyspark.ml.feature import StringIndexer

def toVector(n):
    def _toVector(i):
        return Row("vec")(Vectors.sparse(n, {i: 1.0}))
    return _toVector

indexer = StringIndexer(inputCol="color", outputCol="colorIdx")
indexed = indexer.fit(df).transform(df)
n = indexed.select("colorIdx").distinct().count()

vectorized = indexed.select("colorIdx").map(toVector(n)).toDF()

rawDescription: Spark - Single column to columns of X classes


code:
ast.literal_eval()
import ast

# from
js_obj = "{'x':1, 'y':2, 'z':3}"

# to
py_obj = ast.literal_eval(js_obj)

rawDescription: How to convert raw javascript object to python dictionary?

description: Convert raw javascript object to python dictionary


code: differences = [r[3] - r[4] for r in table]

rawDescription: Arithmetic Operations with Nested Lists in Python


code: item = response.request.meta['item']

rawDescription: How to call Parse_page2 method for every item

description: Call Parse_page2 method for every item


code:
for x in t1( t2( t3( the_whole_structure ) ) ):
    print( x )

rawDescription: Sharing data between processes in Python


code: (k,sum(v)/float(len(v)))

rawDescription: converting list to dict and averaging the values of duplicates in python

description: Converting list to dict and averaging the values of duplicates in python


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

rawDescription: Mutation algorithm python

description: Mutation algorithm python


code:
from bs4 import BeautifulSoup
html_doc = """

Bob
(06 Jul at 09:21)

This message is very important to extract along with the matching author and time of submit

"""
soup = BeautifulSoup(html_doc)
soup.select('div.menu br')[0].next_sibling

rawDescription: Getting text from br tags in BeautifulSoup


code: solutions = set([])

rawDescription: Checking for unique output in Python

description: Checking for unique output in Python


code:
def sum_to(n):
    if n > 0:
        return sum_to(n-1) + 1.0 / n
    else:
        return 0

if __name__ == '__main__':
    print(sum_to(3))

rawDescription: Python 3 Recursion - Maximum Depth Exceeded


code:
import numpy as np
import cv2

A = cv2.imread(r"C:\path\to\a.png", 0)
B = cv2.imread(r"C:\path\to\b.png", 0)

#C = cv2.merge((B,A,B))
C = np.dstack((B,A,B))
cv2.imshow("imfuse",C)
cv2.waitKey(0)

rawDescription: How can I make the composite of two images in OpenCV with Python?

description: Make the composite of two images in OpenCV with Python


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


code:
# This file is NOT licensed under the GPLv3, which is the license for the rest
# of YouCompleteMe.
#
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <http://unlicense.org/>

import os
import ycm_core

# These are the compilation flags that will be used in case there's no
# compilation database set (by default, one is not set).
# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.
flags = [
'-Wall',
'-Wextra',
'-Werror',
'-Wno-long-long',
'-Wno-variadic-macros',
'-DNDEBUG',

# THIS IS IMPORTANT! Without a "-std=<something>" flag, clang won't know which
# language to use when compiling headers. So it will guess. Badly. So C++
# headers will be compiled as C headers. You don't want that so ALWAYS specify
# a "-std=<something>".
# For a C project, you would set this to something like 'c99' instead of
# 'c++11'.
'-std=c99',

# ...and the same thing goes for the magic -x option which specifies the
# language that the files to be compiled are written in. This is mostly
# relevant for c++ headers.
# For a C project, you would set this to 'c' instead of 'c++'.
'-x', 'c',

'-I', '.',

'-I', './src/',

'-I', './include/',

'-I', './ClangCompleter',

'-isystem', '../llvm/include',

'-isystem', '../llvm/tools/clang/include',

'-isystem', './tests/gmock/gtest',

'-isystem', './tests/gmock/gtest/include',

'-isystem', './tests/gmock',

'-isystem', './tests/gmock/include',

'-isystem', '/usr/include',

'-isystem', '/usr/local/include',

]

# Set this to the absolute path to the folder (NOT the file!) containing the
# compile_commands.json file to use that instead of 'flags'. See here for
# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html
#
# Most projects will NOT need to set this to anything; you can just change the
# 'flags' list of compilation flags. Notice that YCM itself uses that approach.
compilation_database_folder = ''

if os.path.exists( compilation_database_folder ):
  database = ycm_core.CompilationDatabase( compilation_database_folder )
else:
  database = None

SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ]

def DirectoryOfThisScript():
  return os.path.dirname( os.path.abspath( __file__ ) )

def MakeRelativePathsInFlagsAbsolute( flags, working_directory ):
  if not working_directory:
    return list( flags )
  new_flags = []
  make_next_absolute = False
  path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]
  for flag in flags:
    new_flag = flag

    if make_next_absolute:
      make_next_absolute = False
      if not flag.startswith( '/' ):
        new_flag = os.path.join( working_directory, flag )

    for path_flag in path_flags:
      if flag == path_flag:
        make_next_absolute = True
        break

      if flag.startswith( path_flag ):
        path = flag[ len( path_flag ): ]
        new_flag = path_flag + os.path.join( working_directory, path )
        break

    if new_flag:
      new_flags.append( new_flag )
  return new_flags

def IsHeaderFile( filename ):
  extension = os.path.splitext( filename )[ 1 ]
  return extension in [ '.h', '.hxx', '.hpp', '.hh' ]

def GetCompilationInfoForFile( filename ):
    # The compilation_commands.json file generated by CMake does not have entries
    # for header files. So we do our best by asking the db for flags for a
    # corresponding source file, if any. If one exists, the flags for that file
    # should be good enough.
    if IsHeaderFile( filename ):
        basename = os.path.splitext( filename )[ 0 ]
        for extension in SOURCE_EXTENSIONS:
            replacement_file = basename + extension
            if os.path.exists( replacement_file ):
                compilation_info = database.GetCompilationInfoForFile( replacement_file )
                if compilation_info.compiler_flags_:
                    return compilation_info
        return None
    return database.GetCompilationInfoForFile( filename )

def FlagsForFile( filename, **kwargs ):
  if database:
    # Bear in mind that compilation_info.compiler_flags_ does NOT return a
    # python list, but a "list-like" StringVec object
    compilation_info = GetCompilationInfoForFile( filename )
    if not compilation_info:
      return None

    final_flags = MakeRelativePathsInFlagsAbsolute(
      compilation_info.compiler_flags_,
      compilation_info.compiler_working_dir_ )

    # NOTE: This is just for YouCompleteMe; it's highly likely that your project
    # does NOT need to remove the stdlib flag. DO NOT USE THIS IN YOUR
    # ycm_extra_conf IF YOU'RE NOT 100% SURE YOU NEED IT.
    try:
      final_flags.remove( '-stdlib=libc++' )
    except ValueError:
      pass
  else:
    relative_to = DirectoryOfThisScript()
    final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to )

  return {
    'flags': final_flags,
    'do_cache': True
  }

rawDescription: YCM does not find my headers?

description: YCM does not find my headers


code:
import itertools

dimension1 = range(3)
dimension2 = ['a']
dimension3 = ['hello', 'world']

for res in itertools.product(dimension1, dimension2, dimension3):
    print(*res)

rawDescription: Classified permutations using itertools or numpy


code:
# place a cell at row zero, column zero, and
# set its state to "alive"
cell = Cell(canvas, 0, 0)
cell.set_state("alive")

rawDescription: Can rectangle be used as a parent class (tkinter)?


code:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'name_of_db',
        'USER': 'login_to_db',
        'PASSWORD': 'pass_to_db',
        'HOST': 'localhost',
        'PORT': '',
    }
}

rawDescription: How to integrate djangobb in an existing project?

description: Integrate djangobb in an existing project


rawDescription: declare multiple variables to same value

description: Declare multiple variables to same value


code:
def mute_error(f):
    def error_wrapper(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except:
            print('Connection Error')

    return error_wrapper

rawDescription: Catch ConnectionError with Django-Haystack and ElasticSearch


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


code:
for line in f:
    current_state, input_val, next_state = parseline(line)

def parseline(line):
    tokens = line.split(" ")
    return (int(tokens[0]), tokens[1], int(tokens[2]))

rawDescription: Python graceful fail on int() call?

description: Python graceful fail on int() call


rawDescription: Creating an alternating dictionary with a loop in Python


code:
relevant_items = ('bb', 'nw')
items = filter(lambda x: x[0] in relevant_items, c.most_common())

rawDescription: Python: Getting specific list elements

description: Python: Getting specific list elements


code:
root = tree.getroot()
root.attrib
root.nsmap

rawDescription: lxml ignoring elements with undefined namespace prefix

description: Lxml ignoring elements with undefined namespace prefix


rawDescription: Plotting surface of implicitly defined volume


code:
Output
C
None

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


code: input('hit enter to exit')

rawDescription: tkinter button to open new window and run script

description: Tkinter button to open new window and run script


code:
pat = '"Parcels \(.*\)"'
match = re.search(pat, t)
print(match.group())

rawDescription: Python look for pattern in string

description: Python look for pattern in string


code: return dict(dictionary)

rawDescription: Python coverting list to dictionary

description: Python coverting list to dictionary


code:
def process(sessions, user):
   ...

rawDescription: Access Shared DataFrame in Multiprocessing Map


code:
df = pd.DataFrame(np.random.rand(10**7, 5), columns=list('abcde'))
df.info()
df.shape

rawDescription: pandas df.loc[z,x]=y how to improve speed?

description: Pandas df.loc[z,x]=y how to improve speed


code: persons_by_id = dict((p.id, p) for p in persons)

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

description: Directly access class instances through class dictionary in Python


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


code:
class RegisteredNumber(int):

    numbers = []

    def __new__(cls,*args,**kwargs):
        self = int.__new__(cls,*args,**kwargs)
        self.numbers.append(self)
        return self

    def __add__(self,other):
        return RegisteredNumber(super().__add__(other))

c = RegisteredNumber(1) + 2

print(RegisteredNumber.numbers)

rawDescription: How to check if a function is pure in Python?

description: Check if a function is pure in Python


rawDescription: Prime number finder - optimization

description: Prime number finder - optimization


code:
from scapy.all import *

def pkt_callback(pkt):
    pkt.show() # debug statement

sniff(iface="<My Interface>", prn=pkt_callback, filter="tcp", store=0)

rawDescription: Scapy packet sniffer triggering an action up on each sniffed packet


code: subprocess.Popen(["mode", "con:", "cols=25", "lines=80"])

rawDescription: Set Console Width (Windows, Python)

description: Set Console Width (Windows, Python)


rawDescription: Is the pickling process deterministic?

description: Is the pickling process deterministic


code:
Pythonic
submodule.binsha = submodule.module().head.commit.binsha
repos.index.add([submodule])
repos.index.commit("updated submodule to 'wanted commit'")

rawDescription: GitPython: how to commit updated submodule


code:
def reinit(self, d):
    self.clear()
    OrderedDict.__init__(self, d)

rawDescription: OrderedDict reinitialisation: order is lost


code: ['', ' by Maersk', 'Maersk', ' from China', 'China', ' to England', 'England', '']

rawDescription: How do I combine these regular expressions to match the variations in this text?

description: Combine these regular expressions to match the variations in this text


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


code:
from collections import defaultdict

d = defaultdict(list)
for i in range(100):
    if not i % 4:
        d['Four'].append(i)

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


code:
import re

data = """<!--#include file="/var/www/localhost/index.html" set="one" reset="two" -->"""
pat = r'''^<!--#([a-z]+) ([a-z]+)="(.*?)" ((?:[a-z]+?=".+")+?) -->'''

result = re.match(pat, data)
result.groups()
('include', 'file', '/var/www/localhost/index.html', 'set="one" reset="two"')

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


code: import pdb; pdb.set_trace()

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


code:
class GroceryForm(forms.Form):
    grocery_type = forms.ChoiceField(choices=(('dairy', 'Dairy'),
                                              ('produce', 'Produce'),
                                              ('deli', 'Deli')))
    name = forms.CharField()

rawDescription: In Python Django, how do I assign a charfield to a column in SQL based on the user's selection from a combobox?


code: df = df.sort('date')

rawDescription: Find Unique Dates in Numpy Datetime Array


rawDescription: Modify csv files with Python

description: Modify csv files with Python


code:
def inv_mod_p(x):
    """
    Compute an inverse for x modulo p, assuming that x
    is not divisible by p.
    """
    if x % p == 0:
        raise ZeroDivisionError("Impossible inverse")
    return pow(x, p-2, p)

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


code:
def goat_door(guess, correct):
    return [random.choice(list({1,2,3} - set(gc)))
            for gc in zip(guess, correct)]

rawDescription: List comprehension to generate and then sample from array that in turn depends on values in another array (index dependent)


code:
d = {'C-STD-B&M-SUM:-1': 0, 'C-STD-B&M-SUM:-10': 4.520475, 'H-NSW-BAC-ART:-9': 0.33784000000000003, 'H-NSW-BAC-ART:0': 0, 'H-NSW-BAC-ENG:-59': 0.020309999999999998, 'H-NSW-BAC-ENG:-6': 0,}

def divide_dictionaries(somedict):
    out = {}
    for k,v in somedict.items():
        head, tail = k.split(":")
        subdict = out.setdefault(head, {})
        subdict[tail] = v
    return out

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


code:
from itertools import islice, izip
list(islice(izip(cycle(list2), cycle(list1)), 5))

rawDescription: Cyclic combination of two list of different length


code:
with open("in.txt") as f:
        r = csv.reader(f, quotechar="'", skipinitialspace=True)
        for row in r:
            print(row)

rawDescription: How to count everything in quotes as only one item

description: Count everything in quotes as only one item


code: products = {v.product_id: v for v in variants }

rawDescription: Python speed up list of dict iteration

description: Python speed up list of dict iteration


code:
df.set_index(['TimeStamp', 'Symbol']).sortlevel(0).to_panel()
panel = df.set_index(['TimeStamp', 'Symbol']).sortlevel(0).to_panel()
panel['Price']

rawDescription: Pandas DataFrame - desired index has duplicate values


code:
a = "blah\nCBD1WL1"
a.decode('utf-8').encode('utf-16')

rawDescription: How do I properly format this string in Python?

description: Properly format this string in Python


rawDescription: Writing clean code in beautifulsoup

description: Writing clean code in beautifulsoup


code:
import pandas as pd
import sklearn.linear_model as ll

data = pd.read_csv('data.csv', sep=';')
X = data.ix[:,1:3]
y = data.ix[:,0]

month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

for i, m in enumerate(data.ix[:,1]):
    data.ix[i,1] = month.index(m)

X = data.ix[:,1:3]
lr = ll.LinearRegression()
lr.fit(X, y)

######### TEST DATA ##########
X_test = [[1, 2008], [2, 2008]]
X_test = pd.DataFrame(X_test, columns=['Month', 'Year'])

y_test = lr.predict(X_test)
print(y_test)

rawDescription: simple prediction using Pearson correlation and linear regression with python

description: Simple prediction using Pearson correlation and linear regression with python


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

@app.route("/final/<result>")
def display_results(result):
    return render_template("results.html", result=result)

rawDescription: Routing view to another URL based on parameters


code:
from .packageA import * # Ensures that all the modules have been loaded in their new locations *first*.
from . import packageA  # imports WrapperPackage/packageA
import sys
sys.modules['packageA'] = packageA  # creates a packageA entry in sys.modules

rawDescription: Unpickling python objects with a changed module path


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

rawDescription: Map Function to Dictionary of Objects

description: Map Function to Dictionary of Objects


code:
from operator import itemgetter
tuples = [(1, 2), (3, 4, 1), (7, 5, 6, 9), (3,)]
sorted(tuples, key=lambda t: t[-1])
sorted(tuples, key=itemgetter(-1))
sorted(tuples, key=lambda t: t[::-1])
different_example = [(3, 4, 1), (1, 2), (3,), (7, 5, 2, 1)]
sorted(different_example, key=itemgetter(-1))
sorted(different_example, key=lambda t: t[::-1])

rawDescription: Sorting Tuples in a descending order based on the last item given in the tuple


rawDescription: Fitting piecewise function in Python

description: Fitting piecewise function in Python


rawDescription: Generating repetitive data in numpy / pandas in a fast vectorized way


code:
cur_column = 5
for line in Input:
    line = line.rstrip()
    fields = line.split("\t")
    for col in fields[cur_colum:]:
       ...
       ...

cur_column += 1 # done processing current column, increment value to next column

rawDescription: Python: Keep track of current column in text file


code: x = dummy(f(dummy(sin(dummy(dummy(x) + dummy(y))))))

rawDescription: How to step through Python expression evaluation process?

description: Step through Python expression evaluation process


code: z = arr[:, 5].sum()  # Sum up all values in column 5.

rawDescription: Sum one row of a NumPy array

description: Sum one row of a NumPy array


code: list(set(a) ^ set(b))

rawDescription: restoring list from unified_diff output

description: Restoring list from unified_diff output


code:
def modify_attrs(self, attrs):
    for attr in attrs:
        val = getattr(self, attr)
        setattr(self, attr, val*2)

...

bobinstance.modify_attrs(['lenname', 'lenshape'])

rawDescription: How to input a list of attributes into a function

description: Input a list of attributes into a function


code:
data = [["4","5"],["3","7"]]
search = "4"

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

rawDescription: Python Search within Lists within Lists

description: Python Search within Lists within Lists


code: conn = mysqldb_conn()

rawDescription: SQLAlchemy memory hog on select statement


code:
import re
pat = r'(?:by|for|from) <?([^\s;>]+)'
print(re.findall(pat, text))

rawDescription: Python: how best to combine two regex's into one pattern match?


code:
key = 'article:%s' % (self.url,)
if (self.redis.exists(key) and
        self.redis.hexists(key, 'id')):
    self.id = self.redis.hget(key, 'id')
else:
    self.id = self.redis.incr('articled')

rawDescription: Some advice on the style of different ways to limit line length to comply with PEP8


rawDescription: Iteratively copy specific rows from CSV file to new file


code:
by_index = ([sub_index, list_index] for list_index, list_item in
             enumerate(items) for sub_index in list_item[0])
[item[1] for item in sorted(by_index)]

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


code:
cursor.execute(
    "insert into Log(ComponentId, Value, TimeStamp) OUTPUT INSERTED.ID VALUES(8,?,?)",
    (value, TimeStamp))

rawDescription: String appending is acting really odd Python


code:
b = {"foo", "bar"}
b

rawDescription: Is there a Python dict without values?

description: Is there a Python dict without values


code:
thing = ['Chrom1', '10000', '10600']
c, start, stop = thing
c
start, stop

rawDescription: Writing python chunking loops with reference to another txt


code:
PATTERN_ONE_ARG_OR_KWARG   = """power< 'func' trailer< '(' not(arglist) obj1=any                         ')' > >"""
PATTERN_ONE_ARG            = """power< 'func' trailer< '(' not(arglist | argument<any '=' any>) obj1=any ')' > >"""
PATTERN_ONE_KWARG          = """power< 'func' trailer< '(' obj1=argument< any '=' any >                  ')' > >"""
PATTERN_TWO_ARGS_OR_KWARGS = """power< 'func' trailer< '(' arglist< obj1=any ',' obj2=any >              ')' > >"""

rawDescription: pattern to match 1-or-2-arg function call for lib2to3

description: Pattern to match 1-or-2-arg function call for lib2to3


code:
from selenium.webdriver.support import expected_conditions as EC

class wait_for_class(object):
    def __init__(self, locator, class_name):
        self.locator = locator
        self.class_name = class_name

    def __call__(self, driver):
        try:
            element_class = EC._find_element(driver, self.locator).get_attribute('class')
            return element_class and self.class_name in element_class
        except StaleElementReferenceException:
            return False

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

description: Wait until an element gains or loses a class


code: self.ILCheck = SmartBool()

rawDescription: Python2 PyQt4 Connect a bool Variable to a QCheckBox item


code:
x = 1.1
id(x)
y = x
id(y)
y += 1
id(y)
id(x)

rawDescription: In Python, why doesn't 'y = x; y += 1' also increment x?


code:
for group in grouper(message, n):
    # matrix multiplication
    for row in key:
        sum_prod = 0
        for a, b in zip(group, row):
            sum_prod += a*b
        #print(group, row, sum_prod, sum_prod % 26)
        result.append(sum_prod)
        #result.append(sum_prod % 26)

rawDescription: 3x1 Matrix Multiplication with lists[UPDATED]


rawDescription: Matching 2 regular expressions in Python


code: p2 = Popen(cmd2, stdin=p1.stdout, stdout=PIPE, stderr=devnull, preexec_fn=p1.stdin.close)

rawDescription: blocks - send input to python subprocess pipeline

description: Blocks - send input to python subprocess pipeline


code:
def adjust():
    user = g.user
    form = AdjustPWMForm()
    if request.method == 'GET':
        form.dutyCycle.data = 55
    if form.validate_on_submit():
        dutyCycle = form.dutyCycle.data
        print('result %s', dutyCycle)
        return redirect(url_for('statusPage'))
    return render_template('adjust.html', title='Adjust PWM', user=user, form=form)

rawDescription: Prepopulate Flask-WTForm IntegerField

description: Prepopulate Flask-WTForm IntegerField


code: sum(samples[i-j] for j in range(n))

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


code:
functions = {0: reference_to_function_1, 1: reference_to_function_2}

def wrapper(index):
    functions[index]()

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


rawDescription: Load JPEG from URL to skimage without temporary file


rawDescription: Replace a blank space followed by text with a blank space using string replace


code:
ifilter(conjoined(lambda x: x not in block_list, lambda x: x in accept_list),
        read_records(filename))

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


code:
Xout = numpy.linspace(1,10,10)
Yout = numpy.linspace(1,10,10)

rawDescription: How to plot contours from multidimensional data in MatPlotLib (NumPy)?

description: Plot contours from multidimensional data in MatPlotLib (NumPy)


rawDescription: Binning variable length lists in python

description: Binning variable length lists in python


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

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


code:
from flask import jsonify

@app.route("/example_array/")
def example():
    list = get_list() # however you get your list data, put it here
    return jsonify(array=list)

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

rawDescription: How to access an array (JSON) in the front-end JavaScript that was passed by Python (Flask)?

description: Access an array (JSON) in the front-end JavaScript that was passed by Python (Flask)


code:
import logging

class ContextFilter(logging.Filter):
    def filter(self, record):
        record.count = counter
        return True

logging.basicConfig(
    level = logging.DEBUG,
    format = '%(levelname)-8s: %(count)s: %(message)s')
logger = logging.getLogger(__name__)
logger.addFilter(ContextFilter())

counter = 5
logger.debug('First Event')
counter += 2
logger.warning('Second Event')

rawDescription: Pass a counter to every python logging method


code:
from jellyfish import jaro_distance
import numpy
def distance(i, j):
    return 1 - jaro_distance(feature_dict[i], feature_dict[j])

feature_dict = 'CHEESE CHORES GEESE GLOVES'.split()

funcProxy = np.vectorize(distance)

distance_matrix = np.fromfunction(funcProxy, shape=(len(feature_dict),len(feature_dict)))

rawDescription: Numpy - constructing matrix of Jaro (or Levenshtein) distances using numpy.fromfunction


code:
array_np = numpy.asarray(array)
low_values_indices = array_np < lowValY  # Where values are low
array_np[low_values_indices] = 0  # All low values set to 0

rawDescription: Fastest way to zero out low values in array?


code:
def plot_multi_y(x, ys, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()
    return [ax.plot(x, y, **kwargs)[0] for y in ys]

def update_multi_y(line_objects, x, ys):
    for y, line_object in zip(ys, line_objects):
        line_object.set_xdata(x)
        line_object.set_ydata(y)

rawDescription: Drawing dynamically n plots

description: Drawing dynamically n plots


code:
from itertools import zip_longest
[i for i,j in izip_longest(a,b) if i!=j]

rawDescription: Python - eliminating common elements from two lists


code: [mydict[key]**exp[key] for key in mydict.keys()]

rawDescription: Fastest Way to Multiply Dictionary Values and Output to 'list type'


code: df.filter(['ticker', 'date', 'value'])

rawDescription: Computing diffs within groups of a dataframe


code: df.loc[g[col].transform(lambda x: len(x) < 10).astype(bool), col] = 'RARE_VALUE'

rawDescription: Replace rarely occurring values in a pandas dataframe


code:
import json
js=json.dumps(a.tolist())
js
np.array(json.loads(js))

rawDescription: how to read numpy 2D array from string?

description: Read numpy 2D array from string


code:
proxy_sem = Semaphore(value=5) # 5 connections will be able to hold this semaphore concurrently
global_sem = Semaphore(value=15) # 15 connections will be able to hold this semaphore

rawDescription: Acquiring first available lock/semaphore on python asyncio


code:
example = ['a', 'b', 'c']
"'{joined}'".format(joined="', '".join(example))

rawDescription: Need to join the elements of a list but keep the '' around element after joining


code:
class Contact(object):

    ...

    @classmethod
    def from_input(cls):
        firstName = input("First Name: ")
        lastName = input("Last Name: ")
        address = input("Address: ")
        telephone = input("Telephone: ")
        mobile = input("Mobile: ")
        email = input("Email: ")
        return cls(firstName, lastName, address, None,
                   telephone, mobile, email, None)

rawDescription: Python - When to create a Class and when to create a Function


code:
import pandas as pd
import io
import numpy as np
import datetime

data = """
   c0   c1   c2   c3   c4  c5
0  1    a    d    3    4   0
1  1    a    c    0    0   6
2  1    b    d    3    1   0
1  1    b    c    0    0   1
    """

df = pd.read_csv(io.StringIO(data), delimiter='\s+')

df2 = pd.DataFrame(df.groupby('c1').sum().ix[:,1:].sum(axis=1), columns=['c6']).reset_index()

df3 = pd.merge(df,df2,on='c1').set_index(df.index)

print(df3)

rawDescription: How to aggregate some rows based on their column value in Python

description: Aggregate some rows based on their column value in Python


code: j = randint(0, i - 1)

rawDescription: oneliner scramble program

description: Oneliner scramble program


code:
def __init__(self, *args, **kwargs):
        super(CommentForm, self).__init__(*args, **kwargs)

        self.fields['categories'].initial = self.instance.object_id

rawDescription: ModelChoiceField initial value in change form


code:
def child(self):
    "Return the child of this protocol layer"
    return self.__child

def parent(self):
    "Return the parent of this protocol layer"
    return self.__parent

rawDescription: Packet sniffer in python using pcapy impacket


code:
for i, im in enumerate(vid):
    print('Mean of frame %i is %1.1f' % (i, im.mean()))

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

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


code:
x = fmin_slsqp(f1, (5,45), f_eqcons=h, f_ieqcons=g)
print(x)

rawDescription: Weight Middle Range for use of scipy.optimize.linprog (Simplex algorithm)


code:
def BVRedAnd(a):
    return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)

rawDescription: How do I encode bv-redand using the z3 Python API?

description: Encode bv-redand using the z3 Python API


code:
import pandas as pd
import numpy as np
import random
import string

df = pd.DataFrame(data={'NAME': [''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(17)) for _ in range(10)],
            'Date': pd.date_range('1/01/2016', periods=10),
            'Whatever': np.random.randint(20, 50, 10)},
                  columns=['NAME', 'Date', 'Whatever']).set_index(['NAME', 'Date'])

random_df = df[df.index.get_loc(np.random.choice(df.index.levels[0])) == True].sort_index(level=1)
print(random_df)

rawDescription: how to get a random sample in a multiindex pandas dataframe?

description: Get a random sample in a multiindex pandas dataframe


code:
pixelR = pixelR[0]
pixelG = pixelValueTuple[1]
pixelB = pixelValueTuple[2]

rawDescription: How do I change each pixel

description: Change each pixel


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


rawDescription: Django queries: how to make contains OR not_contains queries


code:
from circuits.web import Controller, Server

class Root(Controller):

    def index(self):
        return "Hello World!"

Server(("0.0.0.0", 8000)).register(app)

rawDescription: Monitoring output of parallel subprocess in python 2.7 - pocketsphinx


code:
config = tf.ConfigProto(allow_soft_placement=True)
sess = tf.Session(config=config)

rawDescription: Is it possible to split a network across multiple GPUs in tensorflow?


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

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


code:
class Circle(Shape):
    def __init__(self, height, foo_args, shape='circle'):
        Shape.__init__(self, shape, height) # assigns the attributes there
        # other assignments
    @property
    def diameter(self):
        """The diameter property maps everything to the height attribute."""
        return self.height
    @diameter.setter
    def diameter(self, new_value):
        self.height = new_value
    # deleter is not needed, as we don't want to delete this.

rawDescription: child class attribute different name

description: Child class attribute different name


code:
import re
regex, phrases = (r'why (.*) i (.*)\?',
( r'You \g<1> \g<2>?',
  r'Perhaps you only think you \g<1> \g<2>.'))
phrase1, phrase2 = phrases
re.sub(regex, phrase1, 'why am i dumb?')
re.sub(regex, phrase2, 'why am i dumb?')

rawDescription: Explain what this is for me?

description: Explain what this is for me


code:
def gen_probes(hashvalue, n):
    'Same sequence of probes used in the current dictionary design'
    mask = n - 1
    PERTURB_SHIFT = 5
    if hashvalue < 0:
        hashvalue = -hashvalue
    i = hashvalue & mask
    yield i
    perturb = hashvalue
    while True:
        i = (5 * i + perturb + 1) & 0xFFFFFFFFFFFFFFFF
        yield i & mask
        perturb >>= PERTURB_SHIFT

rawDescription: How is the return value of __hash__ used?


code: any(e in stringB for e in listA)

rawDescription: How to check if any item in a list occurs in another list?

description: Check if any item in a list occurs in another list


code:
from nltk.stem.wordnet import WordNetLemmatizer
lmtzr = WordNetLemmatizer()
lmtzr.lemmatize('dance')
lmtzr.lemmatize('dancer')
lmtzr.lemmatize('dancing')
lmtzr.lemmatize('dances')
lmtzr.lemmatize('danced')

rawDescription: Probability count/frequency of related words?


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

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


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


code:
for k in mydict.keys():
   if k == 'two':
       del mydict[k]
mydict

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

description: Delete items from a dictionary while iterating over it


code:
for product, ingred_list in ConsomRatio.items():
    for iname, ivalue in ingred_list.items():
        print('To produce {to_produce} we need {amount} of {ingredience}'
              .format(to_produce=product, ingredience=iname,
                      amount=ivalue))

rawDescription: Dicts in Python

description: Dicts in Python


code: fractExpr = fraction | number + Optional(fraction)

rawDescription: How can fractional number expressions be parsed using pyparsing?


code:
def mp(SNR2, *events):
    ...
    return np.asarray([np.array[[I for event in events[i]]] for i in range(len(events))]).reshape(events.shape)

rawDescription: Syntax Error in function definition

description: Syntax Error in function definition


code:
from email.mime.multipart import MIMEMultipart
msg=MIMEMultipart('mixed')
msg['To']='test'
msg.replace_header('To', 'test2')
print(msg)

rawDescription: How to change attribute of MIMEMultipart object?

description: Change attribute of MIMEMultipart object


code: ('b time', 'c crime')

rawDescription: Comparing values of list of tuples, current and next


rawDescription: How to retrieve the array elements in a tuple in numpy

description: Retrieve the array elements in a tuple in numpy


code:
@Composable
def sub3(n):
    return n - 3

@Composable
def square(n):
    return n * n

rawDescription: How to multiply functions in python?

description: Multiply functions in python


rawDescription: Listing blog entries by year,month

description: Listing blog entries by year,month


rawDescription: Chained Method Calls in Python with dict


code:
cursor = conn.cursor ()
cursor.execute ("DROP TABLE IF EXISTS data_table")
cursor.execute ("""
    CREATE TABLE data_table(
        value     CHAR(80)
    )
""")

cursor.execute (""" INSERT INTO data_table (value) VALUES ('%s')""" % [0, 0])
conn.commit()

for i, x in enumerate(data):    # i is index, x is data[i]
    for s in range(target_sum + 1): #set the range of one higher than sum to include sum itself
        for c in range(s / x + 1):
            cursor.execute(""" SELECT value FROM data_table WHERE value='%s' """ % ([s - c * x, i]))
            if cursor.rowcount == 1:
                cursor.execute(""" SELECT value FROM data_table WHERE value='%s' """ % [s, i+1])
                if cursor.rowcount == 0:
                    cursor.execute (""" INSERT INTO data_table (value) VALUES ('%s')""" % [s, i+1])
    conn.commit()

rawDescription: Results are different between python and mysql for similar command


rawDescription: Not finding the strings expected with pyparsing


rawDescription: Increment given indices in a matrix

description: Increment given indices in a matrix


code:
P_projected = P_centered.dot(np.linalg.pinv(
             Ax_direction[np.newaxis, :])).dot(Ax_direction[np.newaxis, :])

rawDescription: Finding the distance of points to an axis


code:
sequence_of_sentences = ['This is a sentence', 'This is another sentence']
from collections import Counter
counts = Counter()
for sentence in sequence_of_sentences:
    counts.update(word.strip('.,?!"\'').lower() for word in sentence.split())

counts
counts['sentence']

rawDescription: Count word occurrence in a list of strings


rawDescription: python datetime.time operation

description: Python datetime.time operation


code: parser.add_argument('patterns', type=str, nargs='+', help='Pattern(s) for pgrepping')

rawDescription: Take multiple patterns from cli. argparse Python3


code:
itemObject = self.myCboBox.GetClientData(self.myCboBox.GetSelection())
itemID = itemObject.id

rawDescription: How can I store objects other than strings in a wxPython ComboBox?

description: Store objects other than strings in a wxPython ComboBox


code:
for k,v in sorted(class1.items(), key=lambda p:p[1]):
    print(k,v)
for k,v in sorted(class1.items(), key=lambda p:p[1], reverse=True):
    print(k,v)

rawDescription: How do I print a sorted Dictionary in Python 3.4.3

description: Print a sorted Dictionary in Python 3.4.3


rawDescription: Numpy: Sorting a multidimensional array by a multidimensional array


code:
res = pd.concat([df.iloc[i] for val, i in g.groups.items() for v in val.split(',')], ignore_index=True)
res['RevID'] = sum([val.split(',') for val in g.groups], [])

rawDescription: Merging Dataframes with Arrays?

description: Merging Dataframes with Arrays


code:
import dis
def olddivision(x, y): return x / y

dis.dis(olddivision)
from __future__ import division
def newdivision(x, y): return x / y

dis.dis(newdivision)

rawDescription: Why do I lose precision while multiplying and dividing whole ints?


code:
from os import path
from sys import argv
import csv

INIT = 'def __init__'

def csvformat(csvpath):
    """ Read a csv file containing a class name and attrs.

    Returns a list of the form [['ClassName', {'attr':'val'}]].
    """
    csv_lines = []
    with open(csvpath) as f:
        reader = csv.reader(f)
        _ = [csv_lines.append(line)
                for line in reader]
    result = []
    for line in csv_lines:
        attr_dict = {}
        attrs = line[1:]
        last_attr = attrs[0]
        for attr in attrs[1:]:
            if last_attr:
                attr_dict[last_attr] = attr
                last_attr = ''
            else:
                last_attr = attr
        result.append([line[0], attr_dict])
    return result

def attr_template(attrs):
    """ Format a list of default attribute setting code. """
    attr_list = []
    for attr, val in attrs.items():
        attr_list.append(str.format('    if {} is None:\n', attr, val))
        attr_list.append(str.format('      self.{} = {}\n', attr, val))
        attr_list.append('    else:\n')
        attr_list.append(str.format('      self.{} = {}\n', attr, attr))
    return attr_list

def import_template(imports):
    """ Import superclasses.

    Assumes the .py files are named based on the lowercased class name.
    """
    imp_lines = []
    for imp in imports:
        imp_lines.append(str.format('from {} import {}\n',
            imp.lower(), imp))
    return imp_lines

def init_template(attrs):
    """ Template a series of optional arguments based on a dict of attrs.
    """
    init_string = 'self'
    for key in attrs:
        init_string += str.format(', {}=None', key)
    return init_string

def gen_code(foldername, superclass, name, attrs):
    """ Generate python code in foldername.

    Uses superclass for the superclass, name for the class name,
    and attrs as a dict of {attr:val} for the generated class.

    Writes to a file with lowercased name as the name of the class.
    """
    imports = [superclass]
    pathname = path.join(foldername, name.lower() + '.py')
    with open(pathname, 'w') as pyfile:
        _ = [pyfile.write(imp)
                for imp
                in import_template(imports)]
        pyfile.write('\n')
        pyfile.write((str.format('class {}({}):\n', name, superclass)))
        pyfile.write((str.format('  {}({}):\n',
            INIT, init_template(attrs))))
        _ = [pyfile.write(attribute)
                for attribute
                in attr_template(attrs)]
        pyfile.write('    super().__init__()')

def read_and_generate(csvpath, foldername, superclass):
    class_info = csvformat(csvpath)
    for line in class_info:
        gen_code(foldername, superclass, *line)

def main():
    read_and_generate(argv[1], argv[2], argv[3])

if __name__ == "__main__":
    main()

rawDescription: How to dynamically create new python class files?

description: Dynamically create new python class files


code:
import gc, shiboken

def wrapper_from_address(address):
    for item in gc.get_objects():
        try:
            if address == shiboken.getCppPointer(item)[0]:
                return item
        except TypeError:
            pass

rawDescription: Warning seems to point to a different object address


rawDescription: python how to extract a number from a variable

description: Python how to extract a number from a variable


rawDescription: python: regex only gets the last occurrence

description: Python: regex only gets the last occurrence


code:
distance=[[[0]*n]*n]*n
pprint.pprint(distance)
distance[0][0][0] = 1
pprint.pprint(distance)

rawDescription: Create 3D array using Python

description: Create 3D array using Python


code: literal_eval("{'key': 10}")

rawDescription: Converting ConfigParser values to python data types


code:
import urllib
login_data=urllib.urlencode({'username':'your username','password':'your password','submit':'Login'}) # replace username and password with filed name
op = urllib.urlopen('www.exmaple.com/sign-in.php',login_data)

rawDescription: Login using Python in basic HTML form

description: Login using Python in basic HTML form