code:
from twisted.internet.task import LoopingCall

class Client(object):

    def __init__(self):
        self.line = 'no message'
        pygame.init()
        self.screen = pygame.display.set_mode((200, 200))

    def new_line(self, line):
        self.line = line

    def tick(self):
        self.screen.fill((0,0,0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                reactor.stop() # just stop somehow
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                reactor.stop() # just stop somehow
        self.screen.blit(pygame.font.SysFont('mono', 12, bold=True).render(self.line, True, (0, 255, 0)), (20,20))
        pygame.display.flip()

if __name__ == '__main__':
    c = Client()

    lc = LoopingCall(c.tick)
    lc.start(0.1)
    reactor.connectTCP('127.0.0.1',6000, ChatClient(c.new_line))
    reactor.run()

rawDescription: Twisted clients within pygame mainloop?

description: Twisted clients within pygame mainloop


code:
from nose.tools import *

foo = None

def setup():
    global foo  # Ugly.
    foo = 10

def teardown():
    global foo  # Ugly.
    foo = None

@with_setup(setup, teardown)
def test_foo_value():
    assert_equal(foo, 10)

rawDescription: How can I access variables set in the python nosetests setup function

description: Access variables set in the python nosetests setup function


rawDescription: Python/Xpath convert query

description: Python/Xpath convert query


code:
from datetime import timedelta

yesterday_midnight = midnight - timedelta(days=1)

rawDescription: What was midnight yesterday as an epoch time?


code: output = ''.join([x[0] for x in phrase.split()])[:3]

rawDescription: using find in python

description: Using find in python


code: r, g, b = (min(255, max(0, c)) for c in (r, g, b))

rawDescription: Limiting a number to a range

description: Limiting a number to a range


rawDescription: How to get part of string and pass it to other function in python?

description: Get part of string and pass it to other function in python


code:
indices = np.arange(25, dtype=int)
np.unravel_index(indices, (5, 5))

rawDescription: How to find the indices of a vectorised matrix numpy

description: Find the indices of a vectorised matrix numpy


code:
'BBB' in item_dict # True
'BB' in item_dict # False

rawDescription: Find an entry in a list based on a partial string


code: items = listWidget.selectedItems()

rawDescription: How to Disable and Enable selection for a item in QListWideget using Python


rawDescription: Passing a list to numpy.ix_, or how to slice a multidimensional array, when number of dimensions and selection criteria are not known beforehand?


code: min(range(len(v)), key=v.__getitem__)

rawDescription: Min index built-in function

description: Min index built-in function


code: Scrollbar(window, orient="vertical")

rawDescription: Python Tkinter: Attach scrollbar to listbox as opposed to window


code:
request = datastore.LookupRequest()
request.key.extend(list_of_keys)
response = datastore.lookup(request)

rawDescription: Is it possible to query multiple datastore keys in single query?


rawDescription: Python: output for recursively printing out files and folders


code:
group_id = 123
group = session.query(Group).get(group_id)
print(group.toys)

rawDescription: SQLAlchemy chaining association proxy for great grandchildren?


rawDescription: Add a list of lists to a list of lists with a list comprehension


code:
rootnode = TreeNode('rootnode')
# assign "children" attribute straight away:
node1 = TreeNode('node1',
    children=[TreeNode('node1.child1'), TreeNode('node1.child2')]
    )
# or just manipulate as any regular list
rootnode.children.append(node1)

rawDescription: How do you add a child node to a parent in an adjacency list in sqlalchemy?

description: Add a child node to a parent in an adjacency list in sqlalchemy


code:
def remove_zeros(a):
    return float("0." + str(long(str(1+a)[2:])))

rawDescription: Faster way to shift a decimal in Python to remove zeros?


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

# Fake data
x=np.arange(0,5,1)
y=np.ones(x.shape)
yerr = np.ones(x.shape)/4.

# Create figure
fig,ax = plt.subplots(1)

# Set some limits
ax.set_xlim(-1,5)
ax.set_ylim(-2,4)

# Plot errorbars with the line color you want
ax.errorbar(x,y,yerr, fmt='o',color='r',capthick=2,elinewidth=2,capsize=3,zorder=10)

# Plot black errorbars behind (lower zorder) with a wider line and cap thinkness
ax.errorbar(x,y,yerr, fmt='o',color='k',capthick=4,elinewidth=4,capsize=4,zorder=5)

plt.show()

rawDescription: Border on errorbars in matplotlib/python


rawDescription: Regex to match MAC address and also extract it's values


rawDescription: How do I use Regexp Tagger in nltk?

description: Use Regexp Tagger in nltk


code:
from dateutil import parser
dt = parser.parse('Wed Apr 24 14:39:49 CEST 2013')

rawDescription: PYTHON (Jython) how to get DATE TIME value in string - all before specific string?


code:
def categories_view(request):
    categories = Categories.objects.all()   #maybe put an order_by or filter here
    return render_to_response("your_template.html", {'categories':categories})

rawDescription: Traversing multi-dimensional dictionary in django


code:
class Devices(dict):
    def __init__(self,inpt={}):
        super(Devices,self).__init__(inpt)

    def __getattr__(self, name):
        return self.__getitem__(name)

    def __setattr__(self,name,value):
        self.__setitem__(name,value)

rawDescription: Python override dictionary access methods


rawDescription: Convert a string containing a roman numeral to integer equivalent


code:
class bar(object):
    def __init__(self,dimnames):
        self.dd = {n:i for i,n in enumerate(dimnames)}
    def __call__(self,*args):
        return [self.dd[x] for x in args]
    def __getitem__(self,key):
        return self.dd[key]
d0, d1 = bar(['x','y','z']), bar(['a','b','c'])
A[d0('x','z'),slice(*d1('a','c'))]

rawDescription: python tensors with named field access

description: Python tensors with named field access


code:
stepregistry = portal.portal_setup.getImportStepRegistry()
stepregistry.listSteps()

rawDescription: Is there a good reference list for the names of the genericsetup import steps


code:
import timeit
from random import randint
rand_list = [randint(0,10) for i in range(0,10000)]
timeit.Timer('list(set(rand_list))', setup='from __main__ import rand_list').repeat(5, 1000)
timeit.Timer('dict.fromkeys(rand_list).keys()', setup='from __main__ import rand_list').repeat(5, 1000)

rawDescription: Why is list+set method of making a list unique faster than dictionary keys method?


rawDescription: Create docx via python (page breaks, tables) - possible?


code:
from bottle import Bottle
import functools

app = Bottle()

# take a param from the URI
@app.route('/hello1/<param>')
def hello1(param):
    return ['this function takes 1 param: {}'.format(param)]

# "bake" in a param value at route definition time
hello2 = functools.partial(hello1, param='the_value')
app.route('/hello2', ['GET'], hello2)

app.run(host='0.0.0.0', port=8080)

rawDescription: Python bottle: how to pass parameters into function handler


code:
if var in ('stringone', 'stringtwo'):
    dosomething()

rawDescription: Python: How to check if a variable is equal to one string or another string


code:
ertag = child.find("error")
cdatatext = ertag.text
print(cdatatext)

rawDescription: Get CDATA using xml.etree.ElementTree

description: Get CDATA using xml.etree.ElementTree


code:
from datetime import datetime
dates = ['2011-06-18', 'Date', '2010-01-13', '1997-12-01', '2007-08-11']
my_dates = [datetime.strptime(d, '%Y-%m-%d').date()
            for d in dates
            if d != 'Date']
my_dates.sort()

rawDescription: How do I perform math operations on dates and sort them in Python?

description: Perform math operations on dates and sort them in Python


code:
final_list = [os.path.join(root,dir) for
    root,dirs,files in os.walk("path/to/tree") for
    dir in dirs if dir=="arc"]

rawDescription: find folders in a tree and create a list with their paths

description: Find folders in a tree and create a list with their paths


rawDescription: BASE_DIR output within a subfolder, DJANGO


code:
class Summer(object):
    def __init__(self, x0=0):
        self.value = x0

    def add(self, x):
        self.value += x

class SquareSummer(Summer):
    def add(self, x):
        super(SquareSummer, self).add(x ** 2)

class Maxer(object):
    def __init__(self, x0):
        self.value = x0

    def add(self, x):
        self.value = max(self.value, x)

# example usage: collect([Maxer, Summer], iterable)
def collect(collectors, it):
    it = iter(it)

    x0 = next(it)
    collectors = [c(x0) for c in collectors]

    for x in it:
        for c in collectors:
            c.add(x)

    return [c.value for c in collectors]

rawDescription: Computing stats on generators in single pass. Python


rawDescription: Python: PyQt QTreeview example - selection


rawDescription: Select multiple groups from pandas groupby object


code:
def myfunc():
  return "myvalue"
type(myfunc)
myfunc()
myfunc.__call__()

rawDescription: What method attributes are used in Django?


code: name = s[s.index(' by ')+4:s.index(' to /r/books')]

rawDescription: Removing a certain part of a string in python


code:
class DefaultConfig(object):
  PROJECT_NAME = 'my project'

class TestingConfig(DefaultConfig):
  TESTING = True

class DevConfig(DefaultConfig):
  DEBUG = True

configurations = {
  'testing': TestingConfig,
  'dev': DevConfig,
  'default': DefaultConfig
}

rawDescription: Flask: are blueprints necessary for app factories?


code: a = b = None

rawDescription: Unpack assignment vs chained assignment

description: Unpack assignment vs chained assignment


rawDescription: Extracting required indices from the array of tuples


code: section[:] = 0

rawDescription: Slice numpy matrix using vectors as indices


code: item["code"] = "%s-%s-%s" % (item["country"], item["region"], item["location"])

rawDescription: concatenating scraped data in scrapy

description: Concatenating scraped data in scrapy


rawDescription: Sorting a list of tuples, where each tuple consists of a string and a set


code: soup.find_all('div', {'data-text': lambda value: value.startswith('bitcoin:')})

rawDescription: Parsing bitcoin address in html

description: Parsing bitcoin address in html


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


code:
class Player(object):
    identifier = 0
    def __init__(self,name, level=""):
        self.name = name
        self.level =level
        # identifier belong to the class not an instance of it!
        # change in Group as well!
        self.identifier == Player.identifier
        Player.identifier += 1
        if(len(self.name) < 1): # can be 'if not self.name'
            raise ValueError("Name.__init__:  is empty")

        if(self.identifier>=99):
            raise ValueError("Identifier.__init__:  exceeds 99")

rawDescription: Adding an object of one class to an object of another class and checking for duplicates in Python


code:
test = __import__('urllib2',globals(),locals())
cls = None
if 'Request' in dir(test):
    cls = test.__dict__['Request']
    # you found the class now you can use it!
    cls('http://test.com')

rawDescription: Importing everything ( * ) dynamically from a module


rawDescription: Python: print unicode string stored as a variable


code:
import sys

if sys.byteorder == 'big':
    # data was written in little-endian form, so swap the bytes to match
    data.byteswap()

rawDescription: Interpreting binary files as ASCII

description: Interpreting binary files as ASCII


code: df = df[ordered_column_list]

rawDescription: Creating new dataframe columns from existing dataframe column names


code:
for excluded in excludeList:
    kolaDataList = [l for l in kolaDataList if excluded not in l]

rawDescription: not in as a function in filter-function

description: Not in as a function in filter-function


code:
dwg = svgwrite.Drawing('myDrawing.svg', size=('170mm', '130mm'), viewBox=('0 0 170 130'))

dwg.add(dwg.line(start=(30, 30), end=(50,50)))

dwg.save()

rawDescription: Setting default units in svg (Python svgwrite)


code:
x = x.values
y = y.values

rawDescription: Using groupby on a function

description: Using groupby on a function


code:
s = b'GATC'
s
s.decode() # default UTF-8 decoding.
s.decode('ascii')

rawDescription: Python 3.4 dictionary output different from python 2.7


rawDescription: Pandas merging data from specific column


code:
{u'name': u'bedroom'}
{u'name': u'kitchen'}
{u'1': None, u'2': None}
None

rawDescription: Deserialize JSON to Object

description: Deserialize JSON to Object


code: srctxt = io.TextIOWrapper(src)

rawDescription: Text mode adapter for binary (or text) mode file


code:
x = np.arange(time.size) # = array([0, 1, 2, ..., 3598, 3599, 3600])
fit = np.polyfit(x, df['data'], 1)
fit_fn = np.poly1d(fit)

rawDescription: Linear regression with panda time series


rawDescription: how to pickle customized vectorizer?

description: Pickle customized vectorizer


code:
@login_required
def show_info(request):
    r = my_api_view(request)
    return HttpResponse(r.json())

rawDescription: Alternative of Requests in django

description: Alternative of Requests in django


rawDescription: manipulating list items python

description: Manipulating list items python


code:
i = ["user_arr", 100, True]
o = {i[0]: prev_def_func(*i[1:])}
print(o["user_arr"])

rawDescription: Unpack a list so the first element is assigned the result of a function operated on the following elements


code: numpy.mean(samples, axis=0)

rawDescription: randomly select multichoice options

description: Randomly select multichoice options


code:
import matplotlib.pyplot as plt
from matplotlib.dates import AutoDateFormatter, AutoDateLocator

xtick_locator = AutoDateLocator()
xtick_formatter = AutoDateFormatter(xtick_locator)

ax = plt.axes()
ax.xaxis.set_major_locator(xtick_locator)
ax.xaxis.set_major_formatter(xtick_formatter)

rawDescription: Add date tickers to a matplotlib/python chart


rawDescription: Why does the "is" keyword have a different behavior when there is a dot in the string?


code:
#  Second list element of first top-level list element
ll[[1]][[2]]
#[1] 4

#  First list element of third top-level list element
ll[[3]][[1]]
#[1] 42 11

rawDescription: How to set-up this Python data structure in R

description: Set-up this Python data structure in R


rawDescription: How to split a character in list and must still exist in python?

description: Split a character in list and must still exist in python


code:
['headers']

['origin', 'accept-encoding', 'accept-language', 'upgrade-insecure-requests', 'user-agent', 'content-type', 'accept', 'cache-control', 'referer', 'connection', 'alexatoolbar-alx_ns_ph']

'http://www.flyscoot.com'
'gzip, deflate'
'en-US,en;q=0.8'
'1'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36'
'application/x-www-form-urlencoded'
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
'max-age=0'
'http://www.flyscoot.com/index.php/en/'
'keep-alive'
'AlexaToolbar/alxg-3.3'

rawDescription: How could I extract the lengthy config from my controller/main code


code:
word_equivs = {}

for equiv in EQUIVALENCES:
    for word in equiv:
        word_equivs[word] = equiv

rawDescription: a slightly different string equivalence function in python

description: A slightly different string equivalence function in python


code:
from astropy.io import ascii
# Give names for ALL of the columns, as there is no easy way to skip columns
# for a table with no column header.
colnames = ('sn', 'gal_name1', 'gal_name2', 'year', 'month', 'day', ...)
table = ascii.read('sn_full.txt', Reader=ascii.NoHeader, names=colnames)

rawDescription: Adding names and assigning data types to ASCII data


code:
import wx

class Frame(wx.Frame):

    def __init__(self,parent,id):
        self.headr(parent,id)

    def headr(self,parent,id):
        wx.Frame.__init__(self,parent,id, 'My Program', size =(300,300))
        panel=wx.Panel(self)
        status = self.CreateStatusBar()

        uploadButton = wx.Button(panel,label="Upload",pos=(20, 30))
        uploadButton.Bind(wx.EVT_BUTTON,self.printIt)

    def printIt(self, event):
        print("Function has run")

if __name__== '__main__':
    app=wx.App()
    frame = Frame(parent=None,id=1)
    frame.Show()
    app.MainLoop()

rawDescription: wxpython button event running before click

description: Wxpython button event running before click


code:
try:
    conn.execute("""INSERT INTO users (username, email)
                    VALUES ("Alice", "alice@wonderland.com");""")
except sqlite3.IntegrityError:
    print ("Username 'Alice' was already taken.")

rawDescription: SQLite / Python database retrieval and comparison


code: DataFrame({'count' : df1.groupby( [ "Name", "City"] ).size()}).reset_index()

rawDescription: Converting a Pandas GroupBy object to DataFrame


code:
tickers = data4['AcquirorTickerSymbol'].unique()
min_date = data4['dater2'].min()
stock_df = pd.concat(dfs, ignore_index=True)

rawDescription: Python: Pandas: Speeding up an Apply Function


code:
from itertools import chain, izip
list(chain.from_iterable(izip(list_a, list_b)))

rawDescription: Interleaving Lists in Python

description: Interleaving Lists in Python


code:
molecule2atom = Table(
  'molecule2atom',
  Base.metadata,
  Column('molecule_db', Integer),
  Column('molecule_id', Integer),
  Column('atom_id', Integer, ForeignKey('atom.id')),
  ForeignKeyConstraint(
    ('molecule_db', 'molecule_id'),
    ('molecule.db', 'molecule.id')  ),
)

rawDescription: Many to many relationship with a composite key on SQLAlchemy


rawDescription: how to specify the partition for mapPartition in spark

description: Specify the partition for mapPartition in spark


code:
type(int(2**64)) is long
type(int()) is int
int is long

rawDescription: Why is open() preferable over file() in Python?


rawDescription: A templated constructor cursor and a templated member cursor have kind FUNCTION_TEMPLATE in libclang


code:
subsets = [{attr: getattr(x, attr) for attr in ["a", "d"]}
           for x in someObjects]

rawDescription: How Can I Get a Subset of an Object's Properties as a Python Dictionary?


code:
frozenfunc = freezefunc(func)
frozenfunc(a='somevalue')

rawDescription: Freezing Function Arguments

description: Freezing Function Arguments


code:
data=io.loadmat('test.mat')
data
data['images'].T
data['images'].transpose([2,0,1])
data['images'].transpose([2,1,0]).reshape(5,-1)

rawDescription: reshape an array of images

description: Reshape an array of images


code:
with open(filename, 'r') as f:
    lines = f.readlines()

def wrap(line):
    broken = textwrap.wrap(line, 20, break_long_words=False)
    return '\n'.join(broken)

wrapped = [wrap(line) for line in lines]

rawDescription: How to limit the number of characters per line without affecting a word?

description: Limit the number of characters per line without affecting a word


code:
field in table.c
'id' in table.c
'nothere' in table.c

rawDescription: SqlAlchemy Dynamic Where

description: SqlAlchemy Dynamic Where


code: assert isinstance(foo, Bar)

rawDescription: Komodo 7 or 8 code completion for django


code: df1['product_type'] = df1['product_type'].factorize()[0] + 1

rawDescription: Pandas - how to replace specific values in a Series?


code: list2 = [list1[-i:] for i in range(4,1,-1)]

rawDescription: Splicing a list at different intervals based on a value of a list in python


code:
lstset = {l.split()[9].replace('SRC=','') for l in content}
print('\n'.join(lstset))

rawDescription: How to get the nth parameter of a list with delimiter space in python

description: Get the nth parameter of a list with delimiter space in python


code:
#include <stdio.h>
setlinebuf(stdout);

rawDescription: Getting another program's output as input on the fly


code: import this

rawDescription: How to glob for iterable element

description: Glob for iterable element


code:
def scanFiles2(rdir, sstring, extens, start='', cSens=False):
    if not cSens:
        # This only need to called once.
        sstring = sstring.lower()
    fList = []
    for fol, fols, fils in os.walk(rdir):
        for fil in fils:
            if not (fil.startswith(start) and fil.endswith(extens)):
                continue
            fil = os.path.join(fol, fil)
            with open(fil) as rFil:
                for line in rFil:
                    if not cSens:
                        line = line.lower()
                    if sstring in line:
                        break
                else:
                    fList.append(fil)
    ...

rawDescription: Find all text files not containing some text string


code:
counts = arange(0, len(list_of_dates))
plot(list_of_dates, counts)

rawDescription: Plotting a cumulative graph of python datetimes


code:
#draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d

class Arrow3D(FancyArrowPatch):
    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
        FancyArrowPatch.draw(self, renderer)

rawDescription: Python - Plotting velocity and acceleration vectors at certain points


code:
def test(value):
    scaleY.set(value)

rawDescription: Update Scale Widget from the value of other Scale Widget


code: n = int(raw_input())

rawDescription: Python long integer input

description: Python long integer input


code:
# -- coding: utf-8 --

from win32api import *
from win32gui import *
import win32con
import sys, os
import struct
import time

# Class
class WindowsBalloonTip:
    def __init__(self, title, msg):
        message_map = { win32con.WM_DESTROY: self.OnDestroy,}

        # Register the window class.
        wc = WNDCLASS()
        hinst = wc.hInstance = GetModuleHandle(None)
        wc.lpszClassName = 'PythonTaskbar'
        wc.lpfnWndProc = message_map # could also specify a wndproc.
        classAtom = RegisterClass(wc)

        # Create the window.
        style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
        self.hwnd = CreateWindow(classAtom, "Taskbar", style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None)
        UpdateWindow(self.hwnd)

        # Icons managment
        iconPathName = os.path.abspath(os.path.join( sys.path[0], 'balloontip.ico' ))
        icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
        try:
            hicon = LoadImage(hinst, iconPathName, win32con.IMAGE_ICON, 0, 0, icon_flags)
        except:
            hicon = LoadIcon(0, win32con.IDI_APPLICATION)
        flags = NIF_ICON | NIF_MESSAGE | NIF_TIP
        nid = (self.hwnd, 0, flags, win32con.WM_USER+20, hicon, 'Tooltip')

        # Notify
        Shell_NotifyIcon(NIM_ADD, nid)
        Shell_NotifyIcon(NIM_MODIFY, (self.hwnd, 0, NIF_INFO, win32con.WM_USER+20, hicon, 'Balloon Tooltip', msg, 200, title))
        # self.show_balloon(title, msg)
        time.sleep(5)

        # Destroy
        DestroyWindow(self.hwnd)
        classAtom = UnregisterClass(classAtom, hinst)
    def OnDestroy(self, hwnd, msg, wparam, lparam):
        nid = (self.hwnd, 0)
        Shell_NotifyIcon(NIM_DELETE, nid)
        PostQuitMessage(0) # Terminate the app.

# Function
def balloon_tip(title, msg):
    w=WindowsBalloonTip(title, msg)

# Main
if __name__ == '__main__':
    # Example
    balloon_tip('Lorem Ipsum', 'Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...')
    balloon_tip('Example two', 'There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain...')

rawDescription: Multiple WindowsBaloonTip / TrayTip Notifications?


rawDescription: Python: given a list of lists, create a list ordered by the number of occurrences in inner list


code: lambda doc: doc['username'] in following

rawDescription: RethinkDB: matching a string from a list of strings


code: ts.resample('H', how='count')

rawDescription: Count number of events per hour given in datetime/numpy


rawDescription: numpy where compare arrays as a whole

description: Numpy where compare arrays as a whole


code: [[record.a, record.b] for record in records if record.c == 1]

rawDescription: indexing and finding values in list of namedtuples

description: Indexing and finding values in list of namedtuples


code:
for grpname,grpteams in df.groupby('group')['team']:
    teamlist = grpteams.tolist()
...
['Canada', 'Netherlands', 'China', 'New Zealand']
['Germany', 'Norway', 'Thailand', 'Ivory Coast']
['Japan', 'Switzerland', 'Ecuador', 'Cameroon']
['USA', 'Sweden', 'Australia', 'Nigeria']
['Brazil', 'Spain', 'South Korea', 'Costa Rica']
['France', 'England', 'Mexico', 'Colombia']

rawDescription: Generate pairings within World Cup tournament groups


code:
from collections import Counter

unique_items = [item for item, count in Counter(a).items() if count == 1]

rawDescription: Find the occurrences of unique element in list in python


code: ''.join(char for char in word if char.lower() not in 'aeiou')

rawDescription: string replace vowels in python?

description: String replace vowels in python


code:
response = session.post(login_url, data={
    "_token": token,
    "pnr": PNR
})

rawDescription: Trouble with requests/Beautiful soup

description: Trouble with requests/Beautiful soup


code:
import json
from pprint import pprint

data = json.loads(response)
pprint(data)

rawDescription: How do i use native rest api in Django frame work?

description: Use native rest api in Django frame work


code:
x = "a\r\nb\r\nc\r\n"
x

rawDescription: why is python script failing to download webpages through a proxy

description: Why is python script failing to download webpages through a proxy


code:
class A:
    def __init__(self):
        self.test = ''
        self.func("test")
        print(self.test)
    def func(self,var):
        setattr(self,var,'foo')

rawDescription: python 3: Class function member to modify a class data member

description: Python 3: Class function member to modify a class data member


code:
r = requests.head('http://github.com', allow_redirects=True)
r.url
r.history

rawDescription: python: how to tell if a link redirects to another?

description: Python: how to tell if a link redirects to another


rawDescription: How to Print An Odd Number of Backslashes in Python


rawDescription: Python Regular Expression matching multiple lines (re.DOTALL)


rawDescription: Is there a python builtin for merging dicts where I can pass the function to run when there's key conflicts?


code:
import os

if output_fname is None:
    basename, ext = os.path.splitext(input_fname)
    output_fname = basename + ".faa"

rawDescription: Making default output file dependent on input file


code:
for elem in some_list:
    ...

rawDescription: How does this for loop know which list to sort through?


code:
import numpy as np
import ctypes

count = 5
size = 1000

#create some arrays
arrays = [np.arange(size,dtype="float32") for ii in range(count)]

#get ctypes handles
ctypes_arrays = [np.ctypeslib.as_ctypes(array) for array in arrays]

#Pack into pointer array
pointer_ar = (ctypes.POINTER(C.c_float) * count)(*ctypes_arrays)

ctypes.CDLL("./libfoo.so").foo(ctypes.c_int(count), pointer_ar, ctypes.c_int(size))

rawDescription: Passing a set of NumPy arrays into C function for input and output


code: map(lambda l,v: l.append(v), (list1, list2), func())

rawDescription: Appending the return values to a set of list directly


code:
option = 'bool'
form = Your_form(option=option)

rawDescription: How to initialize django-form data type field from a given choices?

description: Initialize django-form data type field from a given choices


code: {item[0]: item[1:] for item in inputlist}

rawDescription: How to convert a list to dict using python

description: Convert a list to dict using python


code:
with open("test.txt") as f:
    data = []
    r = re.compile("NO_USERS=\d+|id_info=\d+")
    for line in f:
        # if True we have a new block
        if line.startswith("BLOCK"):
            # call next twice to get thw second line after BLOCK
            _, l = next(f), next(f)
            # get name after BLOCK
            name = line.split(None,2)[1]
            # find our substrings from l
            d = dict(s.split("=") for s in r.findall(l))
            d["Name"] = name
            data.append(d)

print(data)

rawDescription: How to read a file block-wise in python

description: Read a file block-wise in python


code:
def test_n_props(self):
    for cur_prop in petersen_prop:
        func = globals()[cur_prop]
        self.assertTrue(func(self.adj,**self.args) ==
                        petersen_prop[cur_prop])

rawDescription: Unittest from a dictionary of functions and values


code:
class packet:
  _ethernet = None
  _eth = None
  _ip = None
  _l4 = None
  _pcapw = None
  def __init__(self,pbuffer,writer):
   self._ethernet = copy.deepcopy(pbuffer)
   self._pcapw = writer
  ###some other methods
  def infoIP(self):
    self._eth = dpkt.ethernet.Ethernet(self._ethernet)

    ret = ""
    if self._eth.type == dpkt.ethernet.ETH_TYPE_IP:
       ret = "IPV4"
   ###v6,vlan,arp handling
    else:
       self._pcapw.writepkt(self._ethernet)
       self._ip = None
       return None
    self._ip = self._eth.data
    return ret

  def infoL4(self):
    if (self._ip== None):
        return 0
    self._l4 = self._ip.data
    if type(self._l4) == TCP:
        self._pcapw.writepkt(self._ethernet,ts=1412977616)
        return 6
    ##something else

rawDescription: How do I generate a pcap file in Python?

description: Generate a pcap file in Python


code:
f = open("mydata.csv", "w")
f.write(text)
f.close()

rawDescription: How to save Multi-layered dictionary to csv

description: Save Multi-layered dictionary to csv


code:
from collections import OrderedDict
OrderedDict(sorted(d.items(), key=lambda i:keyorder.index(i[0])))

rawDescription: Custom Sorting Python Dictionary

description: Custom Sorting Python Dictionary


rawDescription: Get command window output to display in widget with tkinter


code:
def reg_iter(s,d):
    r = re.compile("|".join([r"\b{}\b".format(w) for w in d]))
    for match in r.finditer(s):
        links[match.group()].append((match.start(),match.end()))
    return d

rawDescription: Positions of substrings in string

description: Positions of substrings in string


code:
from itertools import repeat

def recreate(callable, count=None):
    for c in repeat(callable, count):
        for val in c():
            yield val

rawDescription: Chain repetitions of same generator in python


code: [items_dict.__setitem__(x, to_string_and_select(x)) for x in we_need_this]

rawDescription: list comprehension with some equal action python

description: List comprehension with some equal action python


rawDescription: Selenium Webdriver is finding hidden values too


code:
# Reshape the 3D array to a 2D array merging the first two dimensions
Ar = A.reshape(-1,A.shape[2])

# Perform lex sort and get the sorted indices and xy pairs
sorted_idx = np.lexsort(Ar.T)
sorted_Ar =  Ar[sorted_idx,:]

# Get IDs for each element based on their uniqueness
id = np.append([0],np.any(np.diff(sorted_Ar,axis=0),1).cumsum())

# Get counts for each ID as the final output
unq_count = np.bincount(id)

rawDescription: Efficiently count the number of occurrences of unique subarrays in NumPy?


rawDescription: Python iterating through pandas more efficiently without for loop


rawDescription: 2d array of zeros

description: 2d array of zeros


code:
import os
f = open('insert.txt', 'r+')
f.seek(3)
f.seek(-1, os.SEEK_CUR) # will go back one position
f.seek(-1, os.SEEK_END) # one position before the end of the file

rawDescription: Most efficient way to add a (generated) header to many files?


code:
# -*- coding: utf-8 -*-
# the following prints the Dutch word "één"
print(u"\xe9\xe9n")

rawDescription: Mixed usage of UTF-8 and ASCII encodings?


code:
import zmq
from multiprocessing import reduction

def rebuild_handle_with_key(pickled_data, authkey=None):
    from multiprocessing import current_process
    from multiprocessing.util import sub_debug
    from multiprocessing.connection import Client
    from multiprocessing.reduction import recv_handle
    import os
    address, handle, inherited = pickled_data
    if inherited:
        return handle
    sub_debug('rebuilding handle %d', handle)
    conn = Client(address, authkey=authkey or current_process().authkey)
    conn.send((handle, os.getpid()))
    new_handle = recv_handle(conn)
    conn.close()
    return new_handle

def rebuild_connection_with_key(reduced_handle, readable, writable, authkey=None):
    import _multiprocessing
    handle = rebuild_handle_with_key(reduced_handle, authkey)
    return _multiprocessing.Connection(
        handle, readable=readable, writable=writable
        )

reduction.rebuild_connection = rebuild_connection_with_key

context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect ("tcp://localhost:5556")
socket.setsockopt(zmq.SUBSCRIBE, '')

obj = socket.recv_pyobj()
authkey = socket.recv()
answer_conn = obj[0](obj[1][0],obj[1][1],obj[1][2], authkey)
# answer_conn = obj[0](*obj[1])

answer_conn.send('All is OK!')

rawDescription: Send python multiprocessing connection via ØMQ


code:
class BaseMeta(type):
    def __new__(cls, classname, bases, dict):
        new = type.__new__(cls, classname, bases, dict)
        new.classname = classname
        print ("BaseMeta::new. Called.")
        return new

class Base(object):
    __metaclass__ = BaseMeta

class HeirMeta(BaseMeta):
    def __new__(self, *args):
        new = BaseMeta.__new__(self, *args)
        print ("HeirMeta::new. Called.")
        return new

class Heir(Base):
    __metaclass__ = HeirMeta

    @classmethod
    def define(cls, nexttype):
        print ("Heir::define. Called.")

class HeirOfHeir(Heir):
    pass

Heir.define(HeirOfHeir)

rawDescription: Converting Python2 to Python3 with metaclasses resulted in a wrong flow


code:
rgb = img_array[:, :, :3]

# form an rgb eqvivalent of intensity
d = tdx_n.repeat(3).reshape(rgb.shape)

# simulate illumination based on pegtop algorithm.
rgb = 2 * d * rgb + (rgb ** 2) * (1 - 2 * d)

plt.imshow(rgb[4:-3,4:-3])
plt.show()

rawDescription: Issue creating map shading in Matplotlib imshow by setting opacity to data gradient


code:
test_list = ['Hafst\xc3\xa4tter', 'asbds@ages.at']
print(test_list)
for item in test_list:
    print(item)

rawDescription: Python list items encoding

description: Python list items encoding


code:
# This is just an example. It could definitely use improvement.
def foo(cr, text, tracking):
    # Normal tracking = 0. Negative spacing shrinks, positive expands.

    i = 0
    for c in text:
        x, y = cr.get_current_point()
        cr.show_text(c)
        counter += 1
        cr.move_to( x - i*tracking, y)

rawDescription: Is there a way to change letter spacing in PyCairo? (Or change a text width without affecting the height)


code:
from Tkinter import *
import numpy as np
import cv2

class Test:
    def __init__(self):
        self.b1="up"
        self.xold=None
        self.yold=None
        self.liste=[]
        self.maclasse = MaClasse()
    def test(self,obj):
        self.drawingArea=Canvas(obj)
        self.drawingArea.pack()
        self.drawingArea.bind("<Motion>",self.motion)
        self.drawingArea.bind("<ButtonPress-1>",self.b1down)
        self.drawingArea.bind("<ButtonRelease-1>",self.b1up)
    def b1down(self,event):
        self.b1="down"
    def b1up(self,event):
        self.b1="up"
        self.xold=None
        self.yold=None
        self.liste.append((self.xold,self.yold))
    def motion(self,event):
        if self.b1=="down":
            if self.xold is not None and self.yold is not None:
                event.widget.create_line(self.xold,self.yold,event.x,event.y,fill="red",width=3,smooth=TRUE)
                self.maclasse.dessiner_ligne(self.xold,self.yold,event.x,event.y)
            self.xold=event.x
            self.yold=event.y
            self.liste.append((self.xold,self.yold))

class MaClasse:
    def __init__(self):
        self.s=600,600,3
        self.ma=np.zeros(self.s,dtype=np.uint8)
        cv2.namedWindow("OpenCV",cv2.WINDOW_AUTOSIZE)
        cv2.imshow("OpenCV",self.ma)

    def dessiner_ligne(self, xold, yold, x, y):
        cv2.line(self.ma,(xold, yold),(x,y),[255,255,255],2)
        cv2.imshow("OpenCV",self.ma)

if __name__=="__main__":
    root = Tk()
    root.wm_title("Test")
    v = Test()
    v.test(root)
    root.mainloop()

rawDescription: Displaying TkInter and OpenCV windows on the same time


rawDescription: ZeroMQ - how to make a CLIENT to give up and try at a later time if the SERVER doesn't respond?


code:
from scipy.interpolate import UnivariateSpline

temp = np.asarray([10, 9.6, 9.3, 9.0, 8.7])    # Temperature in celsius
height = np.asarray([129, 145, 167, 190, 213]) # Height in meters
f = UnivariateSpline(height, temp)

rawDescription: Interval average of 1D data

description: Interval average of 1D data


code:
class MyQTableWidget(QtGui.QTableWidget):
    def __init__(self, parent=None):
        super(MyQTableWidget, self).__init__(parent)

        self.setHorizontalHeader(MyHorizHeader(self))

    def setHorizontalHeaderLabels(self, headerLabels, fontsize):

        qpixmaps = []
        indx = 0
        for labels in headerLabels:
            qpixmaps.append(mathTex_to_QPixmap(labels, fontsize))
            self.setColumnWidth(indx, qpixmaps[indx].size().width() + 16)
            indx += 1

        self.horizontalHeader().qpixmaps = qpixmaps

        super(MyQTableWidget, self).setHorizontalHeaderLabels(headerLabels)

class MyHorizHeader(QtGui.QHeaderView):
    def __init__(self, parent):
        super(MyHorizHeader, self).__init__(QtCore.Qt.Horizontal, parent)

        self.setClickable(True)
        self.setStretchLastSection(True)

        self.qpixmaps = []

    def paintSection(self, painter, rect, logicalIndex):

        if not rect.isValid():
            return

        #------------------------------ paint section (without the label) ----

        opt = QtGui.QStyleOptionHeader()
        self.initStyleOption(opt)

        opt.rect = rect
        opt.section = logicalIndex
        opt.text = ""

        #---- mouse over highlight ----

        mouse_pos = self.mapFromGlobal(QtGui.QCursor.pos())
        if rect.contains(mouse_pos):
            opt.state |= QtGui.QStyle.State_MouseOver

        #---- paint ----

        painter.save()
        self.style().drawControl(QtGui.QStyle.CE_Header, opt, painter, self)
        painter.restore()

        #------------------------------------------- paint mathText label ----

        qpixmap = self.qpixmaps[logicalIndex]

        #---- centering ----

        xpix = (rect.width() - qpixmap.size().width()) / 2. + rect.x()
        ypix = (rect.height() - qpixmap.size().height()) / 2.

        #---- paint ----

        rect = QtCore.QRect(xpix, ypix, qpixmap.size().width(),
                            qpixmap.size().height())
        painter.drawPixmap(rect, qpixmap)

    def sizeHint(self):

        baseSize = QtGui.QHeaderView.sizeHint(self)

        baseHeight = baseSize.height()
        if len(self.qpixmaps):
            for pixmap in self.qpixmaps:
               baseHeight = max(pixmap.height() + 8, baseHeight)
        baseSize.setHeight(baseHeight)

        self.parentWidget().repaint()

        return baseSize

rawDescription: Displaying LaTeX in pyQt/pySide QTableWidget


rawDescription: Pandas Merge - How to avoid duplicating columns


rawDescription: How to select group's rows having the greatest index

description: Select group's rows having the greatest index


code:
filename = '/path/to/file.csv'
df = pd.read_csv(filename, index_col='endDate', parse_dates=['endDate'],
                 date_parser=lambda x: pd.to_datetime(x.rsplit(' ', 1)[0]))

rawDescription: Ignore timezone offset portion of date time stamp pandas parse_dates


rawDescription: Turn a List of Str into a List of Int (Python)


rawDescription: Google cloud endpoint RequestMessage with multiple fields resolution


code:
np.c_[data1d]
np.c_[data2d]

rawDescription: determine number of rows of an (M,N) array and (M,) array with same function

description: Determine number of rows of an (M,N) array and (M,) array with same function


code:
def f(*args):
    pass

rawDescription: Function Decorators

description: Function Decorators


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

def vec_to_spec(v):
    return tuple(len(list(g)) for k,g in groupby(v) if k)

def build_specs(n=6):
    specs = defaultdict(list)
    for v in product([0,1], repeat=n):
        specs[vec_to_spec(v)].append(v)
    return specs

def check(rowvecs, row_counts, col_counts):
    colvecs = zip(*rowvecs)
    row_pass = all(vec_to_spec(r) == tuple(rc) for r,rc in zip(rowvecs, row_counts))
    col_pass = all(vec_to_spec(r) == tuple(rc) for r,rc in zip(colvecs, col_counts))
    return row_pass and col_pass

def nonosolve(row_counts, col_counts):
    specs = build_specs(len(row_counts))
    possible_rows = [specs[tuple(r)] for r in row_counts]
    sols = []
    for poss in product(*possible_rows):
        if check(poss, row_counts, col_counts):
            sols.append(poss)
    return sols

rawDescription: Python nonogram uniqueness

description: Python nonogram uniqueness


code:
UNIQUE_INSTANCE_ID = {} # at module level
logging.debug("Instance %s." % (str("%X" % id( UNIQUE_INSTANCE_ID )).zfill(16)))

rawDescription: In Python App Engine How Do I Uniquely Identify An Instance Of My App Running On The Dev SDK?


code:
needles
haystack
matches = defaultdict(list)
words = re.findall(r'(\w+)', haystack)
for key in needles:
  for word in words:
    if key in word:
      matches[key].append(word)

for key, found in matches.iteritems():
  print('Key: {} - Total Matches: {}'.format(key, len(found)))
  for match in found:
    print('\t{}'.format(match))

rawDescription: substring of a string using python?

description: Substring of a string using python


code:
print('Content-Type: text/html')
print('\n\n')

print('This is my Website!')

rawDescription: Blank page when trying to set up Apache and Django together


code:
def quantityFunction1():
    quantity = input("Please enter the amount of this item you would like to purchase: ")
    if quantity.isdigit():
        return int(quantity)
    else:
        print("We didn't recognise that number. Please try again.")
        return quantityFunction()

rawDescription: Incorrect Looping and returning of variable


code:
def compose(f, g):
    return lambda *x: f(g(*x))

rawDescription: python, functions combination via names and chain them to invoke in-a-go?

description: Python, functions combination via names and chain them to invoke in-a-go


code:
import asyncio

class Test:
    def __enter__(self):
        return self

    def __exit__(self, *args):
        print("arg")

    @asyncio.coroutine
    def __aenter__(self):
        yield from self.init_state()
        return self

    @asyncio.coroutine
    def init_state(self):
        yield from asyncio.sleep(2) # Pretend this is real initialization

    @asyncio.coroutine
    def __aexit__(self, *args):
        return self.__exit__(self, *args)

rawDescription: Coroutine in python between 3.4 and 3.5, How can I keep backwords compatibility?


code: from win32com.client import Dispatch

rawDescription: Why does it take longer to import a function from a module than the entire module itself?


code:
frame_2 = MyFrame2(None, wx.ID_ANY, "") #frame_2 object is created
frame_2.MakeModal(True) #makes frame_2 our temporary top window. This means that frame_1 cannot be accessed now and can only be accessed after frame_2 is closed
frame_2.Show() #shows frame_2

rawDescription: WXPYTHON: How to check If a frame is already visible?


code: pqr_version = ' '.join(string[string.index('pqr')+3:string.index('pqr')+5]) #This will give 201 403061815

rawDescription: Split a paragraph into lines

description: Split a paragraph into lines


code:
import email.utils

email_to_raw   = '"John, A" <john@abc.com>, "Peter, B" <peter@def.com>'

# split into (Name, Addr) tuple
email_to_split = email.utils.getaddresses([email_to_raw])

# combine the tuples into addresses, but keep the list
email_to = [email.utils.formataddr(pair) for pair in email_to_split]

print(email_to) # ['"John, A" <john@abc.com>', '"Peter, B" <peter@def.com>']

rawDescription: Python Retrieve Email Addresses

description: Python Retrieve Email Addresses


code:
import itertools
a = [''.join(i) for i in itertools.permutations("1234") ]
print(a)

rawDescription: Python permutations

description: Python permutations


code:
x = numpy.empty(appropriate_shape, dtype=object)
x[:] = your_list_of_foos

rawDescription: Numpy arrays containing iterable objects


rawDescription: Classify elements of a numpy array using a second array as reference


code:
def complex_func():
    lambda x: 42

    def decorator(cls):
        return lambda: cls()

    @decorator
    class b():
        def method():
            pass

    class c(int, metaclass=abc.ABCMeta):
        def method():
            pass

    {x for x in ()}
    {x: x for x in ()}
    [x for x in ()]
    (x for x in ())

rawDescription: Is it possible to access inner functions and classes via code objects?


code:
def getLongestSequenceSize(search_str, polymer_str):
    longest_match = ''
    for match in re.finditer(r'(?:\b%s\b\s?)+' % search_str, polymer_str):
        if len(match.group(0)) > len(longest_match):
            longest_match = match.group(0)
    return longest_match.count(search_str)

rawDescription: Python: re..find longest sequence

description: Python: re..find longest sequence


code:
h, w = arr.shape
Z = linkage(arr[np.triu_indices(h, 1)], method="average")

rawDescription: Triangle vs. Square distance matrix for Hierarchical Clustering Python?


code:
from urllib import urlencode
params = urlencode({'q': 'python best practices', 'sort': 'relevance'})
params
from urllib2 import urlopen
html = urlopen("http://stackoverflow.com/search?%s" % params).read()
import re
links = re.findall(r'
([^<]*)
', html)
links
from urlparse import urljoin
links = [(urljoin('http://stackoverflow.com/', url), title) for url,title in links]
links

rawDescription: How can I search through Stack Overflow questions from a script?

description: Search through Stack Overflow questions from a script


code:
import re

def repair_json(val):
    return re.sub(r'(\w+):', r'"\1":',
                  val.replace('"', '\u0022').replace("'", '"'))

rawDescription: reading Unicode string as json object in python

description: Reading Unicode string as json object in python


code:
df2.index.name = 'step'
df2.plot()

rawDescription: Plotting data lines from pandas dataframe, identified by keys in one column instead by different columns


code: heading6= "{0:15s}{1:16d}".format("Total Overtime Hours", overHours)

rawDescription: Looping over a text file list with python


rawDescription: Convert pandas json for highstock data format in a angularjs controller


rawDescription: Python numpy array replacing

description: Python numpy array replacing


code:
stdin, stdout, stderr = client.exec_command(
    """
    # simple command that prints nonstop output; & runs it in background
    python -c '
import sys
import time

while 1:
  print time.time()
  sys.stdout.flush()
  time.sleep(0.1)
    ' &
    KILLPID=$!; # save PID of background process
    sleep 2; # or however many seconds you'd like to sleep
    kill $KILLPID
    """)

rawDescription: run command with paramiko for a certain amount of time

description: Run command with paramiko for a certain amount of time


code:
import lxml.etree as ET

csvData = [['foo bar', 'baz quux'],['bing bang', 'bim bop', 'bip burp'],]
csvFile = 'rowboat'
name = csvFile[:-4]
root = ET.Element('csv_data')
for num, tags in enumerate(csvData):
    row = ET.SubElement(root, '{f}-{n}'.format(f = name, n = num))
    for text in tags:
        text = text.replace(' ', '_')
        tag = ET.SubElement(row, text)
        tag.text = text

print(ET.tostring(root, pretty_print = True))

rawDescription: Python Conditional XML Writing

description: Python Conditional XML Writing


code: c.MPILauncher.mpi_args = ["-machinefile", "~/mpi_hosts"]

rawDescription: Setting up a distributed ipython/ipyparallel MPI cluster


rawDescription: How to access an element based on the element appears before it in python list

description: Access an element based on the element appears before it in python list


rawDescription: Find duplicates in a list of lists with tuples


code:
def read_columns(self, board):
    sheet = board
    #sheet = self.tabs_var.get()

rawDescription: Tkinter how to make a dynamic optionmenu without using a dictionary


code:
first = string.index('"')
second = string.index('"', first+1)
quote = string[first+1:second]

rawDescription: How can I select a string using start and endpoints (characters)?

description: Select a string using start and endpoints (characters)


code:
def insertSources(self, srctype, link):
    """ Insert rss sources so we can parse them """
    new = {srctype: link}
    self.__sources.insert(new)

rawDescription: MongoDB and PyMongo - SQL like columns

description: MongoDB and PyMongo - SQL like columns


code:
import subprocess

def write(string):
    p = subprocess.Popen(['python', __file__, 'write'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    p.communicate(input=string)

def read():
    p = subprocess.Popen(['python', __file__, 'read'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    return p.communicate()[0]

if __name__ == "__main__":
    import sys
    from Tkinter import Tk

    if len(sys.argv) != 2:
        sys.exit(1)

    r = Tk()
    try:
        r.withdraw()
        if sys.argv[1] == "write":
            r.clipboard_clear()
            r.clipboard_append(sys.stdin.read())
            r.update()
        elif sys.argv[1] == "read":
            sys.stdout.write(r.clipboard_get()),
        else:
            sys.exit(1)
    finally:
        r.destroy()

rawDescription: How do I use Tkinter and allow my application to keep the focus?

description: Use Tkinter and allow my application to keep the focus


code:
df.C.fillna(999, inplace=True)
df.D.replace('', np.NaN, inplace=True)

rawDescription: Dealing with missing data in Pandas and Numpy


rawDescription: Recursive definitions in Pandas

description: Recursive definitions in Pandas


code:
regex = re.compile(r"^\S.*(?:\n\s.*)+", re.MULTILINE)
[tuple(match.split()) for match in regex.findall(s)]

rawDescription: Group lines by line pattern

description: Group lines by line pattern


code:
arr = np.array([2, 0, 0, 0, 0, 1, 0, 1, 0, 0])
seq = np.array([0,0])
search_sequence_numpy(arr,seq)
search_sequence_cv2(arr,seq)

rawDescription: Searching a sequence in a NumPy array

description: Searching a sequence in a NumPy array


code: result = series.unstack()

rawDescription: Pandas: add dataframes to dataframe - match on index and column value


code:
def test_index_with_sample_case_for_depth_2(self):
    idx = HierarchicalIndex(2)

    # A
    idx.insert(1, 'A', 'X')
    idx.insert(2, 'A', 'X')
    idx.insert(3, 'A', 'X')

    idx.insert(4, 'A', 'Y')
    idx.insert(5, 'A', 'Y')

    idx.insert(10, 'A', 'Z')
    idx.insert(11, 'A', 'Z')

    #B
    idx.insert(6, 'B', 'X')
    idx.insert(7, 'B', 'X')

    idx.insert(8, 'B', 'Y')

    assert_that(idx.get('A'), equal_to([1, 2, 3, 4, 5, 10, 11]))
    assert_that(idx.get('A', 'Y'), equal_to([4, 5]))
    assert_that(idx.get('B'), equal_to([6, 7, 8]))
    assert_that(idx.get('B', 'X'), equal_to([6, 7]))

def test_index_with_sample_case_for_depth_3(self):
    idx = HierarchicalIndex(3)

    # A
    idx.insert(1, 'A', 'X', 'i')
    idx.insert(2, 'A', 'X', 'ii')
    idx.insert(3, 'A', 'X', 'ii')

    idx.insert(4, 'A', 'Y', 'i')
    idx.insert(5, 'A', 'Y', 'ii')

    idx.insert(10, 'A', 'Z', 'ii')
    idx.insert(11, 'A', 'Z', 'iii')

    #B
    idx.insert(6, 'B', 'X', 'ii')
    idx.insert(7, 'B', 'X', 'iii')

    idx.insert(8, 'B', 'Y', 'i')

    #same queries with case for depth 2
    assert_that(idx.get('A'), equal_to([1, 2, 3, 4, 5, 10, 11]))
    assert_that(idx.get('A', 'Y'), equal_to([4, 5]))
    assert_that(idx.get('B'), equal_to([6, 7, 8]))
    assert_that(idx.get('B', 'X'), equal_to([6, 7]))

    #new queries
    assert_that(idx.get('B', 'X', 'ii'), equal_to([6]))
    assert_that(idx.get('A', 'X', 'ii'), equal_to([2, 3]))

rawDescription: A tree structure with dynamic depth and data in only leaves


code:
from unum.units import * # Load a number of common units.
distance = 100*m
time = eval('9.683*s')
speed = distance / time
print(speed)

rawDescription: Casting string to 'unit' object in Python


code:
#!/usr/bin/env python
import tarfile
import subprocess
with tarfile.open("6genomes.tgz", "r:gz") as tar:
    for m in tar.members():
        if m.isreg():
            f = tar.extractfile(m)
            new_filename = generate_new_filename(f.name)
            with open(new_filename, 'wb') as new_file:
                proc = subprocess.Popen(['bgzip', '-c'], stdin=subprocess.PIPE, stdout=new_file)
                proc.stdin.write(f.read())
                proc.stdin.close()
                proc.wait()
            f.close()

rawDescription: How to pipe tar.extractall from python

description: Pipe tar.extractall from python


code:
black_list = ["ab:", "cd:", "ef:", "gh:"]

for line in some_file:
    if ":" in line and not any(x in line for x in black_list):
        pass

rawDescription: How to check if elements of a list are in a string

description: Check if elements of a list are in a string


code: "hello world sample text".split()

rawDescription: Python regex separate space-delimited words into a list


code: widget = self.FindFocus()

rawDescription: wxpython cut copy and paste throughout the application

description: Wxpython cut copy and paste throughout the application


code:
def using_sqlite_union():
    sql = '''
        SELECT p.price, t.date
        FROM ( {t} ) t
        LEFT JOIN price p
        ON p.date = t.date
    '''.format(t = ' UNION ALL '.join('SELECT {d!r} date'.format(d = str(d))
                                      for d in dates))
    cursor.execute(sql)
    return cursor.fetchall()

def using_sqlite_dates():
    sql = '''
        SELECT p.price, t.date
        FROM ( SELECT date from dates ) t
        LEFT JOIN price p
        ON p.date = t.date
    '''
    cursor.execute(sql)
    return cursor.fetchall()

def using_python_dict():
    cursor.execute('''
        SELECT date, price
        FROM price
        WHERE date <= ?
            AND date >= ?
            ''', (max(dates), min(dates)))

    result = dict(cursor.fetchall())
    result = [(result.get(d,None), d) for d in dates]
    return result

N = 500
m = 10
omit = random.sample(range(N), m)
dates = [ datetime.date(2000, 1, 1)+datetime.timedelta(days = i) for i in range(N) ]
rows = [ (d, random.random()) for i, d in enumerate(dates) if i not in omit ]

rawDescription: Query Sqlite for multiple arguments at once and handling missing values


code:
# of selected rows: 0
# of selected rows: 40
# of selected rows: 80
# of selected rows: 120
# of selected rows: 160
# of selected rows: 180
# of selected rows: 220
# of selected rows: 260
# of selected rows: 300
# of selected rows: 340
# of selected rows: 360
# of selected rows: 400
# of selected rows: 440
# of selected rows: 460
# of selected rows: 500
# of selected rows: 540
# of selected rows: 580
# of selected rows: 600
# of selected rows: 640
# of selected rows: 680
DONE

rawDescription: Strange behavior of MySQL SELECT

description: Strange behavior of MySQL SELECT


code:
from tkinter import *

def _show_value(v, *pargs):
    print(*pargs)
    print(v.get())

root = Tk()

entry_var1 = StringVar()
entry_var1.trace('w', lambda *pargs: _show_value(entry_var1, *pargs))

entry_var2 = StringVar()
entry_var2.trace('w', lambda *pargs: _show_value(entry_var2, *pargs))

e1 = Entry(root, textvariable=entry_var1)
e1.pack()

e2 = Entry(root, textvariable=entry_var2)
e2.pack()

root.mainloop()

rawDescription: How to get Entry value using PY_VAR0 or PY_VAR1?

description: Get Entry value using PY_VAR0 or PY_VAR1


code:
class AuthorPublication(models.Model):
    author = models.ForeignKey(Author, related_name='publications')
    object_id = models.PositiveIntegerField()
    content_type = models.ForeignKey(ContentType)
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    class Meta:
        unique_together = (
            ('object_id', 'content_type'),
        )

rawDescription: Django Many-to-Many with a Model Inheritance


code:
img_manip[img_manip > 2] = 0
result = 15000 * img_manip #This is optional, just makes it into a nicer range for my purposes

rawDescription: Iterating through a multidimensional array


rawDescription: Finding columns which contain dates in Pandas


code:
b = bytearray(10)
c = memoryview(b)[5:]
c[:] = bytearray(1 for d in c)
b

rawDescription: Is it possible to get a proxy onto a bytearray?


rawDescription: Solve folding paper challenge

description: Solve folding paper challenge


rawDescription: How to find xpath of an element in a window that's inside another "frame window"

description: Find xpath of an element in a window that's inside another "frame window"


code:
x = np.setxor1d(a, b)
i, = np.nonzero(np.in1d(a, x))
i
a[i]

rawDescription: Find indices of mutually exclusive elements between two arrays in python


code:
def some_func(obj):
    obj.format_byte(...)
    # other stuff
    obj.format_word(...)

rawDescription: Strategy pattern in Python when a "strategy" consists of more than one function


code:
W = tf.Variable(tf.constant(0.0, shape=[vocab_size, embedding_dim]),
                trainable=False, name="W")

embedding_placeholder = tf.placeholder(tf.float32, [vocab_size, embedding_dim])
embedding_init = W.assign(embedding_placeholder)

# ...
sess = tf.Session()

sess.run(embedding_init, feed_dict={embedding_placeholder: embedding})

rawDescription: Using a pre-trained word embedding (word2vec or Glove) in TensorFlow


code: [k for k,v in G.out_degree().iteritems() if v > 2]

rawDescription: How to list specific node/edge in networkx?

description: List specific node/edge in networkx


code: sns.pairplot(df, size=2.5)

rawDescription: How to load data from np matrix to seaborn?

description: Load data from np matrix to seaborn


code:
for a in out:
    print("http://www.virginiaequestrian.com/{}".format(a["href"]))

rawDescription: BeautifulSoup Iteration not working

description: BeautifulSoup Iteration not working


rawDescription: How to use reverse() in django on included URLs?

description: Use reverse() in django on included URLs


code:
qvalues = [[0.1, 0.3, 0.6],[0.7, 0.1, 0.2],[0.3, 0.4, 0.3],[0.1, 0.3, 0.6],[0.1, 0.3, 0.6],[0.1, 0.3, 0.6]]
locations = [(['Loc1','Loc1'], 3), (['Loc2'], 1), (['Loc3', 'Loc3', 'Loc3'], 2)]

locations_dict = {pos:(index,len(loc)) for index,(loc,pos) in enumerate(locations)}
# if python2: locations_dict = dict([(pos,(index,len(loc))) for index,(loc,pos) in enumerate(locations)])

offsets = [None]*len(locations)

def compute_offset(pos):
    # compute new offset from offset and length of previous position. End of recursion at position 1: we’re at the beginning of the list
    offset = sum(compute_offset(pos-1)) if pos > 1 else 0
    # get index at where to store current offset + length of current location
    index, length = locations_dict[pos]
    offsets[index] = (offset, length)

    return offsets[index]

compute_offset(len(locations))

qvalues = [qvalues[offset:offset+length] for offset,length in offsets]

rawDescription: Generating a new order for a list of lists in python


code:
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.core.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "myapp.processor.categories",         #you have added this line to settings
)

rawDescription: Make custom variable in Django Context permanent


rawDescription: Python- insert a character into a string


code:
a = b = 1
a
b

rawDescription: summing two columns in a pandas dataframe

description: Summing two columns in a pandas dataframe


code:
d = [sublist[:] for sublist in a]
d
d[1][1] = 23
d
a

rawDescription: Elements of the original list changes when a deep copy of changes


code:
import msvcrt
def wait():
    msvcrt.getch()
print('Press any key to continue')
wait()

rawDescription: Python: Execute a line by user input?

description: Python: Execute a line by user input


code:
import sys
sys.argv

rawDescription: Can I access sys.argv in python in interactive mode?

description: Access sys.argv in python in interactive mode


code:
def logs(user):
    return Log.objects.filter(email=user.email)

from django.contrib.auth.models import User
User.logs = property(logs)

rawDescription: Perform a SQL JOIN on Django models that are not related?


code:
from itertools import chain
list(chain.from_iterable(x.split('/') if '/' in x else [x] for x in input_list))

rawDescription: Python list comprehension with adding more elements in one go


rawDescription: Extract a part of a string in python

description: Extract a part of a string in python


code:
a = [3, 1, 4, 1, 5, 9]

def get_checksum(a):
    seed = 113
    limit = 10000007
    result = 0

    for item in a:
        result += item
        result *= seed
        result %= limit

    return result

print(get_checksum(a))
#>>> 8921379

rawDescription: Array Checksum Algorithm - Python 3

description: Array Checksum Algorithm - Python 3


rawDescription: pandas - how to combine selected rows in a DataFrame

description: Pandas - how to combine selected rows in a DataFrame


code:
for row, row_r in zip(table, table_r):
    for i, (val, val_r) in enumerate(zip(row, row_r)):
       row[i] = pygame.image.load(os.path.join(str(val)))
       row_r[i] = pygame.image.load(os.path.join(str(val_r)))

rawDescription: Copying a list in python

description: Copying a list in python


rawDescription: what is the difference between eval and exec in python?

description: What is the difference between eval and exec in python


code:
print("This is a program to order numbers in ascending and descending order.")
while 1 == 1:
    until = int(input("\nEnter how many numbers you want ordered: "))
    print("")
    loop = 0
    numbers = []
    while loop < until:
        number = float(input("Enter number: "))
        numbers.append(number)
        loop += 1
        print("\nHere are the numbers in descending order:")
    while len(numbers) > 0:
        print(max(numbers))
        largest = max(numbers)
        numbers.remove(largest)

rawDescription: How do I prevent Python's append method replacing existing values?

description: Prevent Python's append method replacing existing values


code:
def list_list(x,y):
    result = [] # make an empty list to store results

    for a,b in zip(x,y):
        # decide pass or fail
        if a >= 60 or b >= 60:
            word = 'pass'
        else:
            word = 'fail'
        # append to result list
        result.append([a, b, word])

    # return result list
    return result

rawDescription: Iterating List of lists- Return only one list out of four lists


code: [whatever_data]=pickle.load( open( "myallData.p", "rb" ) )

rawDescription: In matlab, how to read python pickle file?


rawDescription: Fit an integral function with parametric limit to data with Python (Debye Model)


rawDescription: Recursive expressions with pyparsing

description: Recursive expressions with pyparsing


rawDescription: Cycle Through List Items

description: Cycle Through List Items


code:
lat_vals, lat_idx = np.unique(lats, return_inverse=True)
lon_vals, lon_idx = np.unique(lons, return_inverse=True)
vals_array = np.empty(lat_vals.shape + lon_vals.shape)
vals_array.fill(np.nan) # or whatever yor desired missing data flag is
vals_array[lat_idx, lon_idx] = vals
vals_array

rawDescription: Fill 2D numpy array from three 1D numpy arrays


code: tril = tril.T

rawDescription: How to compare diagonally opposed element of a multidimensional array with numpy

description: Compare diagonally opposed element of a multidimensional array with numpy


rawDescription: Convert String of Hex and Ints to List in Python


code:
def findInter(pair):
    return (pair[0]+ '_' + pair[1], len(set(list(df[pair[0]])) & set(list(df[pair[1]]))))

rawDescription: The number of intersections between columns


code:
import xml.etree.ElementTree as ET
tree = ET.parse('D:/test.xml')
root = tree.getroot()

def get_info(food_id):
    for child in root.findall("*[@id='{0}']//".format(food_id)):
        print(child.text)

get_info(1)

rawDescription: How do I parse XML with attribute in python?

description: Parse XML with attribute in python


code: import shutil

rawDescription: Python - Copying only new files into another directory


rawDescription: Insert data from one sorted array into another sorted array


code:
import numpy as np
dx = 8
dy = 10
bx = 5.34
by = 1.09
index = np.zeros(dx+dy,dtype = 'int32')
outshape = (nrows, ncols)                        # if you know the size
output = np.zeros(outshape, np.int)              # initialize the output matrix
for i in np.arange(2,dy+1):
    for j in np.arange(1,dx+1):
        theta = 180*np.arctan(abs(j-bx)/(i-by))/np.pi
        if theta < 10:
            r = np.around(np.sqrt((j-bx)**2+(i-by)**2))
            r = r.astype(int)
            if r > 0:
                index[r] += 1
                output[r-1, index[r]-1] = i+(j-1)*dy  # no need to set `s` or `c`

rawDescription: Python numpy indexing does not work

description: Python numpy indexing does not work


code:
# main.py
while True:
    key = raw_input()
    if key == "foo":
        import foo_level
    # and so on.

rawDescription: Import same python module more than once


rawDescription: What is the correct way to AND in python?


code:
import signal

signal.getsignal(signal.SIGTERM)
Out[64]: 0 #i.e. nothing

rawDescription: Run code in python script on shutdown signal


code: my_list = [my_list + harmonic[i] * var1 for i in range(4)]

rawDescription: Preventing nested list output from a for-loop / list comprehension when appending new values to an Array


rawDescription: How can I tell MATLAB that the data I am importing is a series of vectors, not just a series of letters?

description: Tell MATLAB that the data I am importing is a series of vectors, not just a series of letters


code:
def run(self):
    returner = None
    self.dialog = self.get_widget("Authentication")
    result = self.dialog.run()

    login = self.get_widget("auth_login").get_text()
    password = self.get_widget("auth_password").get_text()
    save = self.get_widget("auth_save").get_active()
    self.dialog.destroy()

    if result == gtk.RESPONSE_OK:
        return (True, login, password, save)
    else:
        return (False, "", "", False)

rawDescription: Requesting information from the user inside a GTK main loop


code: a = np.delete(a, 2, axis=1)

rawDescription: Numpy's delete not working

description: Numpy's delete not working


code: dic={word:WordTrigger(parameters) for word in wordlist}

rawDescription: Dynamically Naming a Variable Pointing to a Class


code: a

rawDescription: Matrix multiplication in numpy

description: Matrix multiplication in numpy


code: dictAB = {k: [dictA[k], dictB[k]] for k in dictA.keys() & dictB.keys()}

rawDescription: Refactoring with python dictionary comprehension


code:
cur2=[range(4),range(4,8),range(2,6)]
cur2
max( cur2, key=lambda x:int(x[2]))

rawDescription: Python - 2d list max based on certain part of inner list


rawDescription: if Python doesn't support method overloading, then why does this method overload work while this other does not?

description: If Python doesn't support method overloading, then why does this method overload work while this other does not


code:
import pymongo
conn = pymongo.MongoClient()
db = conn.test
col =  db.collection

for doc in col.aggregate([{'$unwind': '$impressions'},
    {'$match': {'impressions.service': 'furniture'}},
    {'$group': {'_id': '$impressions.id', 'impressions_count': {'$sum': 1}}},
    ]):
    print(doc)

rawDescription: MapReduce in PyMongo

description: MapReduce in PyMongo


code:
...
model_obj = self.pool.get('ir.model')
imf_obj = self.pool.get('ir.model.fields')
field_label_list = []
model_id = model_obj.search(cr, uid, [('model','=','sale.order')], context=context)
if model_id:
    field_ids = imf_obj.search(cr, uid, [('model_id','=',model_id[0]),('ttype','=','many2one'),('relation','=','res.partner')], context=context)
    if field_ids:
        for field in imf_obj.browse(cr, uid, field_ids, context):
            field_label_list.append(field.field_description)
#do what you want with the list
...

rawDescription: Get label names for fields in OpenERP

description: Get label names for fields in OpenERP


code:
a=np.array([1,2,3,4,5,6,7,8,9])
np.where(a>4)
a[np.where(a>4)]
I=np.where(a>4)
I
a[I]
i, = np.where(a>4)   # note the , on LHS
i
a[i]
a[(i,)]

rawDescription: output of numpy.where(condition) is not an array, but a tuple of arrays: why?

description: Output of numpy.where(condition) is not an array, but a tuple of arrays: why


code:
points = [ None,  # dummy value to fill index 0 (we want to start at 1)
           None, None, None, None, None, None,  # for the first six atoms
           (5, 4, '&'),  # for point 7
           (7, 3, '|'),  # for point 8
           (8, 2, '|'),  # for point 9
           (9, 7, '&') ]  # for point 10

rawDescription: Creating formula based on binary tree leaves


code:
[True, True, True]
(True, True, True)
True

rawDescription: Lists are the same but not considered equal?


code: stacked_df = pd.concat(dat_dict)

rawDescription: How to keep dates as index and inner join keys in multiple excel files

description: Keep dates as index and inner join keys in multiple excel files


code:
#create the URLs and store in list
urls = []
for lat, long, lat1, long1 in (zip(llat, llong, llat[1:], llong[1:])):
    for page in range (1,5):
        print ("https://api.flickr.com/services/rest/method=flickr.photos.search&format=json&api_key=5..b&nojsoncallback=1&page={}&per_page=500&bbox={},{},{},{}&accuracy=1&has_geo=1&extras=geo,tags,views,description".format(page, lat, long, lat1, long1))

rawDescription: Loop through list and changing indexes

description: Loop through list and changing indexes


code: subprocess.call(command, shell=True)

rawDescription: Execute Subprocess in Background

description: Execute Subprocess in Background


code: a = GetPassword(buttons=('OK', 'Cancel'))

rawDescription: Can't cope with Dialog and Gridgeometry manager


code:
def handleHotKey(self, evt):
    if self.clicker_loop:
        self.clicker_loop = False
    else:
        self.clicker_loop = True

rawDescription: wxPython: global hotkey loop toggle

description: WxPython: global hotkey loop toggle


code: selected_words = [ w for w in words if w.startswith(u"x") ]

rawDescription: selecting unicode characters from text file or webpage

description: Selecting unicode characters from text file or webpage


rawDescription: Changing title of image to display many images simultaneously using open cv and python


code:
store.select('df',['a > 0','b>0'])
store.select('df',['a > 0'])

rawDescription: Can pandas and file system be used as a replacement for databases?


code:
import example
egg = example.Egg()
try:
    spam = egg.spam1 # expect to throw
    assert(False)
except TypeError:
    assert(True)
spam = egg.spam2
assert(spam == "hello world")

rawDescription: Why isn't python-exposed boost::gregorian::date available everywhere?


code:
class Address(object):
    def __init__(self, name, number, email):
        self.name = name
        self.number = number
        self.email = email

    def __repr__(self):
        return "Address(%s, %d, %s)" % (self.name, self.number, self.email)

# your list of addresses
addresses = [
    Address('Bruno', 44444, 'bruno@hotmail.com'),
    Address('Mariah', 333, 'mariah@hotmail.com'),
    Address('Oliver', 3333, 'oliver@yahoo.co.uk')
]

# Print your addresses
# prints: [Address(Bruno, 44444, bruno@hotmail.com), Address(Mariah, 333, mariah@hotmail.com), Address(Oliver, 3333, oliver@yahoo.co.uk)]
print(addresses)

# Remove "Bruno" from your addresses
# replacement for your "deletec()" function
# prints: [Address(Mariah, 333, mariah@hotmail.com), Address(Oliver, 3333, oliver@yahoo.co.uk)]
print([address for address in addresses if address.name != "Bruno"])

# Sort your addresses descending by name
# replacement for your "arrangebyorder()" function
# prints: [Address(Oliver, 3333, oliver@yahoo.co.uk), Address(Mariah, 333, mariah@hotmail.com), Address(Bruno, 44444, bruno@hotmail.com)]
print(sorted(addresses, key=lambda address: address.name, reverse=True))

rawDescription: Why isn´t it updating?

description: Why isn´t it updating


code:
e = 1
e in a # => True
e in b # => False

rawDescription: How can I quickly compare a list and a set?

description: Quickly compare a list and a set


code:
link = td_elem.find('a').text.strip()
text = ''.join(td_elem.itertext()).strip()
text.split(link)[1]

rawDescription: Parsing lxml.etree._Element contents

description: Parsing lxml.etree._Element contents


code:
def hello_user(self):
    return self.get_name()

rawDescription: LPTHW ex. 45, how to return functions from a class in another module?


code:
import package as pk
pk.MyClass(9)
f1 = pk.functions.MyFunctionsA()
f2 = pk.functions.MyFunctionsB()
f3 = pk.functions.MyFunctionsC()
f1.function1(100)
f2.function1(100)
f3.function1(100)

rawDescription: Passing a parameter between python classes


rawDescription: applying a function on an object in python

description: Applying a function on an object in python


code: query = UserSetting.query(UserSetting.name!='cookieAck', UserSetting.name != 'newkey', UserSetting.name != 'tempCelsius')

rawDescription: Google App Engine - NDB - best way of inversing the IN(list)


code: hand.sort(key=lambda c: rank_cards.index(c[0]), reverse=True)

rawDescription: Getting highest value card in list

description: Getting highest value card in list


code:
import sys

sys.stdout = StdoutWrapper(yourwidget)
# similar for stderr, but you might want an error dialog or make
# the text stand out using appendHtml

rawDescription: Wxwidgets and Pyqt

description: Wxwidgets and Pyqt


code:
import re
s = "name[id]"

# split by either a '[' or a ']'
re.split('\[|\]', s) # = ['name', 'id', '']

rawDescription: How to split a string by using [] in Python

description: Split a string by using [] in Python


code:
# Required Blender information.
bl_info = {
           "name": "My Exporter",
           "author": "",
           "version": (1, 0),
           "blender": (2, 65, 0),
           "location": "File > Export > Test (.tst)",
           "description": "",
           "warning": "",
           "wiki_url": "",
           "tracker_url": "",
           "category": "Import-Export"
          }

# Import the Blender required namespaces.
import sys, getopt

import bpy
from bpy_extras.io_utils import ExportHelper

# The main exporter class.
class MyExporter(bpy.types.Operator, ExportHelper):
   bl_idname       = "export_scene.my_exporter";
   bl_label        = "My Exporter";
   bl_options      = {'PRESET'};

   filename_ext    = ".tst";

   object_count    = 0;

   def __init__(self):
      pass

   def execute(self, context):
      print("Execute was called.");

      self.parse_command_line_options();

      if (self.filepath == ""):
         print("No sutable filename was provided to save to.");
         return {'FINISHED'};

      # Get all the mesh objects in the scene.
      objList = [object for object in bpy.context.scene.objects if object.type == 'MESH'];

      # Now process all the objects that we found.
      for gameObject in objList:
         self.export_object(gameObject);

      # Parse all the objects in the scene.
      return {'FINISHED'};

   def export_object(self, gameObject):
      if (gameObject.type != "MESH"):
         print("Object was not of type mesh.");
      else:
         self.object_count += 1;

      return;

   def parse_command_line_options(self):
      modelFile = "";
      myArgs = [];
      argsStartPos = 0;

      if (("--" in sys.argv) == False):
         return;

      argsStartPos = sys.argv.index("--");
      argsStartPos += 1;
      myArgs = sys.argv[argsStartPos:];

      try:
         opts, args = getopt.getopt(myArgs, 'hm:', ["help", "model-file="]);
      except getOpt.GetoptError:
         print("Opt Error.");
         return;

      for opt, arg in opts:
         if (opt in ("-h", "--help")):
            print("Run this as the following blender command.");
            print("\tblender <blend file> --background --python <script file> -- -m <output file>");
         elif (opt in ("-m", "--model-file")):
            modelFile = arg;

      if (modelFile != ""):
         self.filepath = modelFile;

# Define a function to create the menu option for exporting.
def create_menu(self, context):
   self.layout.operator(MyExporter.bl_idname,text="test (.tst)");

# Define the Blender required registration functions.
def register():
   """
   Handles the registration of the Blender Addon.
   """
   bpy.utils.register_module(__name__);
   bpy.types.INFO_MT_file_export.append(create_menu);

def unregister():
   """
   Handles the unregistering of this Blender Addon.
   """
   bpy.utils.unregister_module(__name__);
   bpy.types.INFO_MT_file_export.remove(create_menu);

# Handle running the script from Blender's text editor.
if (__name__ == "__main__"):
   print("Registering.");
   register();

   print("Executing.");
   bpy.ops.export_scene.my_exporter();

rawDescription: How do I get a Blender exporter script to run from the command line?

description: Get a Blender exporter script to run from the command line


rawDescription: 2D Histogram from a 3x3 array in PYTHON

description: 2D Histogram from a 3x3 array in PYTHON


code:
from scipy import ndimage

labels, nshapes = ndimage.label(a)
areas = ndimage.sum(a, labels=labels, index=range(1, nshapes))

idx = np.argmax(areas)
biggest_shape = labels == (idx + 1)

rawDescription: Variable area threshold for identifying objects - python


code: solution = ' '.join([w.lower() for w in listdefault[::-1] if w.istitle()])

rawDescription: Uncrypting a very simple code in python

description: Uncrypting a very simple code in python


code:
c = connection.cursor()
c.query('SELECT * FROM your_table WHERE id=?', ('yourid',))

rawDescription: How to directly query a relational/SQL database from a ZOPE product?

description: Directly query a relational/SQL database from a ZOPE product


code:
from natsort import natsort_keygen, ns
l1 = ['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
l2 = l1[:]
natsort_key1 = natsort_keygen(key=lambda y: y.lower())
l1.sort(key=natsort_key1)
l1
natsort_key2 = natsort_keygen(alg=ns.IGNORECASE)
l2.sort(key=natsort_key2)
l2

rawDescription: Does Python have a built in function for string natural sort?


code: ('mcgoga12', 'shelby12') ('password', 'password1')

rawDescription: Parsing a text file with Python and split()


code:
class NestedDict(dict):
    def __setitem__(self, key, value):
        if not isinstance(key, collections.Iterable) or isinstance(key, basestring):
            super(NestedDict, self).__setitem__(key, value)
            return
        keys = list(key)
        reduce(
            lambda d, k: d.setdefault(k, {}),
            keys[:-1],
            self
        )[keys[-1]] = value

rawDescription: Python parse a string into n-depth dictionary


code:
class MetaA(type):
    def __new__(mcls, name, bases, dct):
        slots = set(dct.get('__slots__', ()))
        slots.add('y')
        dct['__slots__'] = tuple(slots)
        return super().__new__(mcls, name, bases, dct)

class BaseA(metaclass=MetaA):
    pass

class A(BaseA):
    __slots__ = ('x',)

    def __init__(self):
        self.x = 1
        self.y = 2

print(A().x, A().y)

rawDescription: Is it possible to add __slots__ in decorator of class that already defines __slots__?


rawDescription: Set is much faster than list while lookup for membership


rawDescription: How to get indices of non-diagonal elements of a numpy array?

description: Get indices of non-diagonal elements of a numpy array


code:
class FooBar(Foo):

    @property
    def bar(self):
        # return the same value
        # as in the base class
        return Foo.bar(self)

rawDescription: How to call a property of the base class if this property is being overwritten in the derived class?

description: Call a property of the base class if this property is being overwritten in the derived class


code:
df.start_sec[i] *= scale
df.end_sec[i] *= scale

rawDescription: Updating values in a DataFrame

description: Updating values in a DataFrame


code:
myLines = []
for i in range(10):
    #not pictured: generate xcoord and ycoord however you want
    myLines.append(lines(xcoord,ycoord))

rawDescription: How can I check if 2 drawn lines overlap?

description: Check if 2 drawn lines overlap


code:
# add this function to the same module
def list_to_dict(l):
    return dict(zip(map(str, range(len(l))), l))

rawDescription: Recursive diff of two python dictionaries (keys and values)


code: myuser.groups = [group_list]

rawDescription: having 2 groups of users to view 2 different views in django

description: Having 2 groups of users to view 2 different views in django


code:
import csv

cn = 10001

with open("test.txt") as f, open("out.txt","w") as tmp:
    r, wr = csv.reader(f, delimiter="|"), csv.writer(tmp, delimiter="|")
    head, d = next(r), {}
    wr.writerow(["ID"]+head)
    for row in r:
        v = row[4]
        # if we have already seen the SSN, use the id assigned
        if v in d:
            wr.writerow([d[v]] + row)
        else:
            # else create new id, add pairing to dict and write
            d[v] = cn
            wr.writerow([cn] + row)
            cn += 1

rawDescription: Match attributes against one another Python


code: rcParams['figure.figsize'] = 16, 12

rawDescription: Setting python pandas histogram size

description: Setting python pandas histogram size


code:
from time import sleep
from threading import Thread
class Display(Thread):
    def run(self):
        while True:
            data = self.output.read()
            if data: print(data)
            sleep(1)

t = Display()
t.output = output
t.start()

rawDescription: how to read command output from serial device using python

description: Read command output from serial device using python


code:
import sympy
x,y,z = sympy.symbols('x,y,z')
p = sympy.poly((x+2*y-z)**3)
p.coeffs()

rawDescription: Best way to isolate one coefficient of a multivariate polynomial in sympy

description: Isolate one coefficient of a multivariate polynomial in sympy


code: '10      AccessibleComputing     0       381202555       2010-08-26T22:38:36Z    OlEnglish       7181920 #F3#    [[Help:Reverting|Reverted]] edits by [[Special:Contributions/76.28.186.133|76.28.186.133]] ([[User talk:76.28.186.133|talk]]) to last version by Gurch  #REDIRECT#F0#[[Computer#F0#accessibility]]#F0#{{R#F0#from#F0#CamelCase}}        lo15ponaybcg2sf49sstw9gdjmdetnk ,Computer_accessibility'.split()

rawDescription: what is the delimiter in my text

description: What is the delimiter in my text


code:
# Never do this -- insecure!
symbol = 'IBM'
c.execute("... where symbol = '%s'" % symbol)

# Do this instead
t = (symbol,)
c.execute('select * from stocks where symbol=?', t)

rawDescription: Python - Generate a multiple row update query


code: playerletter = input("What letter would you like to be? X or O? \n").upper()

rawDescription: Variable won't be assigned to input in Python


code:
df = DataFrame(randn(4,2), index=midx)
df.loc[df.index.get_loc_level('y',level=1)[0],0] = np.nan
df

rawDescription: Assign to MultiIndex slice

description: Assign to MultiIndex slice


code:
class Meta(type):
    def __repr__(cls):
        return 'My class %s' % cls.__name__

class A(object):
    __metaclass__ = Meta

rawDescription: Can I define a __repr__ for a class rather than an instance?

description: Define a __repr__ for a class rather than an instance


code:
class TestOriginal(unitest.TestCase):
    def test_Original_method(self):
        with patch('module_under_test.A') as mocked_A:
            mocked_A.return_value = 42
            result = module_under_test.B()
            mocked_A.assert_called_with()
            self.assertEqual(result, 420)

rawDescription: Patch a method outside python class

description: Patch a method outside python class


rawDescription: How to compute an expensive high precision sum in python?

description: Compute an expensive high precision sum in python


code:
import os
if os.environ['APPLICATION_ID'].startswith('dev'):
  pass  # it's localhost
else:
  pass  # it's uploaded on gae

rawDescription: GAE: python code to check if i'm on dev_appserver or deployed to appspot


code:
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

fig, axes = plt.subplots(3, 2)

rect = Rectangle((0.08, 0.35), 0.85, 0.28, facecolor='yellow', edgecolor='none',
                 transform=fig.transFigure, zorder=-1)
fig.patches.append(rect)
plt.show()

rawDescription: matplotlib: subplot background (axes face + labels) colour [or, figure/axes coordinate systems]

description: Matplotlib: subplot background (axes face + labels) colour [or, figure/axes coordinate systems]


code:
def get_overlap_pcnt(row):
    # Get the overlap between arrays.
    overlap = len(np.intersect1d(row['app_id_x'], row['app_id_y']))

    # Compute the percent common.
    if overlap == 0:
        pcnt = 0
    else:
        pcnt = 100*overlap/len(row['app_id_y'])

    return '{:.2f}%'.format(pcnt)

df['adoption_rate'] = df.apply(get_overlap_pcnt, axis=1)

rawDescription: How do I check the % of values in an array that exist in another array in pandas?

description: Check the % of values in an array that exist in another array in pandas


code: final_result = {(A, B, C): [x, y, z] for A, B, C, x, y, z in result}  # more readable than first one

rawDescription: AMPL vs. Python - Importing tables (multi-dimensional dictionaries?)


code:
import types

def do_profile_all_methods(cond):
    if not cond:
        return lambda c: c # Do nothing with the class; the 'null' decorator
    def profile_all_methods(klass):
        for name, attr in klass.__dict__.items():
            if isinstance(attr, types.UnboundMethodType):
                klass[name] = profile(attr)
        return klass
    return profile_all_methods

rawDescription: how can I profile class methods of my python app?

description: Profile class methods of my python app


code:
from collections import defaultdict
D = defaultdict(list)
D[somekey].append(auxfield)

rawDescription: Retrieving a specific set element in Python


code:
for key, value in costs.items():
    print(key, "costs", value)

rawDescription: Combine/ "concatenate" two variables, one being a user input


code:
def merge_file(infile, outfile, separator = ""):
    for line in infile:
        outfile.write(line.strip("\n")+separator)
    outfile.write("\n")

rawDescription: Merging multiple text files into one and related problems


code:
c = a            # a and c now point to the same integer object, 3
d = b            # b and d now point to the same list object, [1, 2, 3]

rawDescription: When does python know an initialization is a copy, so that change at one place automatically changes another place?


code:
re_pattern = re.compile(u'[^\u0000-\uD7FF\uE000-\uFFFF]', re.UNICODE)
filtered_string = re_pattern.sub(u'\uFFFD', unicode_string)

rawDescription: How to filter (or replace) unicode characters that would take more than 3 bytes in UTF-8?

description: Filter (or replace) unicode characters that would take more than 3 bytes in UTF-8


code:
a = np.memmap("qaz.mda", dtype=dt)
a
data = a['data']
data

rawDescription: improve speed when reading a binary file

description: Improve speed when reading a binary file


code:
mypoints = [(distance12, x1, x2),...,(distancenm, xn, xm)]
mypoints.sort()
three_closer = mypoints[:3]

rawDescription: Store 3 nearest coordinates

description: Store 3 nearest coordinates


code:
cred_tuple = ('joeuser', 'secret123')
credential = Credential._make(cred_tuple)

rawDescription: Structure accessible by attribute name or index options


code:
SA=np.array(S)
SA.shape

rawDescription: split ndarray into chunks - whilst maintaining order

description: Split ndarray into chunks - whilst maintaining order


rawDescription: Why do my nested python class instances become tuples?


code:
st = values()
st.struct1.a = 10
st.struct2.c = 20
print(st.struct1.a)
10
print(st.struct2.c)
20
st.setValue(b=20, a=100, d=50, c=60)
print(st.struct1.a)
print(st.struct1.b)
print(st.struct2.c)
print(st.struct2.d)
100
20
60
50

rawDescription: How to handle data in python similar to IDL structures?

description: Handle data in python similar to IDL structures


rawDescription: replace elements to reformat the dataset

description: Replace elements to reformat the dataset


rawDescription: Use between_time() on MultiIndex?

description: Use between_time() on MultiIndex


code:
def mom(c):
    c1=c[1::2].lower()
    c2=c[::2].upper()
    return "".join(i for j in zip(c2, c1) for i in j)
print(mom("Hello dear"))

rawDescription: Use upper and lower cases on a same word


rawDescription: Parsing a string containing # as separator


code:
from pyPdf import PdfFileReader

f = open('CT1-All.pdf', 'rb')
reader = PdfFileReader(f)
contents = reader.getPage(0).extractText().split('\n')
f.close()

rawDescription: parse a pdf using python

description: Parse a pdf using python


rawDescription: Calculate date from last operation from 90 days after


rawDescription: Passing variables onto a MongoDB Query

description: Passing variables onto a MongoDB Query


rawDescription: Python - remove parts of a string

description: Python - remove parts of a string


rawDescription: wxpython cut copy and paste throughout the application

description: Wxpython cut copy and paste throughout the application


code:
import requests
s = requests.session()
r = s.get('http://google.com')
r = s.get('http://facebook.net')
for cookie in s.cookies:
    print(cookie)

rawDescription: How to get 3rd party cookies?

description: Get 3rd party cookies


code: first, rest = seq[0], seq[1:]

rawDescription: How to unpack tuple of length n to m<n variables

description: Unpack tuple of length n to m<n variables


code:
import glob,os.path
filesDepth3 = glob.glob('*/*/*')
dirsDepth3 = filter(lambda f: os.path.isdir(f), filesDepth3)

rawDescription: List directories with a specified depth in Python


code:
def recursive_draw(G,currentscalefactor=0.1,center_loc=(0,0),nodesize=300, shrink=0.1):
    pos = nx.spring_layout(G)
    scale(pos,currentscalefactor) #rescale distances to be smaller
    shift(pos,center_loc) #you'll have to write your own code to shift all positions to be centered at center_loc
    nx.draw(G,pos=pos, nodesize=nodesize)
    for node in G.nodes_iter():
        if type(node)==Graph: # or diGraph etc...
            recursive_draw(node,currentscalefactor=shrink*currentscalefactor,center_loc=pos[node], nodesize = nodesize*shrink, shrink=shrink)

rawDescription: Drawing nested networkx graphs

description: Drawing nested networkx graphs


code:
val_list = []
for var in request.GET:
    var_list.append(request.GET[var])

rawDescription: Django: Handling several page parameters


code: result = np.sum(matrix)

rawDescription: Sum ndarray values

description: Sum ndarray values


code:
def create_myDict(mylists):
    myDict = {}
    for sublist in mylists:
        for i in range(len(sublist)):
            myDict.setdefault(sublist[i], []).append(i)
    return myDict

rawDescription: Create dictionary from multiple lists

description: Create dictionary from multiple lists


code:
file1_names = {o['name']: o for o in file1}
for obj2 in file2:
    obj2.update(file1_names.get(obj2['name'], {}))

rawDescription: There must be a more optimal way to parse two files


code:
operator.getitem(a, b)
operator.__getitem__(a, b)

rawDescription: Check for [] operator

description: Check for [] operator


code:
def fix_incorrect_orientation(pathName):
    for filename in os.listdir(pathName):
        tesseractResult = str(commands.getstatusoutput('tesseract ' + pathName + '/' + filename + ' -  -psm 0'))
        print('tesseractResult: ' + tesseractResult)
        regexObj = re.search('([Orientation:]+[\s][0-9]{1})',tesseractResult)
        if regexObj:
            orientation = regexObj.groups(0)[0]
            print('orientation123: ' + str(orientation))
        else:
            print('Not getting in the Regex.')

rawDescription: Can't get output from Tesseract command run through os.system


code:
#Create metric columns
HMDrr['SLOPE'] = ""
HMDrr['INTERCEPT'] = ""

rawDescription: How do I use row index to create a function based calculated column

description: Use row index to create a function based calculated column


code:
import colander

class Characteristic(collander.MappingSchema):
    id = colander.SchemaNode(colander.Int(),
                             validator=colander.Range(0, 9999))
    name = colander.SchemaNode(colander.String())
    rating = colander.SchemaNode(colander.String())

class Characteristics(collander.SequenceSchema):
    characteristic = Characteristic()

class Person(colander.MappingSchema):
    id = colander.SchemaNode(colander.Int(),
                             validator=colander.Range(0, 9999))
    name = colander.SchemaNode(colander.String())
    phone = colander.SchemaNode(colander.String())
    characteristics = Characteristics()

class Data(collander.SequenceSchema):
    person = Person()

rawDescription: Parse JSON and store data in Python Class


code:
import xml.etree.ElementTree as et

root = et.Element("tmx")
body = et.SubElement(root, "body")

tu = et.SubElement(body, "tu")
et.SubElement(tu, "tuv", attrib={"xml:lang": "en"})
et.SubElement(tu, "tuv", attrib={"xml:lang": "zh"})

print(et.tostring(body))

rawDescription: With xml.etree, How to I create namespaced attribute "XML:lang"?


code:
import csv

with open('Stockinventory.txt', 'w', newline='') as f:
    csv.writer(f).writerows(items)

rawDescription: Rewriting array to text file, need to put each part on new line


rawDescription: How to capture all characters in binary string without python interpreting it

description: Capture all characters in binary string without python interpreting it


code:
def sasquatchify(val):
    return val + ' sasquatch'

def unicornify(val):
    return val + ' unicorns'

def getset(name, getting, setting):
    return property(lambda self: getting(getattr(self, name)),
                    lambda self, val: setattr(self, name, setting(val)))

class Foo(object):
    bar = getset('_bar', sasquatchify, unicornify)
    baz = getset('_baz', sasquatchify, unicornify)

rawDescription: Python: Generic getters and setters

description: Python: Generic getters and setters


code:
def checkForBubblesAbsorbed(balloon, bubbles, window):
    count = 0
    for bubble in bubbles:
       collide = balloonBubbleCollide(balloon, bubble)
       if collide == True:
           count = count + 1
       print(count)
    # This return should be outside the for loop (you have an extra indent)
    return count

rawDescription: Count is increasing then decreasing back to zero. Want a cumulative count


code: data_reduced = np.dot(data - pca.mean_, pca.components_.T)

rawDescription: PCA inverse transform manually

description: PCA inverse transform manually


code:
dummies = df1.combineAdd(df2)
dummies

rawDescription: Pandas / Numpy: How to Turn Column Data Into Sparse Matrix


code:
from scipy import ndimage

def find_clusters(array):
    clustered = np.empty_like(array)
    unique_vals = np.unique(array)
    cluster_count = 0
    for val in unique_vals:
        labelling, label_count = ndimage.label(array == val)
        for k in range(1, label_count + 1):
            clustered[labelling == k] = cluster_count
            cluster_count += 1
    return clustered, cluster_count

clusters, cluster_count = find_clusters(array)
print("Found {} clusters:".format(cluster_count))
print(clusters)

ones = np.ones_like(array, dtype=int)
cluster_sizes = ndimage.sum(ones, labels=clusters, index=range(cluster_count)).astype(int)
com = ndimage.center_of_mass(ones, labels=clusters, index=range(cluster_count))
for i, (size, center) in enumerate(zip(cluster_sizes, com)):
    print("Cluster #{}: {} elements at {}".format(i, size, center))

rawDescription: How to efficiently find clusters of like elements in a multidimensional array

description: Efficiently find clusters of like elements in a multidimensional array


rawDescription: Python Image Processing - Move an Image

description: Python Image Processing - Move an Image


code: df['day'] = df.index.day

rawDescription: How to plot values for multiple factors from one column across several dates in pandas + matplotlib?

description: Plot values for multiple factors from one column across several dates in pandas + matplotlib


code:
@cache_page(60 * 15)
def my_mongo_view(request):
    return render_to_response('home.html', ...)

rawDescription: Is possible to save render_to_response template from django to server?


code:
for i, numbercode in enumerate(numbercode_list):
    print ("Item : %s" %i )
    if i % 100 == 0:
        driver.close()
        driver = init_driver()

rawDescription: Python run code every 100th loop item

description: Python run code every 100th loop item


code:
def home_ajax(request):
    if request.is_ajax():
        my_var = request.GET.get('myvar')
        return HttpResponse('ajax called with myvar: %s' % my_var)

    return HttpResponse()

rawDescription: JSON from JS to View in django

description: JSON from JS to View in django


code:
def sxtn( x, bits ):
     h= 1<<(bits-1)
     m = (1<<bits)-1
     return ((x+h) & m)-h

rawDescription: How can I convert a hex ASCII string to a signed integer

description: Convert a hex ASCII string to a signed integer