rawDescription: How does this program in python work?

description: How does this program in python work


code: mypart['rrp'], mypart['price'] = price

rawDescription: How to extract tags from HTML using Beautifulsoup in Python

description: Extract tags from HTML using Beautifulsoup in Python


rawDescription: How to retrieve the list of supported file formats for Matplotlib savefig() function?

description: Retrieve the list of supported file formats for Matplotlib savefig() function


code:
removable_set = set(removable)
primes = [p for p in primes if p not in removable_set]

rawDescription: What's a fast and pythonic/clean way of removing a sorted list from another sorted list in python?


code:
from ctypes import *

class struct_timespec(Structure):
    _fields_ = [('tv_sec', c_long), ('tv_nsec', c_long)]

class struct_stat64(Structure):
    _fields_ = [
        ('st_dev', c_int32),
        ('st_mode', c_uint16),
        ('st_nlink', c_uint16),
        ('st_ino', c_uint64),
        ('st_uid', c_uint32),
        ('st_gid', c_uint32),
        ('st_rdev', c_int32),
        ('st_atimespec', struct_timespec),
        ('st_mtimespec', struct_timespec),
        ('st_ctimespec', struct_timespec),
        ('st_birthtimespec', struct_timespec),
        ('dont_care', c_uint64 * 8)
    ]

libc = CDLL('libc.dylib') # or /usr/lib/libc.dylib
stat64 = libc.stat64
stat64.argtypes = [c_char_p, POINTER(struct_stat64)]

def get_creation_time(path):
    buf = struct_stat64()
    rv = stat64(path, pointer(buf))
    if rv != 0:
        raise OSError("Couldn't stat file %r" % path)
    return buf.st_birthtimespec.tv_sec

rawDescription: Get file creation time with Python on Mac


code: service_ids = [service.service_id for service in list_services if service.name == 'compute']

rawDescription: Check for particular value from class object and get the value of another key


code:
from django.template import Library

register = Library()

@register.assignment_tag(takes_context=True)
def show_photo(context):
    request = context['request']
    profile = context['profile']
    return profile.show_photo(request) # Instead of passing request I suggest to pass request.user here

rawDescription: Django request.user in model self function


code:
from django.core.cache import cache

cached = cache.get('temp_entries')
if cached:
    result = cached
else:
    result = Temp_entry.objects.filter(sensor=49).order_by('dateTime').reverse().values_list()[:300]
    cache.set('temp_entries', result, 60*20)  # 20 min

rawDescription: Improving performance of django DB query


code:
from PIL import Image

im = Image.new("RGB", (128, 128))
pix = im.load()
for x in range(128):
    for y in range(128):
        pix[x,y] = (255,0,0)

im.save("test.png", "PNG")

rawDescription: Creating image through input pixel values with the Python Imaging Library (PIL)


rawDescription: Is there a way to delist a list in python?


code:
def foo():
    return 2
print(foo)
print(foo())

rawDescription: Passing function returns as method parameters in Python


rawDescription: Selecting elements in an array based on what column and row they are in in order to complete a loop in python


rawDescription: Change stride of numpy array (altering data)


code:
import numpy as np
from pprint import pprint
A = np.array([1, 2, 3, 4])
f1 = open("log1.txt", 'w')
f2 = open("log2.txt", 'w')
n = 2
for i in range(n):
    f1.write(u'\u27A4 - %s\n'.encode('utf-8') % str(i))
    A = A + 1
    f1.writelines(list(u'    \u27B3 - %s\n'.encode('utf-8') % i for i in A))
    pprint(globals(), f2)
f1.close()
f2.close()
f1 = open("log1.txt", 'r')
f2 = open("log2.txt", 'r')
f = open("log.txt", 'w')
f.write(f1.read())
f.write(f2.read())
f.close()

rawDescription: How to pprint globals() in a loop (that has another write log command) at end of file?

description: Pprint globals() in a loop (that has another write log command) at end of file


code:
from django.utils.timezone import utc

datestr = "2013-12-12"
expireDate = datetime.strptime(datestr, "%Y-%m-%d")
datamodel.time = expireDate.replace(tzinfo=utc)
datamodel.save()

rawDescription: Datetime string doesn't match after strftime() and strptime()


code: [exchange_dict[x.strip()] for x in inp.split(',')]

rawDescription: Input points to certain elements in a list of tuples


code:
class Solver:
  def solve(self, x,y): return "eeeek, not implemented"

class Solver1:
  def solve(self, x,y): return x+y

def main(x, y, obj):
  return obj.solve(x,y)**2

main(3, 5, Solver1())

rawDescription: Assign a numeric value that is returned from a function by using exec command


code:
import wx

class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        text = wx.StaticText(self, label="hello, world!")
        button = wx.Button(self, label="press me")
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(text, flag=wx.ALL, border=20)
        sizer.Add(button, flag=wx.ALL, border=20)

        self.SetSizer(sizer)
        self.Layout()
        self.Show(True)
        self.Bind(wx.EVT_BUTTON, self.on_button, button)

    def on_button(self, event):
        wx.MessageBox("Hey!")

if __name__ == "__main__":
    app = wx.App(False)
    f = MyFrame()

rawDescription: Coming from a Visual C# Express IDE/C# programming background, is there a tutorial for creating python applications?


rawDescription: How to set offset with matplotlib

description: Set offset with matplotlib


code:
import numpy as N
import matplotlib.colors as colors

test2 = N.array([100, 10, 95])
norm = colors.Normalize(0,100)
for pix in N.nditer(test2, op_flags=['readwrite']):
    val = (norm(pix))
    print (val)

img = norm(test2)
print(img)

rawDescription: Matplotlib (Python) normalizing data

description: Matplotlib (Python) normalizing data


code: aceptar = Button(root,text="Calcular", command=lambda: my_function(arg1, arg2))

rawDescription: How to call a parametized function with Tkinter in Python?

description: Call a parametized function with Tkinter in Python


code: queue.put((ue9ipAddr, reading))

rawDescription: Identifying queue returns from Python script that uses threading and queue modules


code:
import Image

# open the input image
input_img = Image.open('input.png')

# open gradient image and resize to 256px height
gradient_img = Image.open('gradient.png')
gradient_img = gradient_img.resize( (gradient_img.size[0], 256,) )

# get pixel access object (significantly quicker than getpixel method)
gradient_pix = gradient_img.load()

data = input_img.getdata()
input_img.putdata([gradient_pix[0, r] for (r, g, b, a) in data])
input_img.save('output.png')

rawDescription: Converting an ImageMagick FX operator to pure Python code with PIL


rawDescription: Scrapy hxs.select() not selecting all results


code:
def negativeNumAvg(values):
    x = []
    average = 0

    for i in values:
        if i < 0:
            x.append(i)
    average = sum(x) / len(x)

    return average

rawDescription: Trying to learn how to python have, I am curious about appeand and dictionaries...am i doing this correctly?


code:
global globalList
globalList = []
class MyList():
    def __init__(self):
        self._myList = [1, 2, 3]

    @property
    def myList(self):
        return self._myList + globalList
    @myList.setter
    def myList(self, val):
        self._myList = val

    def append(self, val):
        self.myList = self.myList + [val]
        return self.myList

    def extend(self, val):
        return self.myList.extend(val)

mL1 = MyList()
print("myList: ", mL1.myList)
mL1.append(4)
print("after appending a 4, myList: ", mL1.myList)
mL1.myList.extend([5,6,"eight","IX"])
print("after extend, myList: ", mL1.myList)

rawDescription: Python decorating property setter with list


code:
mu = r_mean/(p*rule)
std = r_vol/rule/np.sqrt(p)

rawDescription: Numpy - Matrix Generation from list comprehension


rawDescription: Resampling OHLC tick data and filling gaps in Pandas


code:
from collections import Counter
def merge(a,b):
  na, nb = Counter(a), Counter(b)
  return list(Counter({k: max((na[k], nb[k])) for k in set(a + b)}).elements())
merge([1, 2, 2, 2, 3], [2, 5, 6])
merge([1, 2, 3], [2, 2, 4])

rawDescription: Union of two lists in Python

description: Union of two lists in Python


code: np.all(np.array([i.property for i in np.nditer(array[2::2,2::2])]) == property_state)

rawDescription: List of objects: how to extract attributes from a particular region or slice?


code:
for row in matrix:
    print(' '.join(row))

rawDescription: Removing brackets and quotes from matrix in python


rawDescription: SQLAlchemy, programmatically check argument


code:
soco[soco['city'] == "LARKFIELD"].city.count()
soco['city2'] = soco.city.str.strip()
soco[soco['city2'] == "LARKFIELD"].city.count()

rawDescription: Leading or trailing whitespace and pandas value_counts vs boolean selection


code:
def getText(self):
    text = QtWidgets.QInputDialog.getText(self, 'Text Input Dialog', 'Enter your name:')
    if text[1]:
        username = text[0]
        print(username)

rawDescription: link QInputDialog text to a variable

description: Link QInputDialog text to a variable


code:
import tokenize
import io
import token
import collections
import keyword

kwset = set(keyword.kwlist)
class Token(collections.namedtuple('Token', 'num val start end line')):
    @property
    def name(self):
        return token.tok_name[self.num]

source = '''
C = A+B
D = C * 4
'''

lastname = None
names = set()
not_dep = set()
for tok in tokenize.generate_tokens(io.BytesIO(source).readline):
    tok = Token(*tok)
    print(tok.name, tok.val)
    if tok.name == 'NAME':
        names.add(tok.val)
        lastname = tok.val
    if tok.name == 'OP' and tok.val == '=':
        not_dep.add(lastname)

print(names)
# set(['A', 'C', 'B', 'D'])
print(not_dep)
# set(['C', 'D'])

deps = dict.fromkeys(names - not_dep - kwset, 1)
print(deps)
# {'A': 1, 'B': 1}

rawDescription: Find dependencies in a python source/script


code:
def aggregate_flights(flights):
    last_id,start,end = None,None,None
    for row in flights:
        if row[-2] != last_id and last_id is not None:
            yield (last_id,(start,end))
            start,end = None,None
        if start is None:
            start = row[3]
        last_id = row[-2]
        end = row[4]
    yield (last_id,(start,end))

rawDescription: Find first and last list within a list with a matching property


code:
result = df.groupby(level=0)['AssociateID'].apply(
    lambda grp: pd.Series(1, index=grp.str.split(',').tolist()))
result.index.names = ['IndexBudgetCode', 'AssociateID']
result = result.reset_index(['AssociateID'])
result = result[['AssociateID']]

rawDescription: Duplicate a list in a Pandas Dataframe into a new row


code:
listofnames = ['alice', 'bob', 'charlie', 'dan']
listofnumberofpancakes = [1,2,3,3]

top_eaters = []
for i, pcakes in enumerate(listofnumberofpancakes):
    if pcakes == max(listofnumberofpancakes):
        top_eaters += [listofnames[i]]

bottom_feeders = [] # get it?  it ryhmes with... nevermind
for i, pcakes in enumerate(listofnumberofpancakes):
    if pcakes == min(listofnumberofpancakes):
        bottom_feeders += [listofnames[i]]

print("The max of pancakes eaten by a person was: ", max(listofnumberofpancakes))
print("The minimum of pancakes eaten by a person was: ", min(listofnumberofpancakes))
print(' and '.join(top_eaters), "ate the most pancakes")
print(' and '.join(bottom_feeders), "ate the least pancakes")

rawDescription: Python using multiple index's of a list to find multiple values


code:
{
    "_id" : ObjectId("545dad3562fa028fb48832f0"),
    "key" : "123456",
    "members" : [
            {
                    "name" : "Shiva",
                    "country" : "India",
                    "profession" : "Software"
            },
            {
                    "name" : "anil",
                    "country" : "India",
                    "profession" : "Software"
            }
    ]
}

rawDescription: How to get matched sub documents from mongodb?

description: Get matched sub documents from mongodb


code:
if isinstance(some_object, basestring):
    ...
elif all(isinstance(item, basestring) for item in some_object): # check iterable for stringness of all items. Will raise TypeError if some_object is not iterable
    ...
else:
    raise TypeError # or something along that line

rawDescription: Check if input is a list/tuple of strings or a single string


rawDescription: Interpreting 5bit subsets within Packed Binary Data Python


rawDescription: 'leet' program - getting all permutations


code:
cmap = matplotlib.cm.coolwarm
cnorm=matplotlib.colors.Normalize(cmap,clip=False)
cmap.set_under(color=cmap(0.0),alpha=1.0)
cmap.set_over(color=cmap(1.0),alpha=1.0)

rawDescription: Color differences between contour and contourf in matplotlib


code:
import re

keyword = 'user'
newuser = 'PeterB'
pattern = re.compile(r'({}\s+)(\S+)'.format(keyword))

with open('test.txt') as infile, open('updated.txt', 'w') as outfile:
    for line in infile:
        outfile.write(pattern.sub(r'\1{}'.format(newuser), line))

rawDescription: Change log file with index

description: Change log file with index


code: parent_dir_path = os.path.join(current_directory, '..')

rawDescription: Include entire directory in python setup.py data_files


code:
parent = dialog
for widget in parent.children():
    if isinstance(widget, QPushButton):
        widget.toggled.connect(self.buttonChecked)

rawDescription: Big number of pushbuttons and smart checking which is checked


code:
with open('xyz.txt', 'w') as fp:
    fp.writelines([ each_line + '\n' for each_line in ['line_1','line_2','line_3']])

rawDescription: Python, Writing Multiple Lines

description: Python, Writing Multiple Lines


rawDescription: How to prevent numbers being changed to exponential form in Python matplotlib figure

description: Prevent numbers being changed to exponential form in Python matplotlib figure


code: obj1, obj2, obj3 = ndb.get_multi([key1, key2, key3])

rawDescription: ndb.get_multi() returning null entities

description: Ndb.get_multi() returning null entities


code:
from random import Random
random = Random(666)
assert random.randint(0, 1000) == 467  # will never break

rawDescription: How to validate a unit test with random values

description: Validate a unit test with random values


code:
x['unexpected'] = 'something else'
print(x['unexpected'])

rawDescription: What is the overhead of using a dictionary instead of a list?


rawDescription: Finding the Index of a character within a string


code:
class YourModelForm(forms.ModelForm):
    class Meta:
        model = YourModel
        fields = ['textA', 'textB']
        ...

rawDescription: django how to insert a textbox input to sqlite database?

description: Django how to insert a textbox input to sqlite database


code:
with codecs.open('Geotweets.csv',mode='w', encoding='utf-8',errors='replace') as cache:
    writer = csv.DictWriter(cache, ["text", "area", "date", "id"])
    for tweet in datares['results']:
        writer.writerow(tweet)

rawDescription: Formatting data returned from twitter api utilizing python in a csv file?


rawDescription: Convert a single string formatted as a csv file into a pandas dataframe


code:
def __add__(self, other):
    '''Add counts from two counters.

    >>> Counter('abbb') + Counter('bcc')
    Counter({'b': 4, 'c': 2, 'a': 1})

    '''
    if not isinstance(other, Counter):
        return NotImplemented
    result = Counter()
    for elem, count in self.items():
        newcount = count + other[elem]
        if newcount > 0:
            result[elem] = newcount
    for elem, count in other.items():
        if elem not in self and count > 0:
            result[elem] = count
    return result

rawDescription: Adding counters deletes keys

description: Adding counters deletes keys


code:
with open('wordlist.txt') as wlist:
    words = [w.strip() for w in wlist]

with open('output.txt', 'r') as output:
    seen = {w.strip() for w in output}

with open('output.txt', 'a') as output:
    count = 0
    while count < 12:
        new_word = random.choice(words)
        if new_word in seen:
            words.remove(new_word)
            continue
        seen.add(new_word)
        output.write(new_word + '\n')
        count += 1

rawDescription: Python: compare two text files for same random lines


code: sum(i**2 for i in lst)

rawDescription: sum squared values in FreqDist, python

description: Sum squared values in FreqDist, python


rawDescription: Python - string replacement, re.match and re.sub in a single operation (replace a char if at end of a string)


code:
LoT=[('/home/simon/Desktop/Windows.edb.export', [], ['MSysUnicodeFixupVer2.2', 'SystemIndex_0P.6', 'SystemIndex_0A.7', 'SystemIndex_GthrPth.5', 'SystemIndex_Gthr.4', 'MSysObjects.0', '__NameTable__.3', 'MSysObjectsShadow.1'])]

path, dirs, files=LoT[0]
path
dirs
files

rawDescription: Python: filter on a list returning empty list


code:
class Potato(object):

    def spam(self, n):
        return self.foo(n=n)

    def foo(self, n):
        return self.bar(n)

    def bar(self, n):
        return n + 2

class PotatoTest(TestCase):

    def test_something(self):
        spud = Potato()
        with patch.object(Potato, 'foo', wraps=spud.foo) as mock:
            forty_two = spud.spam(n=40)
            mock.assert_called_once_with(n=40)
        self.assertEqual(forty_two, 42)

rawDescription: python mock - patching a method without obstructing implementation

description: Python mock - patching a method without obstructing implementation


code:
import pylab as plt

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(212)

ax.plot(range(3))

ax_im = fig.add_subplot(211)
ax_im.plot(range(3), 'o--')
ax_im.set_xticks([])
ax_im.set_yticks([])

plt.show()

rawDescription: Saving matplotlib figure with add_axes

description: Saving matplotlib figure with add_axes


rawDescription: Populating list with images in PYQT

description: Populating list with images in PYQT


code: d_inShot.set_async(h_inShot.astype(np.uint16), stream = strm2)

rawDescription: Returning to host code in pyCUDA after asynchronous kernel launch


rawDescription: Copying the contents of a variable to the clipboard


code:
def gen(parameter):
    while more_sets():
        # ... some code to generate the next set 'x'
        yield x

with open("results", "wt") as f_results:
    for i in combinations(gen("data"), 2):
        inter = i[0] & i[1]
        f_results.write("%d\n" % len(inter))

rawDescription: Python: Fast extraction of intersections among all possible 2-combinations in a large number of lists


code:
from datetime import timedelta
from django.utils.timezone import now

def has_won_any_game_since(user, period):
    return Winner.objects.filter(user=user, win_date__gt=now() - period).exists()

def get_random_winner():
    player_list = list(Participant.objects.all())
    four_months = timedelta(days=120) # ~4 months

    while len(player_list) > 0:
        player = random.choice(player_list)
        if not has_won_any_game_since(player.user, four_months):
            return player
        else:
            player_list.remove(player)
    else:
        return None

rawDescription: python django continous checking for validation of user and date

description: Python django continous checking for validation of user and date


code:
@receiver(pre_save, sender=ContactDetail)
def set_object_to_super(sender, **kwargs):
    obj = kwargs['instance']
    c_obj = obj.content_object
    parents = c_obj._meta.get_parent_list() # Beware: This is a set, not a list!

    if len(parents) == 0:
        # If no parents, its a base class
        return
    elif len(parents) == 1:
        # If only one parent, get that from the object
        parent = list(parents)[0]
        obj.content_object = getattr(c_obj, '%s_ptr'%parent._meta.model_name)
    else:
        # Here's where it gets tricky, there are two or more base classes
        # You, dear reader, will need to figure out which to use!
        # Remember, you can only have one.
        pass

rawDescription: Saving a generic relation to a parent class


code:
import gtk
import gobject
import pango
import os
from subprocess import Popen, PIPE
import fcntl

wnd = gtk.Window()
wnd.set_default_size(400, 400)
wnd.connect("destroy", gtk.main_quit)
textview = gtk.TextView()
fontdesc = pango.FontDescription("monospace")
textview.modify_font(fontdesc)
scroll = gtk.ScrolledWindow()
scroll.add(textview)
exp = gtk.Expander("Details")
exp.add(scroll)
wnd.add(exp)
wnd.show_all()
sub_proc = Popen("ping -c 10 localhost", stdout=PIPE, shell=True)
sub_outp = ""

def non_block_read(output):
    fd = output.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    try:
        return output.read()
    except:
        return ''

def update_terminal():
    textview.get_buffer().insert_at_cursor(non_block_read(sub_proc.stdout))
    return sub_proc.poll() is None

gobject.timeout_add(100, update_terminal)
gtk.main()

rawDescription: Show terminal output in a gui window using python Gtk


rawDescription: Python 2D table lookup by labels

description: Python 2D table lookup by labels


code:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.offsetbox as offsetbox
custom_preamble = {
    "text.usetex": True,
    "text.latex.preamble": [
        r"\usepackage{amsmath}", # for the align enivironment
        ],
    }
plt.rcParams.update(custom_preamble)

# Figure top-level container. Weird size is because
# this is part of a larger code.
fig = plt.figure(figsize=(30, 25))
gs = gridspec.GridSpec(10, 12)
ax_t = plt.subplot(gs[4:6, 10:12])

# Some mock values.
cp_r = [0.001, 8.3, 0.18, 15.2, 5000, 0.3]
cp_e = [0.0005, 0.2, 0.11, 0.3, 200, 0.1]

# Remove axis from frame.
ax_t.axis('off')

# Text lines.
text1 = r'\begin{align*} '
text2 = r'y &= ' + str(cp_r[0]) + '\pm ' + str(cp_e[0]) + '\\\\'
text3 = r'\log(ret) &= ' + str(cp_r[1]) + '\pm ' + str(cp_e[1]) + '\\\\'
text4 = r'A_{{(B-C)}} &= ' + str(cp_r[2]) + '\pm ' + str(cp_e[2]) + '\\\\'
text5 = r'(n-N)_o &= ' + str(cp_r[3]) + '\pm ' + str(cp_e[3]) + '\\\\'
text6 = r'K_{{\odot}} &= ' + str(cp_r[4]) + '\pm ' + str(cp_e[4]) + '\\\\'
text7 = r'd_{{frac}} &= ' + str(cp_r[5]) + '\pm ' + str(cp_e[5])
text8 = r'\end{align*}'
text = text1 + text2 + text3 + text4 + text5 + text6 + text7 + text8

# Draw text box.
ob = offsetbox.AnchoredText(text, pad=1, loc=6, prop=dict(size=13))
ob.patch.set(alpha=0.85)
ax_t.add_artist(ob)

plt.savefig('out.png', dpi=300)

rawDescription: Align LaTeX math text in matplotlib text box


rawDescription: Python: different behavior using gc module in interactive mode


code:
runs = 10
inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55)
results = {}

for run in range(runs):
    for i in inputs:
        results.setdefault(i,[]).append(benchmark(i))

rawDescription: How do I create a unique value for each key using dict.fromkeys?

description: Create a unique value for each key using dict.fromkeys


rawDescription: How to load all cPickle dumps from a log file?

description: Load all cPickle dumps from a log file


code:
s = "cat goose  mouse horse pig cat cow"
re.sub(r'^((.*?cat.*?){1})cat', r'\1Bull', s)

rawDescription: How to find and replace nth occurence of word in a sentence using python regular expression?

description: Find and replace nth occurence of word in a sentence using python regular expression


code:
data = []
for line in open('input.txt'):
    items = line.rstrip('\r\n').split('\t')   # strip new-line characters and split on column delimiter
    items = [item.strip() for item in items]  # strip extra whitespace off data items
    data.append(items)

rawDescription: Python - file contents to nested list

description: Python - file contents to nested list


rawDescription: Pyparsing CSV string with random quotes

description: Pyparsing CSV string with random quotes


code:
p = principal()
s = principal.secondary(p)

rawDescription: How can I acess a metod from an object inside a class in python 2.6?

description: Acess a metod from an object inside a class in python 2.6


code:
import locale
locale.setlocale(locale.LC_ALL, 'en_US.utf8')
locale.format("%.2f", 100028282.23, grouping=True)

rawDescription: Convert float to comma-separated string

description: Convert float to comma-separated string


code: Track.objects.filter(Q(genre__genre__in=['Rock', 'Pop']) | Q(genre__parent__genre__in=['Rock', 'Pop'])).distinct()

rawDescription: Django Many-to-many query fulfilling a specific condition


code:
def find1(adict, key):
    if isinstance(adict, dict):
        if key in adict.keys():
            return adict[key]
        for ndict in adict.values():
            x = find1(ndict, key)
            if x: return x
    else:
        return None

rawDescription: json parser in python

description: Json parser in python


code:
df
inds = df.values.argsort(1)
inds

rawDescription: `pandas.DataFrame.apply` in a row by row operation


code:
def lowest_price(store_dict):
    retlist = []
    for k,v in store_dict.items():
        if len(v) > 0:
            retlist.append((k,min(v)))
        else:
            retlist.append((k,False))
    return retlist

rawDescription: dictionary to list of tuples with smallest value

description: Dictionary to list of tuples with smallest value


code:
latex_preamble = r"""
% ...

\setcounter{tocdepth}{5}
\setcounter{secnumdepth}{5}

% ...
"""

rawDescription: sphinx latexpdf: chapter number only for 3 levels

description: Sphinx latexpdf: chapter number only for 3 levels


code: [[os.path.join(path, 'list%d'%l1_index, l2_value) for l2_value in l2[l1_index]] for l1_index in l1]

rawDescription: Creating nested lists with a list comprehension


code:
from Tkinter import *

#------------------------------------

def my_validater():
    new_text = e1.get() + e2.get()

    # different method to set label text (without StringVar)
    #t['text'] = new_text
    t.config(text=new_text)

    # validater have to return True or False
    return True

#------------------------------------

top = Tk()

#---

t = Label(top)
t.pack()

#---

e1 = Entry(top, validate='key', validatecommand=my_validater) # validate every key
e1.pack()

#---

e2 = Entry(top, validate='key', validatecommand=my_validater) # validate every key
e2.pack()

#---

top.mainloop()

#------------------------------------

rawDescription: Constantly Update Label Widgets From Entry Widgets TKinter


code:
import multiprocessing
import numpy as np
import thread

class Sum: #again, this class is from ParallelPython's example code (I modified for an array and added comments)
    def __init__(self):
        self.value = np.zeros((1,512*512)) #this is the initialization of the sum
        self.lock = thread.allocate_lock()
        self.count = 0

    def add(self,value):
        self.count += 1
        self.lock.acquire() #lock so sum is correct if two processes return at same time
        self.value += value #the actual summation
        self.lock.release()

def computation(index):
    array1 = np.ones((1,512*512))*index #this is where the array-returning computation goes
    return array1

def summers(num_iters):
    pool = multiprocessing.Pool(processes=8)

    sumArr = Sum() #create an instance of callback class and zero the sum
    for index in range(num_iters):
        singlepoolresult = pool.apply_async(computation,(index,),callback=sumArr.add)

    pool.close()
    pool.join() #waits for all the processes to finish

    return sumArr.value

rawDescription: How to parallelize a sum calculation in python numpy?

description: Parallelize a sum calculation in python numpy


code:
import numpy as np
np.random.choice(4, 1000, p=[0.1, 0.2, 0.3, 0.4])

rawDescription: Pythonic way to select list elements with different probability


rawDescription: get div from HTML with Python

description: Get div from HTML with Python


rawDescription: Python BeautifulSoup find span inside class


code:
img = Image.open('./urban-dove-gray.jpg')
pix = img.load()
pix[0,0]

rawDescription: Converting list to numpy array issues

description: Converting list to numpy array issues


code:
portstr = "tcp:8080:interface=localhost" # serve on localhost:8080

if __name__ == '__main__': # $ python proxy_modify_request.py
    import sys
    from twisted.internet import endpoints, reactor

    def shutdown(reason, reactor, stopping=[]):
        """Stop the reactor."""
        if stopping: return
        stopping.append(True)
        if reason:
            log.msg(reason.value)
        reactor.callWhenRunning(reactor.stop)

    log.startLogging(sys.stdout)
    endpoint = endpoints.serverFromString(reactor, portstr)
    d = endpoint.listen(ProxyFactory())
    d.addErrback(shutdown, reactor)
    reactor.run()
else: # $ twistd -ny proxy_modify_request.py
    from twisted.application import service, strports

    application = service.Application("proxy_modify_request")
    strports.service(portstr, ProxyFactory()).setServiceParent(application)

rawDescription: Python - Twisted, Proxy and modifying content


rawDescription: Pyparsing strings where the order is unknown and some items may be missing


code: "SELECT * FROM tbl_subscriber LIMIT %d,%d;" % (actualLimit,steps)

rawDescription: Best way to iterate through all rows in a DB-table

description: Iterate through all rows in a DB-table


code:
from pylab import hist, show

x = [1.1]*29 + [2]*7 + [3.2]*3 + [5]
hist(x)
show()

rawDescription: How to change ticks on a histogram? (matplotlib)

description: Change ticks on a histogram? (matplotlib)


rawDescription: How to sort python dictionary based on similar values and keys?

description: Sort python dictionary based on similar values and keys


code: host = result.hostname or result.path.rpartition('@')[-1]

rawDescription: What's the pythonic way to parse such a URI 'foo://user:pass@host:port' into proper variables?


code:
def square(n):
    return n * n

rawDescription: How can I pass functions or operators as arguments to a function in Python?

description: Pass functions or operators as arguments to a function in Python


code:
def probDoseLevel2(orgVox,level=None):
    relevantRows = voxMapBeamlet[orgVox]

    # Dense column matrix of row sums
    voxDose2 = relevantRows.sum(axis=1)
    if level is None:
        level = voxDose2.sum()/len(orgVox)
    return (voxDose2 <= level).sum() / len(orgVox)

rawDescription: Accessing a large number of unsorted array elements in Python


code:
app.menu = [
    [rumps.MenuItem("About", icon='pony.jpg', dimensions=(18, 18)),
    [rumps.MenuItem("About Me"), rumps.MenuItem("About Project"),
    rumps.MenuItem("etc...")]],
    None,
    rumps.MenuItem('Preferences')
]

rawDescription: Creating Sub Menu for Menu item using Rumps python on Mac OS


code: print('\n'.join(map(lambda x: '* ' * x, range(5))))

rawDescription: How to ignore the next line in python

description: Ignore the next line in python


rawDescription: Going through all folders in Python

description: Going through all folders in Python


code:
#you might need to easy_install this
import json

def your_view(request):
    # You can dump a lot of structured data into a json object, such as
    # lists and touples
    json_data = json.dumps({"HTTPRESPONSE":1})
    # json data is just a JSON string now.
    return HttpResponse(json_data, mimetype="application/json")

rawDescription: How to use JQuery and Django (ajax + HttpResponse)?

description: Use JQuery and Django (ajax + HttpResponse)


code:
class ChessBoard(object):
  def __init__(self):
    self.squares = [None] * 64

  def __setitem__(self, key, value):
    row, col = key
    self.squares[row*8 + col] = value

  def __getitem__(self, key):
    row, col = key
    return self.squares[row*8 + col]

rawDescription: Returning an lvalue from a function in python


code:
for letter in sorted(count):
    print(letter, count[letter])

rawDescription: Count number of occurrences of a character in a string


rawDescription: Is there a way to generate a list of indices using numpy


code: dict(([] if ":" in pair else ["keyword"]) + pair.split(":") for pair in text.split())

rawDescription: python how to parse "user:12345 location:ny search"

description: Python how to parse "user:12345 location:ny search"


code:
with open('data.txt') as f:
    data = f.read()

v = []
# Split the string into blocks, by looking for duplicated line terminaters ('\n\n').
for i, block in enumerate(data.split('\n\n')):
    # Split the blocks in lines by looking for line terminaters ('\n').
    lines = block.split('\n')
    v.append([])
    for line in lines:
        if line == "":
            continue
        v[i] += [line.split(' ')]

# Take the middle block and transpose it.
v1 = map(list, zip(*v[1]))

rawDescription: Reading columns between empty lines

description: Reading columns between empty lines


code: API_LIMIT_PER_PAGE = 0

rawDescription: Disable pagination in Django tastypie?

description: Disable pagination in Django tastypie


code: [x for x in input("Enter numbers: ").split(' ') if x]

rawDescription: Input List - Double/Triple Digits

description: Input List - Double/Triple Digits


code:
class SpecResource(ModelResource):
    results = fields.ToManyField('(...).ResultResource', attribute=lambda bundle: filter_result_items(bundle), full=True)

rawDescription: Tastypie: Filtering by ToManyField

description: Tastypie: Filtering by ToManyField


code:
[letters[start:start+l+1]
 for l in range(len(letters))[::-1]
 for start in xrange(len(letters)-l)]

[['A', 'I', 'R'], ['A', 'I'], ['I', 'R'], ['A'], ['I'], ['R']]

rawDescription: How do I get ALL Combination of Sequential elements of list Pythonically?

description: Get ALL Combination of Sequential elements of list Pythonically


code: g = df.groupby('key1')

rawDescription: Python Pandas Conditional Sums

description: Python Pandas Conditional Sums


rawDescription: Python: adding strings from one list into a second list, themselves inside lists


code:
import math
def function(x, A, B):
    return math.exp(A*x) * math.sin(B*x)

rawDescription: Python - Plot function over a range PYPLOT


rawDescription: Iterating a function over the RGB values of individual pixels


code:
n = 1024
a = np.arange(n)
m = 8
b = a.reshape((a.shape[0]/m, m))
b.mean(axis=1)

rawDescription: Making time bins bigger in a large dataset with python


code:
def convert(d):
    return dict((key, convert(value)) for (key,value) in d.iteritems()) if isinstance(d, defaultdict) else d

rawDescription: Structuring Plain Text to JSON

description: Structuring Plain Text to JSON


rawDescription: Insert elements to beginning and end of numpy array


code:
def dispatch(name, *args, **kwargs):
    func_name_dict[name](*args, **kwargs)

rawDescription: python: dispatch method with string input

description: Python: dispatch method with string input


code: callPrintValue(printValue, "Value to pass to printValue")

rawDescription: How to pass a method that receives parameters as a parameter of another function in Python

description: Pass a method that receives parameters as a parameter of another function in Python


code: actor = next((actor for actor in self.actors if actor.name==actorName), None)

rawDescription: Alternative to list comprehension if there will be only one result


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import random
def box():
    startbox = 0
    allcards = 0
    cards = [1,2,3,4,5,6,7,8,9,10]
    curcards = []
    while True:
        randomn = random.randrange(0,10)
        allcards = allcards+1
        if str(cards[randomn]) not in curcards:
            cards[randomn]
            startbox = startbox + 1
            curcards.append(str(cards[randomn]))
        if len(curcards) == 10:
            break
    return 'Boxes to buy: ' + str(startbox) + ' Cards Found: ' + '; '.join(curcards) + ' Total amount of cards: ' + str(allcards)

#print box()
box()

rawDescription: How to use an array to keep track of different numbers?

description: Use an array to keep track of different numbers


code:
class Earthquake(object):

    ...

    @classmethod
    def from_string(cls, strline):
        return cls(*myfunc(strline))

rawDescription: How to introduce the attributes of an object in python by calling a method in __init__ method?

description: Introduce the attributes of an object in python by calling a method in __init__ method


code:
import codecs
codecs.decode('\\n\\x21', 'unicode_escape')

rawDescription: Python Replace \\ with \

description: Python Replace \\ with \


code:
from collections import defaultdict, Counter

new_dict = {}
for key, values in Dict.iteritems():
    counts = Counter()
    for color, _, count in values:
        counts[color] += count
    new_dict[key] = counts.items()

rawDescription: Sum Values in a Dictionary w/ respect to the Key - Python 2.7


rawDescription: What is the most Pythonic way to test for match with first item of tuple in sequence of 2-tuples?


code:
def allglob(args):
    return itertools.chain.from_iterable(map(glob.iglob, args))

rawDescription: List of files (which might contain wildcards) as arguments of a Python script


code:
def strokesort(agegrp, gender):
    lst = []
    lst.append(whatever)
    return lst

rawDescription: create variable names based on function arguments? Python

description: Create variable names based on function arguments? Python


code:
import timeit
import operator
import numpy as np
import scipy.ndimage.filters as filters
import matplotlib.pyplot as plt

data  = np.array([
    [0,1,2,3,4,7,6,7,8,9,10],
    [3,3,3,4,7,7,7,8,11,12,11],
    [3,3,3,5,7,7,7,9,11,11,11],
    [3,4,3,6,7,7,7,10,11,11,11],
    [4,5,6,7,7,9,10,11,11,11,11]
    ])

data = np.tile(data, (50,50))

def using_filters(data):
    return np.where(np.logical_and.reduce(
        [data == f(data, footprint=np.ones((3,3)), mode='constant', cval=np.inf)
         for f in (filters.maximum_filter, filters.minimum_filter)]))

def using_eight_shifts(data):
    h, w = data.shape
    data2 = np.empty((h+2, w+2))
    data2[(0,-1),:] = np.nan
    data2[:,(0,-1)] = np.nan
    data2[1:1+h,1:1+w] = data

    result = np.where(np.logical_and.reduce([
        (data2[i:i+h,j:j+w] == data)
        for i in range(3)
        for j in range(3)
        if not (i==1 and j==1)]))
    return result

def using_quadratic_loop(data):
    return np.array([[i,j]
            for i in range(1,np.shape(data)[0]-1)
            for j in range(1,np.shape(data)[1]-1)
            if np.all(data[i-1:i+2,j-1:j+2]==data[i,j])]).T

np.testing.assert_equal(using_quadratic_loop(data), using_filters(data))
np.testing.assert_equal(using_eight_shifts(data), using_filters(data))

timing = dict()
for f in ('using_filters', 'using_eight_shifts', 'using_quadratic_loop'):
    timing[f] = timeit.timeit('{f}(data)'.format(f=f),
                              'from __main__ import data, {f}'.format(f=f),
                              number=10)

for f, t in sorted(timing.items(), key=operator.itemgetter(1)):
    print('{f:25}: {t:.3f}'.format(f=f, t=t))

rawDescription: Retrieve position of elements with setting some criteria in numpy


code:
# Typically, transposition will change the order for
# efficiency reasons: no need to change the data !
n = np.random.random((2, 2, 2)).transpose()
n.flags.f_contiguous
n.flags.c_contiguous
x, y, z = np.unravel_index([1,2,3,7], (2, 2, 2), order='F')

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

description: Find the indices of a vectorised matrix numpy


code:
def tuple_list_additions(xs,ys):
  return [y for y in ys if y[0] not in [x[0] for x in xs]]

def dict_additions(xs,ys):
  return {k:ys[k] for k in ys.keys() - xs.keys()}

rawDescription: python compare difference between two lists

description: Python compare difference between two lists


code: line = '''<div class='entry qual-5 used-demoman slot-head bestprice custom' data-price='3280000' data-name="Kill-a-Watt Allbrero" data-quality="5" data-australium="normal" data-class="demoman" data-particle_effect="56" data-paint="" data-slot="cosmetic" data-consignment="consignment">'''

rawDescription: Writing from one file to another python

description: Writing from one file to another python


code:
possible_strings = set()
for row in mydata:
   for item in row:
       possible_string.add(item[0])

rawDescription: find difference between lists and append difference to lists, but for 40 different lists - python

description: Find difference between lists and append difference to lists, but for 40 different lists - python


code:
import re
re.split('[-:]', a)

rawDescription: How to split a string based on either a colon or a hyphen?

description: Split a string based on either a colon or a hyphen


code:
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
auth = OAuth1(API_KEY, API_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
requests.get(url, auth=auth)

rawDescription: How to perform oauth when doing twitter scrapping with python requests

description: Perform oauth when doing twitter scrapping with python requests


code:
objects_list =  list(Person.objects.values())
modified_list = [{"name":x["name"], "male": int(x["male"])} for x in objects_list] # use list comprehension
json.dumps(modified_list)

rawDescription: Django model.BooleanField as 0/1

description: Django model.BooleanField as 0/1


rawDescription: Convert list of positions [4, 1, 2] of arbitrary length to an index for a nested list


code: document.getElementById('<the id of your checkbox here>').disabled = true;

rawDescription: making form elements disappear with javascript

description: Making form elements disappear with javascript


code:
foo = "Hello, this is the string I want, blabla"
foo.split(',')
foo.split(',')[1]

rawDescription: Best way to find strings between two points

description: Find strings between two points


code: zip(dir(), [eval(var) for var in dir()])[-4:]

rawDescription: How to print all variables values when debugging Python with pdb, without specifying each variable?

description: Print all variables values when debugging Python with pdb, without specifying each variable


code: ['abc' + str(x) for x in range(1, 6)]

rawDescription: Repeat a string with a subscript over a given range in python


rawDescription: Django -- How to filter objects with an "author" from a set of "authors"(users)?


code:
from django.conf import settings
from django.template import TemplateDoesNotExist
from django.template.loader import BaseLoader
from django.utils._os import safe_join
import os

class MvcTemplateLoader(BaseLoader):
    "A custom template loader for the MVCEngine framework."

    is_usable = True

    __view_paths = None

    def __init__(self, views_path):
        self.views_path = views_path
        # We only need to instantiate the view_paths class variable once.
        if MvcTemplateLoader.__view_paths is None:
            temp_paths = []
            for each_path in os.listdir(views_path):
                # We want to skip hidden directories, so avoid anything that starts with .
                # This works on both Windows and *NIX, but could it fail for other OS's?
                if not each_path.startswith('.'):
                    full_path = os.path.join(views_path, each_path)
                    if each_path == "shared":
                        # The shared directory is special. Since templates in many other directories will be
                        # inheriting from or including templates there, it should come second, right after the
                        # root views directory. For now, it will be first.
                        temp_paths.insert(0, full_path)
                    else:
                        temp_paths.append(full_path)
            # The root views_path itself will always be first in order to give resolution precendence to templates
            # that are specified with a parent directory. In other words, home/index.html will be immediately
            # resolved with no ambiguity; whereas, index.html could resolve as bar/index.html rather than
            # foo/index.html.
            temp_paths.insert(0, views_path)
            MvcTemplateLoader.__view_paths = temp_paths

    def get_template_sources(self, template_name):
        for template_dir in MvcTemplateLoader.__view_paths:
            try:
                yield safe_join(template_dir, template_name)
            except UnicodeDecodeError:
                # The template dir name was a bytestring that wasn't valid UTF-8.
                raise
            except ValueError:
                # The joined path was located outside of this particular
                # template_dir (it might be inside another one, so this isn't
                # fatal).
                pass

    def load_template_source(self, template_name, template_dirs=None):
        tried = []
        for filepath in self.get_template_sources(template_name):
            try:
                file = open(filepath)
                try:
                    return (file.read().decode(settings.FILE_CHARSET), filepath)
                finally:
                    file.close()
            except IOError:
                tried.append(filepath)

        error_msg = "Could not find %s in any of the views subdirectories." % template_name
        raise TemplateDoesNotExist(error_msg)
    load_template_source.is_usable = True

_loader = MvcTemplateLoader

rawDescription: TemplateDoesNotExist on python app-engine django 1.2 while template rendering relative paths


code:
for k, v in periods.items():
    df['periods'] = np.where(((v[0].hour <= df.t.apply(lambda x: x.hour)) & (df.t.apply(lambda x: x.hour) <= v[1].hour)), k, 'unknown_period')

rawDescription: Bin timestamp into custom periods

description: Bin timestamp into custom periods


code:
if list_of_ids:
    results = models.Object.query.filter(models.Object.id.in_(list_of_ids)).paginate(page, 10, False)
else:
    results = models.Object.query.filter_by(id=-1).paginate()

rawDescription: empty paginate object sqlalchemy

description: Empty paginate object sqlalchemy


code: image = image.astype(np.uint8)

rawDescription: python make RGB image from 3 float32 numpy arrays

description: Python make RGB image from 3 float32 numpy arrays


code:
class TaskThread(object):
    def __call__(self):
        print("in TaskThread.__call__")

pool=multiprocessing.Pool(4)
task=TaskThread()
pool.apply_async(task)
pool.close()
pool.join()

rawDescription: Is it possible to apply a callable object to a pool of processes?


code:
from skimage.util import view_as_windows

def with_strides(img, kernel_min, kernel_max):
    win_w, win_h = kernel_min.shape
    heatmap = np.zeros(img.shape, dtype='uint16')
    target = heatmap[win_h//2:-win_h//2+1, win_w//2:-win_w//2+1]

    windowed = view_as_windows(img, (win_h, win_w))
    mask = ((kernel_min <= windowed) & (windowed <= kernel_max))
    np.sum(mask, axis=(2,3), out=target)

    return heatmap

rawDescription: Numpy custom moving window count cells in range


code:
#!/usr/bin/env python
import ntpath
import os
import shutil
import sys

def normalize(path):
    path = path.strip()
    path = ntpath.splitdrive(path)[1].lstrip("\\/") # remove C:\ or C:/
    return path.replace("\\", "/").lower()

# get non-blank lines and normalize paths
with open(sys.argv[1]) as pathfile:
    paths = set(filter(bool, map(normalize, pathfile)))

# find the paths in the source directory tree & copy them to the destination
src_dir = "/mnt/filesystem/"        # where to copy from
assert src_dir.endswith(os.path.sep) # needed for `path[len(src_dir):]` below
dest_dir = "/destination/directory" # where to copy to
for root, dirs, files in os.walk(src_dir): # traverse directory tree
    for filename in files:
        path = os.path.join(root, filename)
        normalized_path = path[len(src_dir):].lower()
        if normalized_path in paths: # path is from pathfile.txt
           shutil.copy(path, dest_dir) # copy
           paths.remove(normalized_path)
           if not paths: # no more paths to copy
              sys.exit()

rawDescription: Copy files based on path from file

description: Copy files based on path from file


code:
if (cond1 == 'val1' and cond2 == 'val2' and
       cond3 == 'val3' and cond4 == 'val4'):
    do_something

rawDescription: Python style: multiple-line conditions in IFs


code:
import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate
tck,u = interpolate.splprep([x,y],s=3)
unew = np.arange(0,1.01,0.01)
out = interpolate.splev(unew,tck)
plt.figure()
plt.plot(x,y,out[0],out[1])
plt.show()

rawDescription: Approximating data with a multi segment cubic bezier curve and a distance as well as a curvature contraint


code: make

rawDescription: Building SimpleITK with CMake for Python 3


code: cur.execute('SELECT * FROM table1 WHERE column = ?;', (42,))

rawDescription: Python: Passing a cursor back from a class for a dbi instance


code:
listA = [[2,3,-7,-4], [-2,3,4,-5], [-5,-6,-8,2], [9,5,13,2]]
means = [np.mean([el for el in sublist if el < 0] or 0) for sublist in listA]
print(means)

rawDescription: python mean of list of lists

description: Python mean of list of lists


code:
from BeautifulSoup import BeautifulSoup
import urllib2
import re

url="http://m.harveynorman.com.au/tv-audio/portable-audio/ipods"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
A = soup.findAll('strong',{'class':'name fn'})[0]
print(A.renderContents())

rawDescription: Data extraction from webpage by beatifulsoup python


code:
for datetime_string, num in df['<date_column>', '<num_column>']:
    date = datetime_string.split()[0]
    d = dict(pos=num) if num > 0 else dict(neg=num)
    date_counts[date].update(d)

rawDescription: Compress time into day-format and count based on other column


code: self.t0 = Label(frame, fg="blue", textvariable=self.temp0,font=(20)).grid(row=2, column=0)

rawDescription: How to alter attributes in Tkinter

description: Alter attributes in Tkinter


code:
import wx
import wx.grid as gridlib
# import  pyodbc

class RightPanel(wx.Panel):
    """"""

    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)

        grid = gridlib.Grid(self)
        grid.CreateGrid(5, 5)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(grid, 0, wx.EXPAND)
        self.SetSizer(sizer)

class LeftPanel(wx.Panel):
    """"""

    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)

        self.create_controls()
        self.SetBackgroundColour("light green")

    def create_controls(self):

        self.h_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.v_sizer = wx.BoxSizer(wx.VERTICAL)

        self.button = wx.Button(self, label="Press me!")

        self.v_sizer.Add(self.button, 0)

        self.v_sizer.Add(self.h_sizer, 0, wx.EXPAND)
        self.SetSizer(self.v_sizer)

class MyForm(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "DB Viewer", size=(350, 250))

        splitter = wx.SplitterWindow(self)
        leftP = LeftPanel(splitter)
        self.rightP = RightPanel(splitter)

        splitter.SplitVertically(leftP, self.rightP)
        splitter.SetMinimumPaneSize(20)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(splitter, 1, wx.EXPAND)
        self.SetSizer(sizer)

        leftP.button.Bind(wx.EVT_BUTTON, self.on_button_pressed)

        self.Layout()

    def on_button_pressed(self, event):
            self.rightP.SetBackgroundColour("light blue")
            self.Refresh()

if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()

rawDescription: wx.Python: Passing control between multiple panels

description: Wx.Python: Passing control between multiple panels


code: W = tf.constant(embedding, name="W")

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


code: np.apply_along_axis(mahalanobis_sqdist, 1, d1, mean1, Sig1)

rawDescription: python-numpy: Apply a function to each row of a ndarray

description: Python-numpy: Apply a function to each row of a ndarray


code:
keywords = ['Hello', 'world', 'meow']
sql = "SELECT ... WHERE lexicon.word IN (" + ",".join(["?"] * len(keywords)) + ")"
db.execute(sql, keywords)

rawDescription: Using a Variable Number of WHERE Clauses to Match an Arbitrary Number of Keywords pysqlite


rawDescription: How can I make a "tuple of an ndarray of ndarrays"?

description: Make a "tuple of an ndarray of ndarrays"


code:
class Property(models.Model):
    # *Your codes here*

    # *define new method*
    def get_city(self):
        return self.location.city()

rawDescription: django model for city and places

description: Django model for city and places


code: data = np.loadtxt("data.txt", delimiter=",", dtype=np.object)

rawDescription: Read in csv file with one column of strings in the middle


code: [('To', 'sleep'), ('sleep', 'perchance'), ('perchance', 'to'), ('to', 'dream')]

rawDescription: Pythonic way of getting all consecutive 2-tuples from list


code:
def upvote(request, photo_id):
    photo = Photo.objects.get(pk=photo_id)
    photo.score += 1
    photo.save()
    return HttpResponse('your-photo-list-view')

rawDescription: Adding 'vote' buttons to django objects

description: Adding 'vote' buttons to django objects


code:
from IPython.lib import inputhook
inputhook.set_inputhook(app.step)

rawDescription: IPython iterate main loop manually?

description: IPython iterate main loop manually


rawDescription: Python: list directory using user input as directory name not working


code: sorted_objects = sorted(objdict, key=lambda k: k['thing1'])

rawDescription: Sorting a list with dictionaries, django


rawDescription: How to check if file already exists, if not, download on Python?

description: Check if file already exists, if not, download on Python


code:
def _date_created(self, obj):
    return obj.date_created.strftime('%m/%d/%Y')
_date_created.short_description = "Date Created"
_date_created.admin_order_field = 'date_created'

rawDescription: How can I rename a column label in Django Admin for a field that is a method//property?

description: Rename a column label in Django Admin for a field that is a method//property


code: codes = sorted([ d['code'] for d in L ])

rawDescription: How to create list based on elements from dictionary?

description: Create list based on elements from dictionary


code:
from django.conf.urls import patterns
from django.contrib.auth.decorators import login_required
from myapp.views import MyView

urlpatterns = patterns('',
    (r'^about/', login_required(MyView.as_view())),
)

rawDescription: How to apply decorator do dispatch method in class-based views Django

description: Apply decorator do dispatch method in class-based views Django


code:
old_a = a
a = b
b = old_a + b

rawDescription: Fibonacci sequence python

description: Fibonacci sequence python


code:
import matplotlib.pyplot as plt
from matplotlib.dates import datetime as dt
from matplotlib.dates import DateFormatter

formatter = DateFormatter('%m-%d')

f = plt.figure()
ax = f.add_subplot(111)

raw_dates = ["2013-08-30 13:33:11", "2013-08-29 13:33:11", "2013-08-28 13:33:11"]
x = [dt.datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in raw_dates]
y = [125, 120, 112]
ax.plot(x, y)

ax.xaxis.set_major_formatter(formatter)
plt.show()

rawDescription: Matplotlib - How to convert dates from SQLite to matplotlib firmat?


code: ddy = splev(X, tck, der=2)

rawDescription: Peak curvature in Scipy spline

description: Peak curvature in Scipy spline


code: e = root.xpath('.//a[starts-with(text(),"TEXT A")]')

rawDescription: How to use lxml to find an element by text?

description: Use lxml to find an element by text


code:
from twisted.internet import reactor

class MessageReverser(object):
    """
    Accept messages, reverse them, and send them onwards.
    """
    def __init__(self, server):
        self.server = server

    def messageReceived(self, message):
        """
        Callback invoked whenever a message is received.  This implementation
        will reverse and re-send the message.
        """
        self.server.sendMessage(message[::-1])
        doSomeOtherLogic()

def main():
    twistedServer = ...
    twistedServer.start(MessageReverser(twistedServer))
    reactor.run()

main()

rawDescription: Pattern for a background Twisted server that fills an incoming message queue and empties an outgoing message queue?


code: list('abc')

rawDescription: splitting and concatenating a string

description: Splitting and concatenating a string


rawDescription: Multidimensional Enumeration, how to avoid Code Macro Generation


code: [l[i:i+4] for i in range(0,len(l)-len(l)%4,3)]

rawDescription: Iterate with last element repeated as first in next iteration


code:
# access elements one by one
gen = f()
one_value = next(gen)

# convert the generator to a list
all_values = list(f())

rawDescription: Optional yield or return in python3. How to?


code:
import shlex
shlex.split('cat /etc/hosts | grep hostname')

rawDescription: Python resolve shell backquoted string

description: Python resolve shell backquoted string


code: res = [sum(ai) for ai in arra]

rawDescription: Iterating and selecting a specific array from a multidimensional array in Python


code:
lst = [1, 2, 3, 4, 5, 6]
filtered = filter(lambda x: x < 5, lst)

rawDescription: Python equivalent of Ruby's .select

description: Python equivalent of Ruby's .select


code: import myfunkymodule

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


code:
for d in d_list:
    histogram[d['age']] += 1

rawDescription: python: creating histogram out of dictionary

description: Python: creating histogram out of dictionary


code:
from string import maketrans
table = maketrans('{}', '()')
[x if isinstance(x, tuple) else (x,) for x in literal_eval(s.translate(table))]

rawDescription: Pythonic way to parse preflib Orders with Ties files


rawDescription: Iterating nested list inside-out

description: Iterating nested list inside-out


code: d.isoformat(' ')

rawDescription: Date formate conversion in Python

description: Date formate conversion in Python


code:
for link in soup.find_all("td")[:-4]:
    print(link.string)

rawDescription: BeautifulSoup find_all <td>'s except last four ones


code:
attributes = {'name': 'Hello'}
add(**attributes)

rawDescription: Dynamically add keyword arguments

description: Dynamically add keyword arguments


code:
from itertools import izip, islice
[[(x+y)*.5  for x,y in izip(*item)] for item in izip(alist, islice(alist,1,None))]

rawDescription: Create a list where each element is a created based on the index of a nested list in python


code:
d = np.nonzero(boo != np.roll(boo, 1))[0]
if d[0] == 0:
    d = d[1:]
b = np.split(a, d)
b = b[0::2] if boo[0] else b[1::2]

rawDescription: Splitting numpy array according bool

description: Splitting numpy array according bool


rawDescription: Initializing numpy masked array from Python int list with None values


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

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


code:
mpl_packages = [
    'Building Matplotlib',
    setupext.Matplotlib(),
    setupext.Python(),
    setupext.Platform(),
    'Required dependencies and extensions',
    setupext.Numpy(),
    setupext.Dateutil(),
    setupext.FuncTools32(),
    setupext.Pytz(),
    setupext.Cycler(),
    setupext.Tornado(),
    setupext.Pyparsing(),
    setupext.LibAgg(),
    setupext.FreeType(),
    setupext.FT2Font(),
    setupext.Png(),
    setupext.Qhull(),
    setupext.Image(),
    setupext.TTConv(),
    setupext.Path(),
    setupext.ContourLegacy(),
    setupext.Contour(),
    setupext.Delaunay(),
    setupext.QhullWrap(),
    setupext.Tri(),
    setupext.Externals(),
    'Optional subpackages',
    setupext.SampleData(),
    setupext.Toolkits(),
    setupext.Tests(),
    setupext.Toolkits_Tests(),
    'Optional backend extensions',
    # These backends are listed in order of preference, the first
    # being the most preferred.  The first one that looks like it will
    # work will be selected as the default backend.
    setupext.BackendMacOSX(),
    setupext.BackendQt5(),
    setupext.BackendQt4(),
    setupext.BackendGtk3Agg(),
    setupext.BackendGtk3Cairo(),
    setupext.BackendGtkAgg(),
    setupext.BackendTkAgg(),
    setupext.BackendWxAgg(),
    setupext.BackendGtk(),
    setupext.BackendAgg(),
    setupext.BackendCairo(),
    setupext.Windowing(),
    'Optional LaTeX dependencies',
    setupext.DviPng(),
    setupext.Ghostscript(),
    setupext.LaTeX(),
    setupext.PdfToPs(),
    'Optional package data',
    setupext.Dlls(),
    ]

rawDescription: How to know the enabled features of a matplotlib installation?

description: Know the enabled features of a matplotlib installation


code:
shapes = pd.read_csv('shapes.csv')

def f(df):
    return [df.shape_pt_sequence.tolist(), [df.shape_pt_lat.tolist(), df.shape_pt_lon.tolist()]]

res = shapes.groupby("shape_id").apply(f).to_dict()

rawDescription: Breaking down large dataset into organized index


code:
my_switch('1')
my_switch('not a key')

rawDescription: Simple C code in python --- switch statement


code:
def schema(x):
    return 1 if x == 'M' else 2

rawDescription: Return function value to range argument step


code:
_, inv_idx, counts = np.unique(a, return_inverse=True, return_counts=True)
out = counts[inv_idx]

rawDescription: How to count num of elements vector with numpy python

description: Count num of elements vector with numpy python


code:
class MyClass(metaclass=MyTypeSubclass):
    pass

rawDescription: Python builtin functions aren't really functions, right?


code: houses = {col: {row: House(row, col) for row in range(GRIDHEIGHT)} for col in range(GRIDWIDTH)}

rawDescription: Iterating through instances of a class by instance attribute


rawDescription: Dictionary as value in dictionary

description: Dictionary as value in dictionary


code:
@decorator_expr
def decorated_func():
    pass

rawDescription: Decorated function along with original, without having to re-write the function


code:
my_dict = {'a':1, 'b':2, 'c': 3, 'd':4}
my_dict['total'] = sum([value for value in my_dict.values()])
my_dict

rawDescription: Accessing dictionary key values within the same dictionary


rawDescription: Can I change function parameters when passing them as variables?

description: Change function parameters when passing them as variables


code: new_list = [[b for _,b in sub] for sub in mx]

rawDescription: How to convert sparse matrix to dense form using python

description: Convert sparse matrix to dense form using python


rawDescription: new python pandas dataframe column based on value of variable, using function

description: New python pandas dataframe column based on value of variable, using function


code:
with open('/tmp/out.txt', 'wt') as outfile:
    for key,value in final_data:
        outfile.write("{} - {}\n".format(key,value))

rawDescription: Python: reading txt file containing (alphabet and number) and updating the number


rawDescription: Using Apache-Spark to analyze time series


code: move.cursor(100, 100)

rawDescription: Moving the cursor in Mac OS X (in Python and/or R)


code: setBtn = wx.Button(self, label="Set", name="SetX")

rawDescription: Generate wxPython widget groups from lists


code:
def gen(n, k):
    for indices in itertools.combinations(range(n), k):
        # each one of indices can be -1 or +1
        for i in range(len(indices) + 1):
            for neg_indices in itertools.combinations(indices, i):
                l = [0] * n
                for i in indices:
                    l[i] = 1
                for i in neg_indices:
                    l[i] = -1
                yield(l)

rawDescription: How to generate these vectors quickly in Python?

description: Generate these vectors quickly in Python


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

npoints = 1000
x, y = np.random.normal(10, 2, (2, npoints))

fig, ax = plt.subplots()
artist = ax.hexbin(x, y, gridsize=20, cmap='gray_r', edgecolor='white')

# Create the inset axes and use it for the colorbar.
cax = fig.add_axes([0.8, 0.15, 0.05, 0.3])
cbar = fig.colorbar(artist, cax=cax)

plt.show()

rawDescription: Add axis to colorbar in python matplotlib


code:
try:
    mean = a.mean
except AttributeError:
    return _wrapit(a, 'mean', axis, dtype, out)
return mean(axis, dtype, out)

rawDescription: np.mean() vs np.average() in Python NumPy?

description: Np.mean() vs np.average() in Python NumPy


code:
import re
sample = '''\
/team/Croatia/Euro_2012
/team/Netherlands/Euro_2012
/team/Netherlands/WC2014
'''
re.findall(r'/team/.*?/Euro_2012', sample)
re.findall(r'/team/[\w\d%.~+-/]*?/Euro_2012', sample)

rawDescription: Using regex to find a string starting with /team/ and ending with /Euro_2012


code: sort2.reset_index(0, drop=True)

rawDescription: Pandas sort by group aggregate and column


code:
import os
type(os)
os
hasattr(os, 'sep')
hasattr(os, 'foobar')

rawDescription: Can hasattr work on a Module?

description: Can hasattr work on a Module


code:
#TODO: change user agent string
hdr = { 'User-Agent' : 'super happy flair bot by /u/spladug' }
req = urllib2.Request(url, headers=hdr)
html = urllib2.urlopen(req).read()

rawDescription: urllib2 HTTP error 429

description: Urllib2 HTTP error 429


code:
def item_completed(self, results, item, info):
    if self.IMAGES_RESULT_FIELD in item.fields:
        item[self.IMAGES_RESULT_FIELD] = [x for ok, x in results if ok]
    return item

rawDescription: How to download scrapy images in a dyanmic folder

description: Download scrapy images in a dyanmic folder


rawDescription: Gradient calculation with python

description: Gradient calculation with python


rawDescription: repeating a function in python (2.7)

description: Repeating a function in python (2.7)


code:
def is2To4Numbers(q):
    try:
        return 10 <= int(q) <= 9999
    except:
        return False

rawDescription: Digit or Number limit with exact match on Python Regex


rawDescription: How to take out the column index name in dataframe

description: Take out the column index name in dataframe


code: ADD_SUBDIRECTORY( "MyProj/" )

rawDescription: Integrate non-C++ subprojects into CMake project


code:
file_content = '\n'.join(iter(raw_input, ''))
f.write(file_content)

rawDescription: Writing multiple lines to a textfile by taking input in python?


rawDescription: Sorting data in a .csv by month and year and calculating the mean


rawDescription: How to build an undo storage with limit?

description: Build an undo storage with limit


rawDescription: checking to see if same value in two lists

description: Checking to see if same value in two lists


code:
msg = "kalhfdlakdhhhhhhhhhfklajdf"
reps = []
for i in range(len(msg)-1):
    if msg[i] == msg[i + 1]:
        reps.append(msg[i])

reps

rawDescription: Longest repeating substring using for-loops and if-statements


code: "abcd"

rawDescription: Need help understanding a recursive solution to reverse a List


rawDescription: Implementing a bit-swap hack in Python

description: Implementing a bit-swap hack in Python


rawDescription: Python sorting a list of pairs

description: Python sorting a list of pairs


code:
picwiz = r.db(self.PROJECT_DB).table(self.PROJECT_TABLE_PICWIZ)
picwiz.filter(lambda doc: r.expr(following).contains(doc['username']))\
  .limit(5)\
  .run(self.db_connection)

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


code: majority_x, majority_y = x[y == 0, :], y[y == 0]

rawDescription: random subsampling of the majority class

description: Random subsampling of the majority class


code:
class SuchAndSuch(object):
    @classmethod
    def update(cls):
        pass # do stuff

rawDescription: How do I use a method outside a class?

description: Use a method outside a class


code:
['productG', 'productF', 'productE', 'productH']
['productD', 'productC', 'productB', 'productA']

rawDescription: An algorithm to create clusters from data pairs in python


rawDescription: I am using a numpy array of randomly generated ordered pairs, I need to determin if the ordered pairs are different types of triangles


code:
def searcher(s):
    if COMPILED_REGEXP_OBJECT.search(s):
        return s

matching_strings = filter(searcher, YOUR_LIST_OF_STRING)

rawDescription: Searching list of strings using regular expressions in python


code:
try:
  from threading import local
except ImportError:
  from django.utils._threading_local import local

_thread_locals = local()
def get_current_user():
  return getattr(_thread_locals, 'user', None)

class ThreadLocals(object):
  """Middleware that gets various objects from the request object and
  saves them in thread local storage."""

  def process_request(self, request):
    _thread_locals.user = getattr(request, 'user', None)

rawDescription: How do I set up add, delete, update and view permissions for a particular model instance?

description: Set up add, delete, update and view permissions for a particular model instance


code: points = zip(x_list, y_list)

rawDescription: Deleting elements from numpy or list in python


rawDescription: keep tabs after .split()

description: Keep tabs after .split()


code:
A
B

rawDescription: Getting the index of pandas dataframe for matching row values


rawDescription: Why python's monkeypatch doesn't work when importing a class instead of a module?


code:
np.packbits((x > 0).astype('i1')).tostring()
bin(0xe0)

rawDescription: Converting positive and negative values to a bitstring using numpy.clip


code:
def fst(ID):
    return FirstClass(ID)

rawDescription: How to create cross-module, on-thy-fly variable name in python?

description: Create cross-module, on-thy-fly variable name in python


code:
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords

# Full list of stop words from nltk
#stop_words = set(stopwords.words('english'))

stop_words = set(['hello', 'there', 'been'])

with open('input.txt','rU') as f_input, open('output.txt', 'w') as f_output:
    for line in f_input:
        line_words = set(word_tokenize(line))
        stop_words_present = line_words & stop_words

        if stop_words_present:
            print("Yes: '{}' contains {}".format(line.strip(), stop_words_present))     # Contains at least one stop word
        else:
            print("No:", line.strip())      # Contains non stop stops
            f_output.write(line)

rawDescription: How to delete a particular sentence from a file using line number in Python

description: Delete a particular sentence from a file using line number in Python


code:
sess = cherrypy.session
sess['_cp_username'] = None

rawDescription: I am struggling to understand sessions in CherryPy


code:
f = [None, function1, function2, function3, ...]
for f in f_list[start:]:
    f()

rawDescription: How to start at a specific step in a script?

description: Start at a specific step in a script


code:
import time
time.__file__

rawDescription: Windows Service relative path issue in Python


code:
import pandas as pd
df = pd.read_csv(r'C:\Users\user\Documents\file.csv')

rawDescription: How to calculate a new field in python using a linear relationship

description: Calculate a new field in python using a linear relationship


code:
idata = iter(data)
[myfunc(a, b) for a, b in izip(idata, idata)]

rawDescription: Perform an action over 2 and 2 elements in a list


rawDescription: Get minimum value of masked array

description: Get minimum value of masked array


code:
plt.xlim(0, 3)
plt.ylim(0, 2)

rawDescription: Adding extra contour lines using matplotlib 2D contour plotting


rawDescription: Why do I need to pass an object to this class to make it work?


code:
class Foo(object):
    def run_expression(self):
        return eval(self.expression, vars(self))

f = Foo()
f.a = 2
f.b = 3
f.expression = 'a + b'
f.run_expression()

rawDescription: python class with user defined expressions executed at runtime

description: Python class with user defined expressions executed at runtime


code:
m = create_autospec(A)
m.__add__ = Mock()

rawDescription: Unable to mock __subclasses__ in python

description: Unable to mock __subclasses__ in python


code:
from PyQt4 import QtGui
app = QtGui.QApplication([])
class MyList(QtGui.QListWidget):
    def mouseReleaseEvent(self, e):
        super(MyList, self).mouseReleaseEvent(e)
        print('released', e)

l = MyList()
l.addItems(['hello', 'world'])
l.show()

rawDescription: PyQt4: emit signal when mouse is released anywhere on the screen


rawDescription: Is there a way to get the username of the currently authenticated user in python Bottle using basic_auth?


code:
class AnimatedWidget(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)

        color1 = QtGui.QColor(255, 0, 0)
        color2 = QtGui.QColor(0, 255, 0)

        self.color_anim = QtCore.QPropertyAnimation(self, 'backColor')
        self.color_anim.setStartValue(color1)
        self.color_anim.setKeyValueAt(0.5, color2)
        self.color_anim.setEndValue(color1)
        self.color_anim.setDuration(1000)
        self.color_anim.setLoopCount(-1)
        self.color_anim.start()

    def getBackColor(self):
        return self.palette().color(QtGui.QPalette.Background)

    def setBackColor(self, color):
        pal = self.palette()
        pal.setColor(QtGui.QPalette.Background, color)
        self.setPalette(pal)

    backColor = QtCore.pyqtProperty(QtGui.QColor, getBackColor, setBackColor)

rawDescription: Blinking Widget with PyQt

description: Blinking Widget with PyQt


code:
foo = (
    "this text will be "
    "joined into one long string. "
    "Note that I don't need to concatenate these "
    "explictly. No newlines are included\n"
    "unless you insert them explicitly."
)

rawDescription: String Concatenation: Putting large chuck of text in Python code


rawDescription: Find common rows of 2 dataframe for 2 columns


rawDescription: Select certain dates from Pandas dataframe


code:
#!/usr/bin/env python3

# Declare itself as package if needed
if __name__ == '__main__' and __package__ is None:
    import os, sys, importlib
    parent_dir = os.path.abspath(os.path.dirname(__file__))
    sys.path.append(os.path.dirname(parent_dir))
    __package__ = os.path.basename(parent_dir)
    importlib.import_module(__package__)

# Continue with your code
do_things()

rawDescription: How to debug a python module that needs to be executed with -m?

description: Debug a python module that needs to be executed with -m


rawDescription: How to reverse sub arrays in numpy?

description: Reverse sub arrays in numpy


rawDescription: how to sort python dict by its value?

description: Sort python dict by its value


code: fmin = np.minimum(f1, f2); fmax = np.maximum(f1, f2)

rawDescription: Is there a faster way to separate the minimum and maximum of two arrays?


code:
if fill_value is not None:
    table = table.fillna(value=fill_value, downcast='infer')

rawDescription: Pandas Pivot table converts float to int


code:
from System.IO import *
from Spotfire.Dxp.Application.Visuals import VisualContent
from System.Drawing import Bitmap, Graphics, Rectangle, Point
import clr
clr.AddReference("Microsoft.Office.Interop.PowerPoint")
import Microsoft.Office.Interop.PowerPoint as PowerPoint

powerpoint = PowerPoint.ApplicationClass()
powerpoint.Visible = True
pres=powerpoint.Presentations.Add()
slideCounter = 1

for visual in Document.ActivePageReference.Visuals:
    #print visual.Title

    #export graphic to temp file
    vc = visual.As[VisualContent]()
    bm = Bitmap(2000, 1200)
    g = Graphics.FromImage(bm)
    r = Rectangle(Point(0,0), bm.Size)
    vc.Render(g, r)
    file = Path.GetTempFileName()
    bm.Save(file)

    #pp setup
    slide=pres.Slides.Add(slideCounter, PowerPoint.PpSlideLayout.ppLayoutTitleOnly)
    slideCounter = slideCounter+1
    slide.Shapes.AddPicture((file), False, True, 30, 60, 650, 400)
    title=slide.Shapes.Title
    txt=slide.Shapes.AddTextBox(1,10,500,500,100)
    title.Top=0.1
    obj=slide.Shapes.Title.TextFrame.TextRange
    obj.Font.Size=24

rawDescription: Script to Export Spotfire Graphic to PowerPoint


code:
def find_random_pattern(theme):
    found_lines = []
    pattern = open('poempatterns.txt','r')
    for line in pattern:
        # Call strip() just in case you have some blank spaces or \n at the end
        found = re.findall(".*theme=%s.*" % theme, line.strip())
        for match in found:
            found_lines.append(line)

    selectedline = random.choice(found_lines)
    return selectedline

rawDescription: re.findall() doesn't matches with it's finding

description: Re.findall() doesn't matches with it's finding


code:
from itertools import chain as ch, ifilter as ifil, imap
from os import path, listdir

files = list(ch.from_iterable(imap(listdir, ifil(path.isdir, ('dir1', 'dir', 'dir3')))))

rawDescription: One-liner to get flat list of files from a list of possible directories?


code:
def __get__(self, obj, objtype):
    """Support instance methods."""
    if obj is None:
        return self.func
    else:
        return functools.partial(self.__call__, obj)

rawDescription: How do I get the arguments for any python method?

description: Get the arguments for any python method


code:
# print out some test values
for test in (0,20,100,700):
    print (test, lookup[test])

rawDescription: Parse HTML Table with Python BeautifulSoup


code:
import re
s = "You would like to eat salad as meal 1 and fruits as meal 2 and pizza as meal 3 in your diet."

s = re.sub(r'(\d+)', lambda match: str(int(match.group()) + 1), s)
print(s)
# You would like to eat salad as meal 2 and fruits as meal 3 and pizza as meal 4 in your diet.

rawDescription: incrementing the digit by 1 in python using isdigit()

description: Incrementing the digit by 1 in python using isdigit()


code:
s = ':foo [bar]'
s.split()
[word.strip(':[]') for word in s.split()]

rawDescription: Split string without non-characters

description: Split string without non-characters


code:
# convert signal strength
data[:,-1]= 10**(data[:,-1]/10.)

rawDescription: Searching a list of 3 lists for equivalence of 2 lists and averaging all the values in the 3rd list where list 1 and 2 are equal (Python)


code:
# Note: the lower limit is inclusive while the upper limit is exclusive
x = np.random.randint(-5, 6, size=(5, 5))

rawDescription: Python numpy bool masks for absoluting values


code:
import numpy as np
from scipy.sparse import csr_matrix

def compute_M(data):
    cols = np.arange(data.size)
    return csr_matrix((cols, (data.ravel(), cols)),
                      shape=(data.max() + 1, data.size))

def get_indices_sparse(data):
    M = compute_M(data)
    return [np.unravel_index(row.data, data.shape) for row in M]

rawDescription: faster alternative to numpy.where?

description: Faster alternative to numpy.where


code:
someVarSetByBody = "This was set by the body"
Console.WriteLine("Body is loading")
myexecfile(r"..\..\IronPython\Header.py")
Console.WriteLine("Body has loaded")

rawDescription: IronPython 'execfile' Equivalent in C#

description: IronPython 'execfile' Equivalent in C#


code:
idx = np.concatenate([[0], 1+np.diff(g).nonzero()[0]])
np.maximum.reduceat(v, idx)

rawDescription: numpy, get maximum of subsets

description: Numpy, get maximum of subsets


code:
def get_element_by_tag(element, tag):
    if element.tag.endswith(tag):
        yield element
    for child in element:
        for g in get_element_by_tag(child, tag):
            yield g

rawDescription: Python: Ignore xmlns in elementtree.ElementTree


code:
lista = ['avispa', 'abeja', 'avestruz', 'ballena', 'bisonte', 'bullterrier']
for item in lista:
    if item.startswith("a"):
        print(item)

rawDescription: find items in a text file but show only those that begin with the input letters

description: Find items in a text file but show only those that begin with the input letters


code:
from collections import Counter
d = Counter({'0':3, '1':3, '2':4, '3':4, '4':4})
d
d.update(d.keys())
d

rawDescription: Adding a constant integer to a value in a python dictionary


rawDescription: Update certain elements in a list

description: Update certain elements in a list


code:
def my_view(request):
    image_url = get_face_recog(path, image_path)
    return render(request, 'mytemplate.html', {'image_url': image_url})

rawDescription: Call Python Function with Opencv in Django


code: page_titles = raw_input("Enter a list of page titles separated by commas: ").split(",")

rawDescription: get a list of comma separated values in python and use that list to perform a command as many times as necessary with each value

description: Get a list of comma separated values in python and use that list to perform a command as many times as necessary with each value


code:
A
setones_between_triggers(A,2,-2)

rawDescription: numpy array set ones between two values, fast

description: Numpy array set ones between two values, fast


code: l5 = map(lambda x: x * new_len / float(len(l)), l4)

rawDescription: python list average over bin sizes

description: Python list average over bin sizes


code:
cols = [1,2] # list all the columns you want here
with open('testfile') as f:
    split_lines = [line.split(';') for line in f]
    result = [[line[col] for col in cols] for line in split_lines]

result

rawDescription: Python : Alias in comprehensive list

description: Python : Alias in comprehensive list


code:
c2 = np.einsum('i,jk->ijk', a, b)
np.allclose(c2, a[:,None,None]*b)

rawDescription: How to make 1d array multiplied by 2d array resulting in 3d array for python

description: Make 1d array multiplied by 2d array resulting in 3d array for python


code:
from operator import itemgetter
children = itemgetter("children")
[k['id'] for i in some_tree for j in children(i) for k in children(j)]

rawDescription: Evective way of getting list from tree leafs in Python


code:
try:
    xxx
except:
    xxx

rawDescription: dict of dicts python

description: Dict of dicts python


code:
def get_a(**values):
    return values['a']

s = get_a(a=1, b=2)      # returns 1

rawDescription: What does the Star operator mean in Python?


code: numpy.random.random((3, 3))

rawDescription: Simple way to create matrix of random numbers


code:
import os
time = 10
os.system("shutdown /t %s " % time)
# `str` is not required, so removed.

rawDescription: How to shutdown windows 8 with python 2.7 using a timer

description: Shutdown windows 8 with python 2.7 using a timer


code:
#!/bin/env python

import sys

def main():
    data = sys.stdin.readlines()

    word_count = 0
    char_count = 0
    line_count = len(data)
    for l in data:
        linewords = l.split()
        word_count += len(linewords)
        for w in l:
            char_count += len(w)

    print("Lines:      %d" % line_count)
    print("Characters: %d" % char_count)
    print("Words:      %d" % word_count)

if __name__ == '__main__':
    main()

rawDescription: Preparing Python program to be run in UNIX enviroment


rawDescription: How to convert the following string to python date?

description: Convert the following string to python date


code:
class Address(db.EmbeddedDocument):
    city = db.StringField()
    suffix = db.StringField()
    street_name = db.StringField()
    zipcode = db.StringField()
    prefix = db.StringField()
    state = db.StringField()
    is_contracted = db.IntField()
    street_num = db.StringField()

    meta = {
        'allow_inheritance': False,
    }

class Buildings(db.Document):
    addresses = db.ListField(db.EmbeddedDocumentField(Address))
    created_at = db.DateTimeField(default=datetime.datetime.now)

    meta = {
        'allow_inheritance': False,
        'indexes': ['_id'],
        'ordering': ['-created_at'],
    }

rawDescription: Empty EmbeddedDocument field?

description: Empty EmbeddedDocument field


code: [Counter(x)[2] for x in a]

rawDescription: How to count occurrences of specific element for arrays in a list?

description: Count occurrences of specific element for arrays in a list


rawDescription: How to calculate netmask from 2 ip adresses in Python

description: Calculate netmask from 2 ip adresses in Python


code:
import numpy as np
import pandas as pd
# Create random data
rd = pd.DataFrame(np.random.randn(100, 10))
# Calculate all the desired values
df = pd.DataFrame({'mean': rd.mean(), 'median': rd.median(),
                   '25%': rd.quantile(0.25), '50%': rd.quantile(0.5),
                   '75%': rd.quantile(0.75)})
# And plot it
df.plot()

rawDescription: Plotting quantiles, median and spread using scipy and matplotlib


code:
def get_angle_plot(line1, line2, offset = 1, color = None, origin = [0,0], len_x_axis = 1, len_y_axis = 1):

    l1xy = line1.get_xydata()

    # Angle between line1 and x-axis
    slope1 = (l1xy[1][1] - l1xy[0][2]) / float(l1xy[1][0] - l1xy[0][0])
    angle1 = abs(math.degrees(math.atan(slope1))) # Taking only the positive angle

    l2xy = line2.get_xydata()

    # Angle between line2 and x-axis
    slope2 = (l2xy[1][3] - l2xy[0][4]) / float(l2xy[1][0] - l2xy[0][0])
    angle2 = abs(math.degrees(math.atan(slope2)))

    theta1 = min(angle1, angle2)
    theta2 = max(angle1, angle2)

    angle = theta2 - theta1

    if color is None:
        color = line1.get_color() # Uses the color of line 1 if color parameter is not passed.

    return Arc(origin, len_x_axis*offset, len_y_axis*offset, 0, theta1, theta2, color=color, label = str(angle)+u"\u00b0")

rawDescription: Best way to plot an angle between two lines in Matplotlib

description: Plot an angle between two lines in Matplotlib


code:
word_getter = operator.itemgetter(*nextWordIndices)
nextWord = word_getter(allWords)

rawDescription: optimized way to get values from list when list of indices given

description: Optimized way to get values from list when list of indices given


rawDescription: How to pass ET.dump() xml string from a Django view to a template -- python django ElementTree

description: Pass ET.dump() xml string from a Django view to a template -- python django ElementTree


code:
class X(object):
    x1 = 1

x = X()
x.x2 = 2
x.__dict__
x.x1
x.__dict__['x1']

rawDescription: using dict vs class __dict__ method to format strings

description: Using dict vs class __dict__ method to format strings


code:
#!/usr/bin/env python
from tkinter import *
import sys
import urllib.request
from urllib.request import urlopen
import base64
from bs4 import BeautifulSoup

class Weather(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.configure(bg = "#ededed")
        self.grid()
        self.heading = Label(self, bg = "#ededed", text = "       Temperature      ").grid(row = 0, column = 1, pady = 5)
        self.heading = Label(self, bg = "#ededed", text = "        Picture        ").grid(row = 0, column = 2, pady = 5)

        button = Button(self, bg = "#ededed", text = "Canberra", command = self.canberra_data).grid(row = 3, column = 0, sticky = EW)

        self.obsVar1 = StringVar()
        label = Label(self, textvariable = self.obsVar1, bg = "#e5e5e5", fg = "#751974").grid(row = 1, column = 1)
        self.obsVar1.set("")

    def canberra_data(self):
        soup = BeautifulSoup(urllib.request.urlopen("http://www.bom.gov.au/act/observations/canberra.shtml").read())
        table = soup.find("table", {"id" : "tCANBERRA"}).tbody("tr", "rowleftcolumn")
        for row in soup("th", {"id" : "obs-station-canberra"}):
            for temp in soup("td", {"headers" : "obs-temp obs-station-canberra"}):
               self.obsVar1.set(temp.text)

        raw_data = BeautifulSoup(urllib.request.urlopen("http://www.weather.com.au/act/canberra").read())
        image = raw_data("img", ("class", "si"))[0]
        image = image["src"]
        if image == ("/images/icons/5.gif"):
            URL = urllib.request.urlopen("http://www.weather.com.au/images/icons/5.gif").read()
            b64_data = base64.encodestring(URL)
            image = PhotoImage(data = b64_data)
            label = Label(self, image = image)
            label.image = image
            label.grid(row=1,column=2)

master = Tk()
master.title("Weather Program")
app = Weather(master)
master.mainloop()

rawDescription: TypeError: 'Weather' object is not callable


code:
string = 'I will be {} years and {} months on {month} {day}'
some_date = {'month': 'January', 'day': '1st'}
diff = [3, 11] # years, months
string.format(*diff, **some_date)

rawDescription: String formatting options: pros and cons


code:
import math
import matplotlib.pylab as plt

nrows = int(math.ceil(len(subsl) / 2.))

fig, axs = plt.subplots(nrows, 2)

ylim = 100000, 600000
for ax, subsm in zip(axs.flat, subsl):
    H7, subsm = sumsubdesc2(table, subsm)
    H7.plot(ax=ax, title='Rolling 4q mean %s' % subsm)
    ax.set_ylim(ylim)

rawDescription: Create subplots in Matplotlib in a loop?

description: Create subplots in Matplotlib in a loop


code:
v = (item for item in propadd if item[0]==row1[8] and harversine(custx,custy,item[2],item[3])<1500)
k = (item for item in custadd if item[0]==row1[4])
m = (item for item in numlist if re.search(r"^[0-9]+(?=\s)",row1[0]) is not None and item[0]==re.search(r"^[0-9]+(?=\s)",row1[0]).group())
extraValues = ('value 1', 'value 2', 'value3')
for ind, gen in enumerate((v, k, m)):
    l = list(gen)
    if len(l) == 1:
        row1[1] = l[0][1]
        row1[2] = l[0][2]
        row1[3] = extraValues[ind]
        break

rawDescription: Assign differing values to list generator results


code:
class Car:
    def __init__(self, color, make, model):
        self.color = color
        self.make = make
        self.model = model

    def __str__(self):
        return ' '.join((self.color, self.make, self.model))

rawDescription: Outputting object in Python using print

description: Outputting object in Python using print


code:
class redirect_output(object):
    """context manager for reditrecting stdout/err to files"""

    def __init__(self, stdout='', stderr=''):
        self.stdout = stdout
        self.stderr = stderr

    def __enter__(self):
        self.sys_stdout = sys.stdout
        self.sys_stderr = sys.stderr

        if self.stdout:
            sys.stdout = open(self.stdout, 'w')
        if self.stderr:
            if self.stderr == self.stdout:
                sys.stderr = sys.stdout
            else:
                sys.stderr = open(self.stderr, 'w')

    def __exit__(self, exc_type, exc_value, traceback):
        sys.stdout = self.sys_stdout
        sys.stderr = self.sys_stderr

rawDescription: IPython: redirecting output of a Python script to a file (like bash >)


code: CURRENT_ROOM = monkey_room

rawDescription: Python game logic

description: Python game logic


code:
from itertools import product

X = np.arange(15) # or whatever values for x
Y = np.arange(5)  # or whatever values for y
N, M = len(X), len(Y)
Z = np.zeros((N, M))
for i, (x,y) in enumerate(product(X,Y)):
    Z[np.unravel_index(i, (N,M))] = z([x,y])

rawDescription: Python & Matplotlib: How to create a meshgrid to plot surf?


code:
from itertools import imap
imap(lambda x,y:x(y), functions, values)

rawDescription: Zip and apply a list of functions over a list of values in Python


code: best = max(genes, key=lambda k: compareGenes(k, target))

rawDescription: how to make this a list comprehension

description: Make this a list comprehension


rawDescription: Pythonic way to rewrite the following C++ string processing code


rawDescription: Python calculating Catalan Numbers

description: Python calculating Catalan Numbers


code:
SQ = r"'[^']*'"   # single-quoted string
DQ = r'"[^"]*"'   # double-quoted string
OPS = r'[{}:]'    # operators
WS = r'\s+'       # whitespace
     # add more types as needed...
tokens = '(?:' + '|'.join([OPS, SQ, DQ, WS]) + ')'
pattern = re.compile(tokens, re.DOTALL)

def tokenize(source):
    start = 0
    end = len(source)
    while start < end:
        match = pattern.match(source, start)
        if match:
            yield match.group(0)
        else:
            raise ValueError('Invalid syntax at character %d' % start)

        start = match.end()

rawDescription: Match open and close brackets in garbled string


code:
import lxml.etree
tree = lxml.etree.parse('input.xml')
elems = tree.xpath('//tfs:ActnCode[../tfs:OrdDtl/tfs:AcctLookup/tfs:FundAcctID/text()="984575"]',
    namespaces={'tfs':'tfs'})
elems2 = tree.xpath('.//tfs:ActnCode[../tfs:OrdDtl]',
    namespaces={'tfs':'tfs'})
print('elems', elems)
for elem in elems:
    elem.text = 'CAN'
tree.write("output.xml")

rawDescription: replace xml values with python

description: Replace xml values with python


code:
my_dict = {1:[1,2,3],4:[5,6,7],8:[9,10,11]}
for row in zip(*([key] + value for key, value in sorted(my_dict.items()))):
    print(*row)

rawDescription: How can I print a dictionary in table format?

description: Print a dictionary in table format


code: tag2entries = soup.select('tag1  tag2')

rawDescription: Python BeautifulSoup find all tags under a certain type of tag


rawDescription: reading a file and storing values in a matrix using python

description: Reading a file and storing values in a matrix using python


code:
def matchOCR(l, r):
    for expl in expQuestions(l):
        for expr in expQuestions(r):
            if matchats(expl, expr):
                return True
    return False

rawDescription: elegant way to match two wildcarded strings

description: Elegant way to match two wildcarded strings


code: dig = list(int(d) for d in str(num))

rawDescription: Divide number into digits and save them in list (array) using python


code:
from string import ascii_uppercase
from itertools import product

def gen_words(mask):
    replace = mask.count('?')
    mask = mask.replace('?', '{}')
    for letters in product(ascii_uppercase, repeat=replace):
        yield mask.format(*letters)

rawDescription: Generate list of 7 letter words meeting specific conditions - Python


rawDescription: how to find whether this python list within list contains duplicates or not?

description: Find whether this python list within list contains duplicates or not


code:
set2 = set(x['id'] for x in list2)
for entry in list1:
  if entry['id'] in set2:
    entry['match'] = True

rawDescription: mapping two list

description: Mapping two list


rawDescription: Can I extend list in Python with prepend elements instead append?

description: Extend list in Python with prepend elements instead append


code: df.groupby('A').apply(lambda x: x[x['B'] > 0]['B'].sum())

rawDescription: Count the number of matched element in pandas


code: bnext = Button(...)

rawDescription: matplotlib, plt.show() in a different method = no on_clicked

description: Matplotlib, plt.show() in a different method = no on_clicked


code: [format(e, '05b') for e in m]

rawDescription: How to print a binary number

description: Print a binary number


code:
result = db.col.find({"some": "condition"}, {"name": 1})
print([document["name"] for document in result])

rawDescription: Pymongo.find() only return answer

description: Pymongo.find() only return answer


rawDescription: Genericise Function call

description: Genericise Function call


code:
print(df.loc[:, ('Area', 'Branch Name')])
# 2    Name1
# 3    Name2
# Name: (Area, Branch Name), dtype: object

print(df.loc[:, ('Auto loan', 'No of accounts')])
# 2    0
# 3    0
# Name: (Auto loan, No of accounts), dtype: object

rawDescription: Pandas: parse merged header columns from Excel


code:
subsidiaries = session.query(Subsidiary)\
                .join(Subsidiary.commerce)\
                .join(Commerce.commerce_tags)\
                .filter(CommerceTag.id == id)

rawDescription: Trying to filter by an intermediate table


code:
1 in [1, 2, 3]
3 in range(50)
"foo" in { "foo": "bar" }
"bar" not in { "foo": "bar" } # (it only looks at keys for dictionaries)

rawDescription: Multiple while matches in python

description: Multiple while matches in python


code:
class MyString:
    str = ''
    def __init__(self,str):
        MyString.str = str
    def __div__(self, sep):
        return self.str.split(sep)
m = MyString('aSAA')
print(MyString.str)
#print(m.str)
['a', 'cda', 'cda', 'cd']

rawDescription: Is there any way besides __init__ to receive values when constructing a class?


code:
import numpy as np

def fisher_criterion(v1, v2):
    return abs(np.mean(v1) - np.mean(v2)) / (np.var(v1) + np.var(v2))

rawDescription: Calculating the Fisher criterion in Python


code:
from kivy.config import Config
Config.set('kivy', 'double_tap_timeout', '500') #< 500 ms between 2 touch tap

rawDescription: Python GUI for accessibility Application


rawDescription: Numpy equivalent of dot(A,B,3)

description: Numpy equivalent of dot(A,B,3)


code:
if get_choice(scenario2options)==0: # first choice, i.e. Approach exit door
    ...
else: # other choice, i.e. Check for vital signs
    ...

rawDescription: While keeps asking for input. Not skipping to second function


code:
class A(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __str__(self):
        return "A: a = %s, b = %s" % (self.a, self.b)

class B(A):
    def __init__(self, *args):
        if type(args[0]) is A:
            self.__dict__ = args[0].__dict__.copy()
            c = args[1]
        else:
            super(B, self).__init__(*args[:2])
            c = args[2]
        self.c = c

    def __str__(self):
        return "B: a = %s, b = %s, c = %s" % (self.a, self.b, self.c)

rawDescription: Python construct child class from parent


code:
h = input('Enter hex: ').lstrip('#')
print('RGB =', tuple(int(h[i:i+2], 16) for i in (0, 2 ,4)))

rawDescription: Converting Hex to RGB value in Python

description: Converting Hex to RGB value in Python


code:
misc_dir = os.path.join(mypackage_dir, 'misc')
tests_dir = os.path.join(mypackage_dir, 'tests')

rawDescription: Self reference for assertions while unittesting


code:
with open('input.txt', 'r') as istr:
    with open('output.txt', 'w') as ostr:
        for i, line in enumerate(istr):
            # Get rid of the trailing newline (if any).
            line = line.rstrip('\n')
            if i % 2 == 0:
                line += 'S'
            print(line, file=ostr)

rawDescription: Append Text (Single Letter) to the end of each line in a text file


rawDescription: How to turn a script into a function

description: Turn a script into a function


code:
from tkinter import *

def start(root, z):
    a = 'hi'
    z['text'] = a
    root.after(100, start, root, z)

root = Tk()
z = Label(root, text='')
z.place(width=50, height=20)

start(root, z)

root.mainloop()

rawDescription: Looking for a way to stop memory leak in this basic program


code:
from bs4 import BeautifulSoup
import requests

webpage = requests.get('http://www.bbcgoodfood.com/search/recipes?query=tomato')
soup = BeautifulSoup(webpage.content)
links = soup.find_all("article")

for ele in links:
    print(ele.a["href"])
    print(ele.img["src"])

rawDescription: How to scrape a page with BeautifulSoup and Python?

description: Scrape a page with BeautifulSoup and Python