code:
def display_form():
    form = FORM('Your name:',
            INPUT(_name='name', requires=IS_NOT_EMPTY()),
            INPUT(_type='submit'))
    if form.process().accepted:
        session.flash = 'form accepted'
        redirect(URL('next'))
    elif form.errors:
        response.flash = 'form has errors'
    else:
        response.flash = 'please fill the form'
    return dict(form=form)

rawDescription: Preprocessing form data before using it

description: Preprocessing form data before using it


code:
import argparse

parser = argparse.ArgumentParser(prog="LS.py",
                                 usage="%(prog)s [options] [paths...]\nThe paths are optional; if not given . is used.",
                                 add_help=False)

group = parser.add_argument_group("Options")

group.add_argument("-h", "--help", action="help", help="show this help message and exit")
group.add_argument("-path", default=".", help=argparse.SUPPRESS)
group.add_argument("-m", "--modified", action="store_true",
                    help="show last modified date/time")
group.add_argument("-o", "--order", nargs=1, default="name",
                    help="sort order (n[ame], m[odified], s[ize])\n[default: name]")
group.add_argument("-r", "--recursive", action="store_true",
                    help="recurse into subdirectories")
group.add_argument("-s", "--sizes", action="store_true",
                   help="show sizes")

args = parser.parse_args()

rawDescription: Move "help" to a different Argument Group in python argparse


code:
import time
import sys

for i in range(4, 0, -1):
    print('\rTime left:', i, end='')
    sys.stdout.flush()
    time.sleep(1)

rawDescription: How to alter a string after it has been printed

description: Alter a string after it has been printed


code:
class Parent(object):
    def new(self,*args,**kwargs):
        # use `self` in some way to perhaps change `args` and/or `kwargs`
        return type(self)(*args,**kwargs)

rawDescription: Python Inheritance : Return subclass

description: Python Inheritance : Return subclass


rawDescription: iterating through a list of dictionary names

description: Iterating through a list of dictionary names


rawDescription: How to obtain different types of range in an array

description: Obtain different types of range in an array


code:
for k in audio:
    for val in audio[k]:
        print("{}:{}".format(k,val))

rawDescription: How to add multiple values to the same key in a Python Dictionary

description: Add multiple values to the same key in a Python Dictionary


code:
import logging
extra = {'app_name':'Super App'}

logger = logging.getLogger(__name__)
syslog = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s')
syslog.setFormatter(formatter)
logger.setLevel(logging.INFO)
logger.addHandler(syslog)

logger = logging.LoggerAdapter(logger, extra)
logger.info('The sky is so blue')

rawDescription: How do I add custom field to Python log format string?

description: Add custom field to Python log format string


code:
from pyspark.sql.functions import current_date, datediff, unix_timestamp

df_casted.where(datediff(current_date(), col("dt")) < 7)

rawDescription: PySpark: filtering a DataFrame by date field in range where date is string


code:
count = lambda x: sum(s[i:i+m] == x for i in range(len(s)))
X = [''.join(cs) for cs in itertools.product("abc", repeat=3)]
counts = [count(x) for x in X]

rawDescription: Average time a substring occurs

description: Average time a substring occurs


code:
from django import forms
from django.forms.formsets import formset_factory
from django.forms.forms import NON_FIELD_ERRORS

class CommentForm(forms.Form):
    comment = forms.CharField(label='comment')

class MainForm(forms.Form):
    name = forms.CharField(label='name')

    def __init__(self):
        self.commentFormset =  formset_factory(CommentForm, extra=1)
        self.comments = self.commentFormset()

    def clean(self):
        cleaned_data = super(MainForm, self).clean()

        for nForm, commentForm in enumerate(self.comments):
            if commentForm.is_valid():
                pass
            else:
                self._errors[NON_FIELD_ERRORS] = self.error_class(['Invalid Comments'])

rawDescription: Flexible number of form fields in Django forms


code: FacialPanel = cmds.modelPanel(camera = "facial_cam", mbv=False)

rawDescription: maya/python modify modelPanel layout and behaviour

description: Maya/python modify modelPanel layout and behaviour


code:
import sys
from ctypes import *

c_ulonglong_p = POINTER(c_ulonglong)

_GetDiskFreeSpace = windll.kernel32.GetDiskFreeSpaceExW
_GetDiskFreeSpace.argtypes = [c_wchar_p, c_ulonglong_p, c_ulonglong_p, c_ulonglong_p]

def GetDiskFreeSpace(path):
    if not isinstance(path, unicode):
        path = path.decode('mbcs') # this is windows only code
    free, total, totalfree = c_ulonglong(0), c_ulonglong(0), c_ulonglong(0)
    if not _GetDiskFreeSpace(path, pointer(free), pointer(total), pointer(totalfree)):
        raise WindowsError
    return free.value, total.value, totalfree.value

rawDescription: Available disk space on an SMB share, via Python


code:
def __init__(self):
     env.roles = ['web']

rawDescription: How do I decorate Fabric tasks with @roles when my tasks inherit from the Task class?

description: Decorate Fabric tasks with @roles when my tasks inherit from the Task class


code:
reader = csv.DictReader(infile, fieldnames=COLS, quoting=csv.QUOTE_NONNUMERIC)
ranpak_dict = {row['SN']: row for row in reader if row['CHARGE'] > 0}

rawDescription: Add key/values to dictionary using condition


code:
try:
    from . import ElementPath
except ImportError:
    ElementPath = _SimpleElementPath()

rawDescription: ElementTree: What is the syntax for the 'match' argument to the 'find' method?


code:
def _h5_fast_bool_ix(self, h5_array, ix, read_chunksize=100000):
    '''Iterate over an h5 array chunkwise to select a random subset
    of the array. `h5_array` should be the array itself; `ix` should
    be a boolean index array with as many values as `h5_array` has
    rows; and you can optionally set the number of rows to read per
    chunk with `read_chunksize` (default is 100000). For some reason
    this is much faster than using `ix` to index the array directly.'''

    n_chunks = h5_array.shape[0] / read_chunksize
    slices = [slice(i * read_chunksize, (i + 1) * read_chunksize)
              for i in range(n_chunks)]

    a = numpy.empty((ix.sum(), h5_array.shape[1]), dtype=float)
    a_start = 0
    for sl in slices:
        chunk = h5_array[sl][ix[sl]]
        a_end = a_start + chunk.shape[0]
        a[a_start:a_end] = chunk
        a_start = a_end

    return a

rawDescription: Uniformly shuffle 5 gigabytes of numpy data


code:
# Python 3.1 or before

import operator

def accumulate(iterable, func=operator.add):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = next(it)
    yield total
    for element in it:
        total = func(total, element)
        yield total

# Python 3.2 and newer can use
# from itertools import accumulate

array = list(accumulate(rand(100)))

rawDescription: List comprehension with an accumulator

description: List comprehension with an accumulator


code:
nested_dates = []
for y, yeardict in sorted(datedict.items()):
    yearlist = []
    for m, days in sorted(yeardict.items()):
        yearlist.append((m, sorted(days)))
    nested_dates.append((y, yearlist))

rawDescription: Looping over a tuple in jinja2

description: Looping over a tuple in jinja2


code:
import numpy as np
from multiprocessing import Process, Condition, Event
from time import sleep
import psutil

def read_arr(arr, done, stop):
    with done:
        S = np.sum(arr)
        print(S)
        done.notify()
    while not stop.is_set():
        sleep(1)

def main():
    # Create a large array
    print('Available before A (MiB):', psutil.virtual_memory().available / 1024 ** 2)
    input("Press Enter...")
    A = np.random.random(2**28)
    print('Available before Process (MiB):', psutil.virtual_memory().available / 1024 ** 2)
    input("Press Enter...")
    done = Condition()
    stop = Event()
    p = Process(target=read_arr, args=(A, done, stop))
    with done:
        p.start()
        done.wait()
    print('Available with Process (MiB):', psutil.virtual_memory().available / 1024 ** 2)
    input("Press Enter...")
    stop.set()
    p.join()

if __name__ == '__main__':
    main()

rawDescription: Why does my loop require more memory on each iteration?


code:
# test_configpage.py
from base import *

class ConfigPageTest(BaseTestClass):

    def test_one(self):
        pass

    def test_two(self):
        pass

    @unittest.skipIf(True, 'msg')
    def test_three(self):
        pass

rawDescription: Python unittest, skip tests when using a base-test-class


code:
# all as one list comprehension starting with just the string
[1+len(t.split(',')) for t in my_str.split('[tag]')]

rawDescription: Python - Count elements of a list within a range of specified values


code:
from collections import defaultdict
list1 = [('id1','host1'),('id2','host2'),('id1','host5'),('id3','host4'),('id4','host6'),('id5','host8')]
list2 = [('id1','IP1'),('id2','IP2'),('id3','IP3'),('id4','IP4'),('id5','IP5')]
d1 = defaultdict(list)
for k,v in list1:
    d1[k].append(v)

rawDescription: Python merge lists by common element

description: Python merge lists by common element


code: vertexes = list(set(vertexes.value))

rawDescription: How to change a global variable value inside a task map or reduce in Apache Spark using Python

description: Change a global variable value inside a task map or reduce in Apache Spark using Python


rawDescription: Merging 2 list of dicts based on common values


rawDescription: Comparing NumPy arrays so that NaNs compare equal


code:
def read_pairs_file():
   pairFd = open(pairFile, 'r')
   for line in pairFd.readLines():
      id, isUsed = line.split(',')
      yield (id, isUsed)
   pairFd.Close()

rawDescription: Random searching and modification of a file in python


rawDescription: Adding extra functionality to parent class method without changing its name


code:
df[['pad1','pad2','pad3']] = np.nan

df2 = df.copy().iloc[:,:-3]
for i in range(1,len(df2.columns)):
    df2.iloc[:,i] = ((df.iloc[:,i].notnull()) &
                     (df.iloc[:,i+1:i+4].apply(lambda x: all(x.isnull()),axis=1)))

rawDescription: Excel like formulas with pandas

description: Excel like formulas with pandas


code:
from unittest import skip

@skip
def foo_test():
    pass

rawDescription: Unittests marked with @unittest.skip are not marked under nosetests


code:
import re
text = '''\
www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?db=nucleotide&val=NM_003157.1 rs 1123
www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?db=nucleotide&val=NM_006157 dd 12
www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?db=nucleotide&val=NM_021018.2 ff 121
www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?db=nucleotide&val=NM_000908.2 rs10472828-?
'''
f = text.splitlines()
for i in f:
    print(re.findall(r"N[A-Z]_[0-9]+(?:\.[1-9])*", i.strip()))

rawDescription: grep output not same as "re.findall()" output in python3

description: Grep output not same as "re.findall()" output in python3


code:
import re
quoted = '%u003c%u0062%u0072%u003e'
re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: unichr(int(m.group(1), 16)), quoted)
altquoted = '%u3c%u0062%u0072%u3e'
re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: unichr(int(m.group(1), 16)), altquoted)

rawDescription: Javascript unescape() vs. Python urllib.unquote()


code:
from operator import itemgetter
[map(sum,map(set,zip(*g))) for _,g in groupby(sorted(d, key=itemgetter(0)),key=itemgetter(0))]

rawDescription: merging sorted list of list members if neighbors are equal

description: Merging sorted list of list members if neighbors are equal


code:
pts = MultiPoint([Point(i) for i in points])
mask = pts.convex_hull.union(pts.buffer(10, resolution=5, cap_style=3))
result = MultiPolygon(
    [poly.intersection(mask) for poly in polygonize(lines)])

rawDescription: Python finite boundary Voronoi cells

description: Python finite boundary Voronoi cells


code:
import re

def find_start_of(needle, haystack):
    """
    @param needle    Search on first char of string
    @param haystack  Longer string to search in

    Look for first char of needle in haystack; return offset
    """

    if needle=='':
        return 0

    offs = haystack.find(needle[0])
    if offs==-1:
        return len(haystack)
    else:
        return offs

def find_end_of(lst, letterset):
    """
    @param lst       Chars to search for
    @param letterset String to search through

    lst contains some chars of letterset in order;
    Return offset in letterset of last char of lst
    """

    offs = 0
    for ch in lst:
        t = letterset.find(ch, offs)

        if t==-1:
            raise ValueError('letterset (%s) is not an ordered superset of lst (%s)' % (letterset, lst))
        else:
            offs = t+1

    return offs-1

def alignSeq(s1, s2):
    """
    @param s1 A string consisting of letters and hyphens
    @param s2 A string containing only letters

    The letters in s1 are an in-sequence subset of s2

    Returns s1 with the missing letters from s2 inserted
    in-sequence and greedily preceding hyphens.
    """

    # break s1 into letter-chunks and hyphen-chunks
    r = '([^-]*)([-]*)'        # string of letters followed by string of hyphens
    seq = re.findall(r, s1) # break string into list of tuples
    seq = seq[:-1]          # discard final empty pair
    # eg: "MAT--LA-B" becomes [('MAT', '--'), ('LA', '-'), ('B', '')]

    # find start of corresponding letter-chunks in s2
    offs = 0
    chunkstart = []
    for letters,hyphens in seq:
        offs += find_start_of(letters, s2[offs:])
        chunkstart.append(offs)
        offs += find_end_of(letters, s2[offs:]) + 1

    # get end+1 for each letter-chunk
    chunkend = chunkstart[1:] + [len(s2)]
    # get replacement letter-chunks
    chunks = [s2[st:en] for st,en in zip(chunkstart,chunkend)]

    # do replacement for each chunk
    outp = [c+s[1] for c,s in zip(chunks, seq)]

    return ''.join(outp)

rawDescription: Inserting missing portions of a sequence in python


code: float(len(data))

rawDescription: average list of dictionaries in python

description: Average list of dictionaries in python


code:
from sqlalchemy import func, text

func.datediff(text('month'), TableA.date, todays_date) >= 0

rawDescription: Python Sqlalchemy: Filter by datediff of months


code:
def CustomProp(name, maxval):
    name = '_' + name

    @property
    def pro(self):
        return getattr(self, name)

    @pro.setter
    def pro(self, val):
        if not isinstance(val, (int, float)):
            # In Python 2 -> '' > 10(or any number) is True, so better check the type as well.
            raise TypeError('Only integers and floats are allowed.')
        if val > maxval:
            raise ValueError("Value {!r} above maximum {!r}.".format(val, maxval))
        else:
            setattr(self, name, val)

    return pro

class Test(object):
    x = CustomProp('x', 10)
    y = CustomProp('y', 20)
    z = CustomProp('z', 30)

    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

rawDescription: Is there a faster way to use @property for multiple properties in a class?


code:
# Plot single value
df.boxplot(column='Value', by=['Parameter', 'Site'])

# Plot Multiple values
df.boxplot(column=['Value', 'OtherValue'], by=['Parameter', 'Site'])

rawDescription: Python Matplotlib Box plot

description: Python Matplotlib Box plot


code:
from itertools import chain

list(chain(*m))  # shortest
# or:
list(chain.from_iterable(m)) # more efficient

rawDescription: Converting matrix to an array in python

description: Converting matrix to an array in python


code:
offset = chunk*x
values = format.unpack_from(line, offset)

rawDescription: Parsing a string with defined data dictionary into a list efficiently


code:
authors = []
for line in text.split('\n'):
    names = re.split(r'\d+: |[^,;.]{20,}', line)[1]
    authors.append(re.findall(r'\w+,? [\w.]+', names))

rawDescription: Grouping characters in Python

description: Grouping characters in Python


code:
class Country(object):
    def __init__(self, location, population, president='none'):
        self.location = location
        self.population = population
        self.president = president

dic = {'canada': Country('North America', '150M+')}

dic['canada'].population = '100M+'

rawDescription: python, how to update the dictionaries by mutating its format?

description: Python, how to update the dictionaries by mutating its format


code:
MvT101group = MvT101.groupby('Order',sort=True).sum()
MvT102group = MvT102.groupby('Order',sort=True).sum()

rawDescription: How should I subtract two dataframes and in Pandas and diplay the required output?


rawDescription: Loop and add with 2 lists

description: Loop and add with 2 lists


code:
input_name = raw_input("Enter variable name:") # User enters "orange"
locals()[input_name] = 4
print(orange)

rawDescription: setting user input to variable name

description: Setting user input to variable name


code:
# coding: utf-8
from __future__ import print_function
import sys
import codecs

symbols = (u'♠',u'♥',u'♦',u'♣')

print(u' '.join(symbols))
print(*symbols)
with codecs.open('test.txt','w','utf-8') as testfile:
    print(*symbols, file=testfile)

rawDescription: Unicode not printing correctly to cp850 (cp437), play card suits


code: modified_foo = function(original_foo)

rawDescription: in Python Is there ever a good time to use a global variable inside a class?

description: In Python Is there ever a good time to use a global variable inside a class


code:
import timeit
setup = 'import numpy as np; a=np.random.random(1000); b = np.random.random(1000)'
[timeit.timeit('np.dot(a,b)',setup,number=1000000) for _ in range(3)]
[timeit.timeit('np.inner(a,b)',setup,number=1000000) for _ in range(3)]

rawDescription: difference between numpy dot() and inner()

description: Difference between numpy dot() and inner()


code: subprocess.Popen('/bin/echo $TEST_VARIABLE', shell=True, env=d).wait()

rawDescription: Python: Exporting environment variables in subprocess.Popen(..)


code: u"Want to post in %s?(Y/N)" % i['name']

rawDescription: Print non-ascii text in Python

description: Print non-ascii text in Python


code:
def fit_poly_through_origin(x, y, n=1):
    a = x[:, np.newaxis] ** np.arange(1, n+1)
    coeff = np.linalg.lstsq(a, y)[0]
    return np.concatenate(([0], coeff))

n = 1000
x = np.random.rand(n)
y = 1 + 3*x - 4*x**2 + np.random.rand(n)*0.25

c0 = np.polynomial.polynomial.polyfit(x, y, 2)
c1 = fit_poly_through_origin(x, y, 2)

p0 = np.polynomial.Polynomial(c0)
p1 = np.polynomial.Polynomial(c1)

plt.plot(x, y, 'kx')
xx = np.linspace(0, 1, 1000)
plt.plot(xx, p0(xx), 'r-', )
plt.plot(xx, p1(xx), 'b-', )

rawDescription: How to make my pylab.poly1d(fit) pass through zero?

description: Make my pylab.poly1d(fit) pass through zero


code:
# use this code to convert integer values to ints at parse time
key_qs = qs.copy()
value_qs = qs.copy()
def convert_integers(tokens):
    if tokens[0].isdigit():
        tokens[0] = int(tokens[0])
value_qs.setParseAction(convert_integers)

value = Forward()
key_value = Group(key_qs + value)
struct = LBRACE + Dict(ZeroOrMore(key_value)) + RBRACE
value <<= value_qs | struct
parser = Dict(key_value)

rawDescription: Parsing a CS:GO script file in Python

description: Parsing a CS:GO script file in Python


rawDescription: Create a list of tuples from list of tuples


code:
class Singleton(type):
    def __init__(cls, *args, **kwargs):
        cls.__instance = None
        super().__init__(*args, **kwargs)

    def __call__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super().__call__(*args, **kwargs)
        return cls.__instance

rawDescription: Python Singleton design pattern tracking application stats


code:
dict3 = {}
#Note because you want the addresses to be the key of the new dictionary
#we only need to look at the keys that exist in both dict1 and dict2.
for key in dict2.keys():
    if key in dict1:
        dict3[dict2[key]] = dict1[key]

rawDescription: Compare two dictionaries with one key in common and form a new dictionary combining the remaining keys associated with this common key


rawDescription: Using regex for mutliple lines

description: Using regex for mutliple lines


rawDescription: How to display dictionary by their values, descending?

description: Display dictionary by their values, descending


code:
se = ((x, x+1) for x in range(5))
for a, b in se:
    print('{} {}'.format(a, b))

rawDescription: Getting two values from one range

description: Getting two values from one range


code: df1['deltaValue'] = df1['value'] - df1.loc[('Group1','ref')]['value']

rawDescription: Calculate difference from a reference row in pandas (python)


code:
from datetime import datetime

def on_message(self, room, user, message):
    template = "{0} - {1.name}({1.rank}): {2.body}"
    timetemp = "%H:%M:%S %b %d %Y"
    print(template.format(datetime.strftime(datetime.now(), # or 'message.time'?
                                            timetemp),
                          user, message))

rawDescription: Chatango Chaning Time

description: Chatango Chaning Time


code:
search_nums = [100,102] # List of search numbers. NumPy arrays would work too.
xyzv = xyzv[np.in1d(xyzv[:,3].astype(int),search_nums)]

rawDescription: How to delete rows where specific column value is not within other array?

description: Delete rows where specific column value is not within other array


code:
sorted([w.n(2,chop=True) for w in solve(-x**3+2*x**2+3*x-2)])
sorted([w.n(2,chop=True) for w in cutrig(-1,2,3,-2)])

rawDescription: Python/Sympy trigonometric solution of cubic equation


code:
# Lower-case, split into words, discard everything that's not a letter
tok_lines = [ re.split(r"[^a-z]+", line.lower()) for line in pCorp ]
# tok_lines is now a list of lists of words

stopwordlist = nltk.corpus.stopwords.words("english") # or any other list
stopwords = set(w.lower() for w in stopwordlist)
cleantoks = [ [ t for t in line if t not in stopwords ]
                                        for line in tok_lines ]

rawDescription: Text mining and NLP: from R to Python

description: Text mining and NLP: from R to Python


rawDescription: Index a Pandas dataframe grouped by date and aggregated?


code:
def is_a_straight(hand):
    rank_set = set([card['rank'] for card in hand])
    rank_range = max(rank_set) - min(rank_set) + 1
    return rank_range == len(hand) and len(rank_set) == len(hand)

rawDescription: Identifying a 'straight' (from Poker) using Python


code:
import subprocess

file_ = open("ouput.txt", "w")
subprocess.Popen(["host", ipAddress], stdout=file_)

rawDescription: python Save the output of a shell command into a text file

description: Python Save the output of a shell command into a text file


code:
class Relative:

    def __init__(self, first_name=None):
        self.first_name = first_name

    @staticmethod
    def _valid_name(name):
        return name is None or name.isalpha()
        # this will choke if name isn't None or a string - maybe add more rules?

    @property
    def first_name(self):
        return self._first_name

    @first_name.setter
    def first_name(self, new_name):
        if not self._valid_name(new_name):
            raise ValueError('Invalid first name: {!r}'.format(new_name))
        self._first_name = new_name

    @classmethod
    def from_input(cls):
        relative = cls()
        while True:
            # you could alternatively use cls._valid_name directly here
            try:
                relative.first_name = input('Enter first name: ')
            except ValueError:
                print('Please try again.')
            else:
                break
        return relative

rawDescription: Class method to create new instance

description: Class method to create new instance


code:
split_bits(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, 32)
[format(i, 'X') for i in _] # show corresponding hex representations
split_bits(0b1000100110101011, 4)
[format(i, 'b') for i in _] # show corresponding binary representations

rawDescription: Split each after 32 bits of 128 bit input in Python


code: admin.add_view(views.CRUDSettings(session=db.session, name='CRUD Settings', endpoint='crud'))

rawDescription: Flask-Admin - adding a custom view

description: Flask-Admin - adding a custom view


code:
lst = [1, 2, 3]
lst.append(lst)  # oh my!

r = reprlib.Repr()
r.maxlevel = 5   # max recursion depth

print(r.repr(lst))

rawDescription: Limiting print output

description: Limiting print output


code:
## swigMock.py ##
class swigsubpackagebar(object):
    pass

rawDescription: how do I create a in-line module

description: Create a in-line module


code:
def onChange(val):
    if val == "Square":
        r = 2
    elif val == "Sphere":
        r = 1
    else:
        r = 5

    c = container.winfo_children()
    old_r = len(c) # Number of widgets in container frame

    # Destroys all excess widgets in the container frame
    # Eg. old_r = 5, r = 2 | Last 3 widgets in frame are destroyed
    if old_r > r:
        for wid in c[r:old_r]:
            wid.destroy()

    # Dynamically create Entry widgets in container frame
    # Only creates extra to meet r value
    # Eg. old_r = 2, r = 5 | Creates 3 widgets in frame after original 2
    elif old_r < r:
        for x in range(old_r, r):
            e = tk.Entry(container)
            e.grid(row = 1 + x, column = 0)

rawDescription: Python grid_remove

description: Python grid_remove


code:
class Photo(models.Model):
    title = models.CharField(max_length=100)
    gallery = models.ForeignKey(Gallery, related_name='photos')
    file = models.ImageField(upload_to=get_site_profile_path)

    def __unicode__(self):
        return self.title

class Gallery(models.Model):
    name = models.CharField(max_length=40)
    site = models.ForeignKey(Site)

    def __unicode__(self):
        return self.name

rawDescription: Django MTMField: limit_choices_to = other_ForeignKeyField_on_same_model?


code:
for line in fd:
    new_line = line.split(' ')
    for word in new_line:
        new_word = ''.join(l for l in word if l.isalpha())
        new_word = new_word.lower()
        for ind_count, let in enumerate(new_word):
            c_dict.setdefault((let, ind_count), set()).add(new_word)

rawDescription: Manipulating sets in dictionaries

description: Manipulating sets in dictionaries


code: print("\n\n".join("\n".join(map(str,seq)) for seq in stuff if seq))

rawDescription: Print a new line in between a list in python


code:
if info_list:
    complete_dict=dict(zip(category_list,info_list))

rawDescription: Removing empty dictionary elements in Python


code:
class X2(list):
    def __hash__(self):
        return hash(tuple(self))

rawDescription: What makes a user-defined class unhashable?


code: val = ''.join(c for c in val if c.isdigit() or c in ',.')

rawDescription: how to clean or convert unknown characters in an otherwise integer field in python?

description: Clean or convert unknown characters in an otherwise integer field in python


code:
import dateutil
pd.read_csv(
    BytesIO(raw_data),
    parse_dates=['dates'],
    date_parser=dateutil.parser.parse,
)

rawDescription: skip rows with bad dates while using pd.read_csv

description: Skip rows with bad dates while using pd.read_csv


code:
c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
c

rawDescription: Python tuple key in dictionary not able to fetch


code:
for i in range(0, 5):
    instance.pk = None
    instance.save()

rawDescription: How can I save the same form more than once in Django 1.8?

description: Save the same form more than once in Django 1.8


code: c.update({i:V[i] for i in ID})

rawDescription: Is there any alternative ways other than loop to update the dictionary from any sequence data (Python)?


rawDescription: Remove duplicate from list which is used as value in dictionary


code:
a = [1, 2, 4]
b = 'foo'
from itertools import chain

func(*chain(a,b)) #chain will work for both iterators and iterables

rawDescription: Confusing double usage of python asterisk notation (as a function argument, or as a function definition)


code: new = df2[df2['followers'] != df2['followers']][['userid','date','followers']]

rawDescription: Operating on multiindex dataframe

description: Operating on multiindex dataframe


rawDescription: Find closest number in a circular array

description: Find closest number in a circular array


code:
def filter_mask(fg_mask):
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))

    # Fill any small holes
    closing = cv2.morphologyEx(fg_mask, cv2.MORPH_CLOSE, kernel)
    # Remove noise
    opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel)

    # Dilate to merge adjacent blobs
    dilation = cv2.dilate(opening, kernel, iterations = 2)

    return dilation

rawDescription: Counting Cars OpenCV + Python Issue

description: Counting Cars OpenCV + Python Issue


code:
import csv

with open('example.csv') as handle:
    reader = csv.reader(handle)
    next(reader, None)
    for row in reader:
        user, *scores = row
        average = sum([int(score) for score in scores]) / len(scores)
        print (
            "{user} has average of {average}".format(user=user, average=average)
        )

rawDescription: Row Average CSV Python

description: Row Average CSV Python


code:
import cssutils
from pprint import pprint

css = u'''
body, html { color: blue }
h1, h2 { font-size: 1.5em; color: red}
h3, h4, h5 { font-size: small; }
'''

dct = {}
sheet = cssutils.parseString(css)

for rule in sheet:
    selector = rule.selectorText
    styles = rule.style.cssText
    dct[selector] = styles

pprint(dct)

rawDescription: python how to parse css file as key value

description: Python how to parse css file as key value


code:
from django.views.generic import ListView
from ideapad.models import Idea
from sauce.decorators import SortQuerysetMixin

class IndexListView(SortQuerysetMixin, ListView):
    default_sort = '-date'
    model = Idea
    template_name = 'ideapad/index.html'
    context_object_name = 'ideas'

rawDescription: Django Coding Style: Should I be using class decorators here?


code:
def check_sudoku(array):
    reference = range(1, len(array) + 1)
    transposed = zip(array)
    for row, col in zip(array, transposed):
        if sorted(row) != reference or sorted(row) != reference:
            return False
    return True

rawDescription: Made typo, Python function still works. Why?


rawDescription: Printing to stdout or file without repeating code


rawDescription: Slicing numpy recarray at "empty" rows

description: Slicing numpy recarray at "empty" rows


code:
from OpenSSL import crypto

req = crypto.X509Req()
pkey = crypto.PKey()
pkey.generate_key(crypto.TYPE_RSA, 2048)
req.set_pubkey(pkey)
req.sign(pkey, 'sha1')
certreq = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)
certreq = certreq.replace('-----BEGIN CERTIFICATE REQUEST-----\n', '').replace('-----END CERTIFICATE REQUEST-----\n', '')
private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)

rawDescription: PyOpenSSL convert certificate object to .pem file


code:
import random
[random.expovariate(0.2) for i in range(10)]

rawDescription: how to generate integer inter arrival times using random.expovariate() in python

description: Generate integer inter arrival times using random.expovariate() in python


code:
{True}
{True}
{1}

rawDescription: Dict/Set Parsing Order Consistency

description: Dict/Set Parsing Order Consistency


rawDescription: Regular expression for a list of elements in patents


code:
period = datetime.timedelta(days=28)  # 4 weeks
delta = today - start
remainder = delta.days % period.days
today + datetime.timedelta(days=remainder)

rawDescription: Divide two timespans by eachother in Python/dateutil


rawDescription: How to partially copy using python an Hdf5 file into a new one keeping the same structure?

description: Partially copy using python an Hdf5 file into a new one keeping the same structure


code: params['fields'] = 'impressions,clicks'

rawDescription: Filtering statistics from facebook ads api using the python sdk


rawDescription: Is there way to use dictionary in python to print 2 outputs: one as string of whole token and one as number


code:
import funcy

pipeline = funcy.rcompose(
    get_monthly_historical_returns,
    calculate_returns,
    calculate_excess_returns
)

result = pipeline('./assets/monthly_historical_returns.csv')

rawDescription: Python 3 control flow in script with lots of steps


code: lot

rawDescription: Removing duplicates from a list of tuples based on one of values


rawDescription: uploading a file but did not get a file name

description: Uploading a file but did not get a file name


code:
class IndirectList():
    def __init__(self, *args):
        self.array = list()

        for subarray in range(len(args)):
            for element in range(len(args[subarray])):
                self.array.append((args[subarray], element))

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

    def __getitem__(self, key):
        if key not in range(len(self.array)):
            raise IndexError
        return (self.array[key][0])[self.array[key][1]]

    def __setitem__(self, key, value):
        if key not in range(len(self.array)):
            raise IndexError
        (self.array[key][0])[self.array[key][1]] = value

rawDescription: Storing a single list of references to elements in several other lists in python


code:
with open(filename, 'r') as f:
    lines = (line for line in f if predicate(line))
    arr = np.genfromtxt(lines)

rawDescription: numpy.loadtxt Skipping multiple rows

description: Numpy.loadtxt Skipping multiple rows


rawDescription: How to get dtype column names

description: Get dtype column names


code:
@register.filter
def to_js(value):
    """
    To use a python variable in JS, we call json.dumps to serialize as JSON server-side and reconstruct using
    JSON.parse. The serialized string must be escaped appropriately before dumping into the client-side code.
    """
    # separators is passed to remove whitespace in output
    return mark_safe('JSON.parse("%s")' % escapejs(json.dumps(value, separators=(',', ':'))))

rawDescription: Safely Using JSON with html inside of the JSON in Django Templates


code: a[:, None]

rawDescription: Use outer function with FUN="-" in Python


code: -I, --ignore-installed

rawDescription: Can I force pip to reinstall the current version?

description: Force pip to reinstall the current version


code:
from datetime import date

def generate_quarters(start, end):
    while start < end: #NOTE: not including *end*
        yield start
        start = start.increment()

start = Quarter.from_string('14Q3')
end = Quarter.from_date(date.today())
print("\n".join(map(str, generate_quarters(start, end))))

rawDescription: generate time series by quarter, increment by one quarter

description: Generate time series by quarter, increment by one quarter


code:
distance = [[]]
distance[-1].extend ([0,1,2,3.5,4.2])
distance

rawDescription: Nested float arrays in Python

description: Nested float arrays in Python


code:
# Creating the df that will save my results in the backtest iterations
cols = ('Strategy','Ticker','ROI')  # ,'Sharpe R','VaR','Strat'
df_res = pd.DataFrame(columns = cols)

rawDescription: Save vars pr iteration to df and when done save df to csv


code:
normalized_values = ['123', '456']
content = ['a123', '123', 'b456', '789']
for index, value in enumerate(content):
    for normalized_value in normalized_values:
        if normalized_value in value:
            content[index] = normalized_value

rawDescription: Python CSV: write rows according to dict mapping


code: return (related_object in [s.subscribed_to for s in subs])

rawDescription: Check if objects is foreign key of queryset result


rawDescription: Python: Altering code between iterations


code:
filter(tuple_wanted, dct.items())
filter(fun, dct.items())
filter(lambda tpl: wanted in tpl, dct.items())

rawDescription: Python - using dictionary to count keys and values


code:
from collections import Counter
l = [
    {'name': 'Amy', 'count': 1},
    {'name': 'Amy', 'count': 2},
    {'name': 'Peter', 'count': 1}
]
c = Counter()
for v in l:
    c[v['name']] += v['count']

rawDescription: Python list grouping and sum

description: Python list grouping and sum


rawDescription: Passing variable to html page using Python Django


code:
import win32com.client
import win32api
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("calc")
win32api.Sleep(100)
shell.AppActivate("Calculator")
shell.SendKeys("1{+}2{=}^C")
win32api.Sleep(500)

import win32clipboard
import win32con
win32clipboard.OpenClipboard()
r = win32clipboard.GetClipboardData(win32con.CF_TEXT).rstrip('\x00')
win32clipboard.CloseClipboard()
print(r)

rawDescription: Get result from Calculator with WScript.Shell


code:
import re
p = re.compile(r'^(\d+)\s[^(]+\(([^()]+)\)')
test_str = "70849   mozilla/5.0(linux;u;android4.2.1;zh-cn)applewebkit/534.30(khtml,likegecko)version/4.0mobilesafari/534.30"
print(p.findall(test_str))
# or using re.search if the number is not at the beginning of the string
m = re.search(r'(\d+)\s[^(]+\(([^()]+)\)', test_str)
if m:
    print("Number: {0}\nString: {1}".format(m.group(1), m.group(2)))
# [('70849', 'linux;u;android4.2.1;zh-cn')]
# Number: 70849
# String: linux;u;android4.2.1;zh-cn

rawDescription: Match first parenthesis with Python

description: Match first parenthesis with Python


code:
tag1, tag2 = 'tag1', 'tag2'
q = (Photo.query
     .filter(Photo.tags.any(Tag.name == tag1))
     .filter(Photo.tags.any(Tag.name == tag2))
     )

rawDescription: Flask-SQLAlchemy: multiple filters through one relation


code:
def decorator(*a):
    decorator._depth = 0
    def real_decorator(function):
        def wrapper(*args, **kwargs):
            global flag
            if decorator._depth == 0:  # entering outermost call
                flag = False

            decorator._depth += 1
            function(*args, **kwargs)
            decorator._depth -= 1

            if decorator._depth == 0:  # exiting outermost call
                flag = True
        return wrapper
    return real_decorator

rawDescription: Changing values in decorator for nested functions


rawDescription: python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

description: Python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B


code: glider

rawDescription: Removing specific columns and rows from nested list


rawDescription: How can I replace a number of list elements between 2 boundary symbols in a python list

description: Replace a number of list elements between 2 boundary symbols in a python list


code:
from selenium import webdriver

driver = webdriver.Firefox()  # can be webdriver.Chrome()
driver.get("about:blank")

data = '
test
'  # supposed to come from BeautifulSoup
driver.execute_script('document.body.innerHTML = "{html}";'.format(html=data))

rawDescription: Can beautiful soup output be sent to browser?


code:
same_likes = WhoLikes.all().filter('users', current_user_key_name)
like_the_same_keys = set()
for keys in same_likes:
   like_the_same_keys.union(keys.users)
same_like_users = UserModel.get_by_key_names(like_the_same_keys)

rawDescription: modelling the google datastore/python

description: Modelling the google datastore/python


code:
e = OrExpression(
    EqualsExpression(
        Variable("element"),
        Literal("Apple")
    ),
    OrExpression(
        EqualsExpression(
            Variable("element"),
            Literal("Orange")
        ),
        EqualsExpression(
            Variable("element"),
            Literal("Duck")
        )
    )
)

rawDescription: Create python functions from expression trees


code: df[df.index.get_level_values('a').isin([5, 7, 10, 13])]

rawDescription: Pandas slicing along multiindex and separate indices


code:
from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup

base_url = 'http://www.ragalahari.com'
url = 'http://www.ragalahari.com/actress/14035/kajal-aggarwal-at-memu-saitham-dinner-with-stars.aspx'

soup = BeautifulSoup(requests.get(url).content)

for img in soup.find_all('img', src=True):
    src = img.get('src')
    if not src.startswith('http'):
        src = urljoin(base_url, src)

    print(src)

rawDescription: Parse the relative link and absolute link using python


code:
class User(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(50), index=True, unique= True)
    email = db.Column(db.String(50),index=True, unique= True)

    bestfriend_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    bestfriend = db.relationship('User', remote_side=['id'], lazy='dynamic')

    def are_bestfriends(self, user):
        return self.best_friend == user

    def be_bestfriend(self, user):
        if not self.are_bestfriends(user):
            self.bestfriend = user
            user.bestfriend = self
            return self

rawDescription: Make only one BestFriend with flask-sqlalchemy


code:
my_lists = [[1, 2], [5, 7], [8, 9]]
my_tuple = tuple(my_lists)
print(my_tuple)

rawDescription: Creating a tuple with n entries for n lists


rawDescription: Delete an item from a list by match not index


rawDescription: Filter a 2D numpy array from an array of values


code:
a = 90
b = 100
'{0} is less than {1}'.format(*sorted([a, b]))

rawDescription: Returning different types in Python

description: Returning different types in Python


code:
from collections import defaultdict

def repack(mongo_data):
    result = defaultdict(list)
    for data in mongo_data:
        result[data["host"]].append(data)
    return result

rawDescription: Converting php loop to python

description: Converting php loop to python


code:
x = np.random.random(100)
y = np.random.random(100)
z = np.random.random(100)
p = np.random.random(3)
p

rawDescription: Search neighboring points using k-d trees


code:
def iterative_weighted_invert(x, y, threshold=None, numiter=5):
    last_y = y
    for _ in range(numiter):
        model = weighted_invert(x, y, weights=last_y, threshold=threshold)
        last_y = gaussian(x, *model)
    return model

rawDescription: How can I perform a least-squares fitting over multiple data sets fast?

description: Perform a least-squares fitting over multiple data sets fast


code:
def TestLoop():
    for i in range(1, 10000000):
        f = 1.0 / i
        if f != float(repr(f)):
            print('Failed.')
            return
    print('Succeeded.')
    return

TestLoop()

rawDescription: Float to String Round-Trip Test

description: Float to String Round-Trip Test


code:
dict_input = {
    "kishore": {"name":"kishore", "age":23},
    "xyz": {"name":"xyz", "age":21}
}
dict_input["kishore"]
dict_input["no-such-name"]
dict_input.get("no-such-name", "?")

rawDescription: Find a dictionary based on a key in list of dictionaries in python


rawDescription: Prepend function call in other function in Python


code:
shr_var = {}
class multiprocessing_np_arr_base_class(object):
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            shr_var[k] = v

rawDescription: Define a function that repeat commands for each input given in python


code:
for day in days:
    day_objects = Email.objects.filter(day_of_week=day)
    total_campaigns[day] = day_objects.count()
    # recipients
    ...

rawDescription: Nesting multiple 'for' loops

description: Nesting multiple 'for' loops


code:
event = CustomerEventsServiceEvent(**d)
event.save()

rawDescription: Insert a dict in cassandra DB

description: Insert a dict in cassandra DB


code: x = __import__('inner-script', globals(), (thing, counter), [], -1)

rawDescription: Run python from python without Popen or os.system


code:
# part2.py
# gvars is defined later
def scream():
 print(gvars.sound)

# part1.py
import part2

class GameVariables:
    pass

if __name__=="__main__":
    gvars = GameVariables()
    part2.gvars = gvars
    gvars.sound = "Yooo"
    part2.scream()
    gvars.sound = "Whaa"
    part2.scream()

#output
Yooo
Whaa

rawDescription: Python 3.x.x one variable spread across multiple .py files


code:
class Node:
    def __init__(self, name):
        self.name = name
        self.links = []

    def link(self, other, weight = None):
        self.links.append((other, weight))

rawDescription: Give class instances different methods depending on instance variables


code: data

rawDescription: Python stemming (with pandas dataframe)

description: Python stemming (with pandas dataframe)


code:
import sysconfig
import sys
sysconfig.get_platform()
sys.version_info[:3]

rawDescription: Testing Python C libraries - get build path


code: t1 = Triangle(int(side1), int(side2), int(side3))

rawDescription: How to make the input into a parameter in a class for Python

description: Make the input into a parameter in a class for Python


rawDescription: Django login form not working for custom user model


code:
import multiprocessing as mp
import multiprocessing.util as util
util.log_to_stderr(util.SUBDEBUG)

print(list(mp.Pool(1).imap(abs, range(3))))

rawDescription: multiprocessing Pool.imap broken?

description: Multiprocessing Pool.imap broken


code:
a = np.random.randint(256, size=(2048, 2048)).astype(np.uint8)
a.strides
np.rot90(a, k=-1).strides
np.rot90(a, k=-1).copy().strides
np.rot90(a, k=-1).copy(order='C').strides
np.rot90(a, k=-1).copy(order='K').strides

rawDescription: Force numpy array to physically match striding in memory


code: listX, listY = zip(*[p for p in zip(listX, listY) if pairs[p] != 3])

rawDescription: extract repeated elements in a list in python

description: Extract repeated elements in a list in python


code:
def read_entirely(file):
    with open(file, 'r') as handle:
        return handle.read()

result = '\n'.join(read_entirely(file) for file in toLoad)

rawDescription: How to concatenate several Javascript files into one file using Python

description: Concatenate several Javascript files into one file using Python


code:
u = User.objects.create(name='user')
g = Group.objects.create()
m = Member.objects.create(group=g, user=u)

rawDescription: Queryset for ManyToMany relation in Django


code:
it = iter(iterable)
try:
    while True:
        item = next(it)
        stuff(item)
except StopIteration:
    del it

rawDescription: How do I return a set of n consecutive integers given n and an iterable?

description: Return a set of n consecutive integers given n and an iterable


code:
inf
-inf
nan

rawDescription: Why aren't Inf, -Inf and NaN keywords in Python?


rawDescription: Django REST framework serializing model combinations


code:
# Add subplots to the current figure
plt.subplot2grid((2, 2), (0, 0))

# Get the current figure. This will hold the subplots created in the previous command
fig = plt.gcf()

rawDescription: On handling the layout of subfigures

description: On handling the layout of subfigures


code:
import numpy as np

# Mask of elements from J to be summed up
mask = np.arange(J.shape[0])[:,None] >= JTildeIDX

# Map the mask onto input array and sum along columns for final output
out = (J*mask).sum(0)

rawDescription: Cumsum and vectorized slicing

description: Cumsum and vectorized slicing


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

fig, ax = plt.subplots()
x1 = np.linspace(-1,1,100)

ax.plot(x1, np.sin(x1))
ax.plot(x1, np.sin(x1 / 2.0))
ax.autoscale(False)         #You could skip this line and use scalex=False on
ax.plot(x1, 3 * np.sin(x1)) #the "theoretical" plot. It has to be last either way

fig.savefig('test.pdf')

rawDescription: Make matplotlib autoscaling ignore some of the plots


code:
@register.filter(name='get')
def get(d, k):
    return d.get(k, None)

rawDescription: Accessing dict elements with leading underscores in Django Templates


rawDescription: How do i compute with (numpy) -arrays eloquently in python

description: Compute with (numpy) -arrays eloquently in python


code: stdoutdata, stderrdata = child_process.communicate(stdindata)

rawDescription: Printing to stdout in subprocess

description: Printing to stdout in subprocess


code:
for node in root.getiterator():
    if some_condition_matches_parent:
        for child in node.getiterator():
            if some_condition_matches_child:
                node.remove(child)

rawDescription: How to remove a node inside an iterator in python xml.etree.ElemenTree

description: Remove a node inside an iterator in python xml.etree.ElemenTree


code:
from abc import ABCMeta, abstractmethod

class Basic(object):
    __metaclass__ = ABCMeta

    allInstances = None

    def __init__(self):
        if self.__class__.allInstances is None:
            self.__class__.allInstances = set()
        self.__class__.allInstances.add(self)

    def __del__(self):
        self.__class__.allInstances.remove(self)

rawDescription: inheritance of set class attribute in python

description: Inheritance of set class attribute in python


rawDescription: Is there a faster way of extracting row/column submatrices from scipy.sparse.dok_matrix?


code: dic3 = { k : (dic1[k], dic2[k]) for k in dic1.viewkeys() & dic2.viewkeys() }

rawDescription: Match keys from two dictionaries, and make new dictionary with matched key and two associated values


code:
index_date = pd.date_range('2016-04-01', '2016-04-04')
index_date = pd.Series(index_date)
index_time = pd.date_range('09:30:00', '16:00:00', freq='78min')
index_time = pd.Series(index_time.time)

index = index_date.apply(
    lambda d: index_time.apply(
        lambda t: datetime.combine(d, t)
        )
    ).unstack().sort_values().reset_index(drop=True)

rawDescription: Python Pandas, Resampling only specific hours


code:
import wx
import wx.html2

class MyBrowser(wx.Frame):
    def __init__(self, *args, **kwds):
        wx.Frame.__init__(self, *args, **kwds)
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.browser = wx.html2.WebView.New(self, backend=wx.html2.WebViewBackendIE)
        sizer.Add(self.browser, 1, wx.EXPAND, 10)
        self.SetSizer(sizer)
        self.SetSize((700, 700))

if __name__ == '__main__':
    app = wx.App()
    dialog = MyBrowser(None, -1)
    dialog.browser.LoadURL("https://www.google.com")
    dialog.Show()
    app.MainLoop()

rawDescription: How to create a HTML-dialog window in Python with Internet Explorer control?

description: Create a HTML-dialog window in Python with Internet Explorer control


code: False

rawDescription: Get system metrics using PowerShell

description: Get system metrics using PowerShell


rawDescription: minimizing a given vector of components with a dataframe

description: Minimizing a given vector of components with a dataframe


code:
import collections
result = collections.defaultdict(int)
def count():
    fruit = input("What fruit are you getting at the store? ")
    result[fruit] += 1

rawDescription: Counting with python dictionaries and adding functionality


code:
def bet(self, player, bet):
    with self.condition:
        self.bets[player] = bet
        self.condition.notify()

rawDescription: Multiplayer Gaming via python

description: Multiplayer Gaming via python


rawDescription: Kivy - adding and removing labels

description: Kivy - adding and removing labels


code:
f = makeF()
f()

rawDescription: Defining a function with exec from inside a function in global environment


code:
with open("testDTC.txt") as f:
    for line in f:
        if line.strip() and not line.startswith(":"):
            spl = line.split(None,2)
            print("{} ;{}".format(" ".join(spl[:2]),spl[2]))

rawDescription: python, search .txt file and inject character

description: Python, search .txt file and inject character


code:
data = [
  (u'1',
   u'Six Thinking Hats',
   u'Edward de BONO',
   u'Penguin Books'
  ),
 ...
]

rawDescription: Parsing of table from .docx file

description: Parsing of table from .docx file


code:
import Tkinter as Tk
root = Tk.Tk()

ent = Tk.Entry(root, state='readonly')
var = Tk.StringVar()
var.set('Some text')
ent.config(textvariable=var, relief='flat')
ent.pack()
root.mainloop()

rawDescription: python tkinter popup window with selectable text

description: Python tkinter popup window with selectable text


code:
lis = [None]*6
lis[1] = "foo"   #change the 2nd element
lis[4] = "bar"   #change the fifth element
lis

rawDescription: python list with fixed number of elements

description: Python list with fixed number of elements


code:
[('a', '500'), ('d', '600')]  # With template A
[]                            # With template B

rawDescription: Python how to match files to templates

description: Python how to match files to templates


code:
from yourapplication.simple_page import simple_page

app = Flask(__name__)
app.register_blueprint(simple_page)

rawDescription: How to divide flask app into multiple py files?

description: Divide flask app into multiple py files


code: a = np.asarray(a)

rawDescription: filtering numpy matrix on a column

description: Filtering numpy matrix on a column


code:
import runpy

class Project(object):

    def __init__(self, path):
        module = runpy.run_path(path)
        for k, v in module.items():
            if not k.startswith('__'):
                self.__dict__[k] = v

rawDescription: Import variables (with evaluation) to class namespace (i.e. self.varName)


code:
import collections
import functools

class memoized(object):
   '''Decorator. Caches a function's return value each time it is called.
   If called later with the same arguments, the cached value is returned
   (not reevaluated).
   '''
   def __init__(self, func):
      self.func = func
      self.cache = {}
   def __call__(self, *args):
      if not isinstance(args, collections.Hashable):
         # uncacheable. a list, for instance.
         # better to not cache than blow up.
         return self.func(*args)
      if args in self.cache:
         return self.cache[args]
      else:
         value = self.func(*args)
         self.cache[args] = value
         return value
   def __repr__(self):
      '''Return the function's docstring.'''
      return self.func.__doc__
   def __get__(self, obj, objtype):
      '''Support instance methods.'''
      return functools.partial(self.__call__, obj)

rawDescription: How can I rewite this Python code using iteration?

description: Rewite this Python code using iteration


code:
from django.db import models

# Get field_name, is_foreign_key pairs from model meta
fields_foreign = [(
   field.name,
   isinstance(field, models.ForeignKey)
) for field in Contact._meta.fields]

# Assume every related model has a 'name' field,
# if you want to get 'name' fields of these models,
# construct the list of field names to pass to values():
# something like ['url', 'email', 'person', 'bonus_field__name']
value_fields = [
    f[0] if not f[1] else "{}__name".format(f[0])
    for f in fields_foreign
]

# Now get the values
Contact.objects.values(*value_fields)

rawDescription: Model.objects.all() returns integers for ForeignKeys and choice fields - how to force it to return names instead?


code:
def rgb2Hex(rgb_tuple):
    return '#%02x%02x%02x' % tuple(rgb_tuple)

num = 10000 #10,000 pixels in 100,100 image
colors = [[random.randint(0,255) for i in range(0,3)] for j in range(0,num)]
colors = [rgb2Hex(color) for color in colors]
im = Image.fromstring('RGB',(100,100),"".join(colors))
tkpi = ImageTk.PhotoImage(im)
## add to a label or whatever...
label_image = Tkinter.Label(root, image=tkpi)

rawDescription: How to draw a bitmap real quick in python using Tk only?

description: Draw a bitmap real quick in python using Tk only


code: result = result[['nU', 'ar', 'es']]

rawDescription: pandas - group and count nunique values

description: Pandas - group and count nunique values


code:
my_dict = {}
with open("your_document") as f:
    for line in f:
        line = line.strip()
        my_dict[line] = my_dict.get(line, 0) + 1

rawDescription: How do I count occurences of a unique label?

description: Count occurences of a unique label


code:
choice = [1, 1, 1, 1]
A = ['D', 'e', '0', '}']
''.join([c * i for c, i in zip(A, choice)])
choice = [0, 1, 0, 1]
''.join([c * i for c, i in zip(A, choice)])
from itertools import compress
''.join(compress(A, choice))

rawDescription: Python multiplication of two list

description: Python multiplication of two list


code:
def smooth(series, delta=2, tol=0.001):
    it = iter(series)
    last = next(it)
    yield last
    for i in it:
        while abs(i - (last + delta)) > tol:
            last += delta
            yield last
        last = i
        yield last

rawDescription: How do I fill an unknown size gap in an series

description: Fill an unknown size gap in an series


rawDescription: Setting a variable equal to a returned value from a for loop in Python


code:
import luigi

from luigi.s3 import S3Target

from somewhere import do_something_with

class MyS3File(luigi.ExternalTask):

    def output(self):
        return luigi.S3Target('s3://my-bucket/path/to/file')

class ProcessS3File(luigi.Task):

    def requires(self):
        return MyS3File()

    def output(self):
        return luigi.S3Target('s3://my-bucket/path/to/output-file')

    def run(self):
        result = None
        # this will return a file stream that reads the file from your aws s3 bucket
        with self.input().open('r') as f:
            result = do_something_with(f)

        # and the you
        out_file = self.output().open('w')
        # it'd better to serialize this result before writing it to a file, but this is a pretty simple example
        out_file.write(result)

rawDescription: Luigi Pipeline beginning in S3

description: Luigi Pipeline beginning in S3


code:
for i in range(max_iterations):
    hx = s.sigmoid(np.dot(X, theta)) # this will probably be > 0.5 initially
    d = y - hx # then this will be "very" negative when y is 0
    theta = theta + alpha*np.dot(np.transpose(X),d) # (1)
    ll[i] = sum(y * np.log(hx) + (1-y) * np.log(1- hx))

rawDescription: Batch Gradient Descent for Logistic Regression


code:
def __repr__(self):
    strs = []
    for x in self:
        strs.append(str(x))
    return '[%s]' % ', '.join(strs)

rawDescription: Print class that uses __getitem__ in python as list


code: np.reshape(float_array, (100, 100))

rawDescription: Vectorize python function

description: Vectorize python function


code:
datestr = "Wed Apr 24 19:25:06 2013 GMT"
time.mktime(time.strptime(datestr, "%a %b %d %H:%M:%S %Y %Z")) * 1000
timestamp = 1366831506000
time.strftime("%a %d %b %Y %H:%M:%S GMT", time.gmtime(timestamp / 1000.0))

rawDescription: python linux timestamp to date time and reverse

description: Python linux timestamp to date time and reverse


code:
import re
text = 'Not foo. Not No foo. Not foo or bar. No foo and no bar. Not bar or foo. Not bar or foo or banana. Not bar or banana or foo. Not bar, banana, or foo. Not bar, foo, or banana. This is a group of Text. There is no foo. There is no bar. There is no foo or bar. There is no bar or foo. I have coffee. I have a bar. No bar for you. Nonono, this is the wrong foo. Nono this is also a wrong foo. Anonymous foo.'
keywords = ['foo']
negated = ['no', 'not']

phraselist = re.split(r'\.\s', text)

out = {}

for phrase in phraselist:
    for keyword in keywords:
        for neg in negated:
            regex = re.compile(r'\b{!s}\b.+\b{!s}\b'.format(neg, keyword), re.I)
            if regex.search(phrase.lower()):
                try:
                    if not phrase in out[keyword]:
                        out[keyword].append(phrase)
                except KeyError:
                    out[keyword] = [phrase]

print(out)

expected = 'Not foo. Not No foo. Not foo or bar. No foo and no bar. Not bar or foo. Not bar or foo or banana. Not bar or banana or foo. Not bar, banana, or foo. Not bar, foo or banana. There is no foo. There is no foor or bar. There is no bar or foo.'
print(expected)

rawDescription: Skipping an unknown number of words in python


code: desired = something.pivot(index='index', columns='cols')

rawDescription: reshaping data frame in pandas

description: Reshaping data frame in pandas


code:
expected = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
# Test recursive generator using Node.__iter__
assert [str(n) for n in tree] == expected

# test non-recursive Iterator
assert [str(n) for n in node_depth_first_iter(tree)] == expected

rawDescription: Implementing a depth-first tree iterator in Python


code:
df['r_c8c11']=df['c11']*1.0/df['c8'] #if your dtype for these columns are int
df.sort(columns=['r_c8c11'])

rawDescription: How to sort and select pandas data

description: Sort and select pandas data


rawDescription: raw_input() with With White Spaces in Between the Inputs in Python 2

description: Raw_input() with With White Spaces in Between the Inputs in Python 2


code:
def process_new_file():
    try:
        filename = check_for_new_file()   # raises ValueError if no file ready
    except NoneReady:
        return
    in_file = open(filename, 'rb')
    csv_file_in = csv.reader(in_file)
    out_file = open(MASTER_CSV, 'rb+')
    csv_file_out = csv.writer(out_file)
    for row in csv_file_in:
        csv_file_out.write(row)
    csv_file_out.close()
    csv_file_in.close()
    shutil.move(filename, PROCESSED)

rawDescription: Updating CSV files automatically

description: Updating CSV files automatically


code: plot(w, e)

rawDescription: how to variate a parameter in an equation python

description: Variate a parameter in an equation python


rawDescription: Splicing mRNA using for a while loops

description: Splicing mRNA using for a while loops


code:
def update_object():
   object.x += object_vx
   object.y += object.vy

# this is your main game loop
while running:
    ...
    update_object()

rawDescription: Pygame move object position from one point to another at constant speed


code: output = inputstr.rpartition('.')[0]

rawDescription: Remove the last part of string separated with dot in Python


code:
log = os.popen("log.sh").read()
for line in log.splitlines(True):
   ...

rawDescription: Finding a line in a Python string (not file)


code:
import numpy as np

# create a (5, 5) array containing unique integers drawn from [0, 100]
uarray = np.random.choice(np.arange(0, 101), replace=False, size=(5, 5))

# check that each item occurs only once
print(np.bincount(uarray.ravel()).sum() == uarray.size)
# True

rawDescription: Using Numpy Array to Create Unique Array


code:
from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.set_preference('plugin.default_plugin_disabled', False)

driver = webdriver.Firefox(firefox_profile=profile)

rawDescription: Selenium: How to click on the install plugins button?


code:
# simple version, easy to understand and fast enough
#   up to maybe a thousand digits

def next_palindrome(n):
    """
    Find the first integer p such that p > n and p is palindromic
    """
    # There are two forms of palindrome:
    #   even number of digits,     abccba
    #   odd number of digits,      abcba
    # Find abc
    s = str(n)
    abc = s[:(len(s) + 1) // 2]

    # There are six possibilites for p:
    #
    #   abcpq  <  abcba    -> p = abcba
    #   abcpq  >= abcba    -> p = ab(c + 1)ba      (with carries as needed)
    #   abcpqr == 999999   -> p = 1000001          *(num digits + 1)
    #
    #   abcpqr <  abccba   -> p = abccba
    #   abcpqr >= abccba   -> p = ab(c+1)(c+1)ba   (with carries as needed)
    #   abcpq  == 99999    -> p = 100001           *(num digits + 1)
    #
    #  *Note that the even-number-of-9s case is properly handled by
    #    odd-digits-with-carry, but odd-number-of-9s needs special handling
    #
    # Make basis substrings
    cba  = abc[::-1]
    ba   = cba[1:]
    abc1 = str(int(abc) + 1)
    cba1 = abc1[::-1]
    ba1  = cba1[1:]
    # Assemble candidate values
    candidates = [
        int(abc  + ba),        # abcba
        int(abc1 + ba1),       # ab(c+1)ba
        int(abc  + cba),       # abccba
        int(abc1 + cba1),      # ab(c+1)(c+1)ba
        int(abc1[:-1] + ba1)   # handles odd-number-of-9s
    ]
    # Find the lowest candidate > n
    return min(c for c in candidates if c > n)

def main():
    while True:
        n = int(input("\nValue for n (or -1 to quit): "))
        if n == -1:
            break
        else:
            print("Next palindrome is {}".format(next_palindrome(n)))

if __name__ == "__main__":
    main()

rawDescription: Speeding Up Python 3.4 Code

description: Speeding Up Python 3.4 Code


code:
for s in map(lambda x: "".join(x),itertools.product(*letts)):
    print(s)

rawDescription: Python 2D array with same values

description: Python 2D array with same values


rawDescription: Python standard library function for rearranging a list


rawDescription: Hiding axis text in matplotlib plots

description: Hiding axis text in matplotlib plots


code:
def __init__(self, *args, **kwargs):
    model_value = kwargs.pop('my_value', None)
    super(MyForm, self).__init__(*args, **kwargs)
    if model_value is not None:
        self.fields['my_choices'].queryset = SomeModel.objects.filter(my_field=my_value)

rawDescription: Construct form from queryset

description: Construct form from queryset


rawDescription: Using chdir to move up a directory in Python


code:
from Tkinter import *

def displayButton(root,employNum, employPass):

    Label(root,text = employNum.get() ).grid(row = 3, column = 1, sticky = N+S+W+E)
    Label(root, text = employPass.get()).grid(row = 4, column = 1, sticky = N+S+W+E)

def main():

    root = Tk()

    Label(root, text = 'Employee Number: ').grid(row = 0, column = 0, sticky = W)
    Label(root, text = 'Login Password: ').grid(row = 1, column = 0, sticky = W)

    employeeNum = StringVar()
    employeePass = StringVar()
    Entry(root, textvariable = employeeNum).grid(row = 0, column = 1, columnspan = 2, sticky = W)
    Entry(root, textvariable = employeePass).grid(row = 1, column = 1, columnspan = 2, sticky = W)

    checkButton = BooleanVar()
    Checkbutton(root, text = 'Remember Me', variable = checkButton).grid(row = 2, column = 1, sticky = W)

    Button(root, text = 'Save', relief = RAISED).grid(row = 2, column = 2, sticky = E)
    display = Button(root, text = 'Display', relief = RAISED, command = lambda: displayButton(root, employeeNum,employeePass))
    display.grid(row = 3, column = 2, sticky = E)
    #display.bind('<Button-1>', displayButton)

    Label(root, text = "Employee's number is ").grid(row = 3, column = 0, sticky = W)
    Label(root, text = "Employee's Passowrd is ").grid(row =4 , column = 0, sticky = W)
    root.mainloop()

main()

rawDescription: Pass multiple arguments to a function in tkinter


code:
input_array = np.array([1, 2, 3, 4])
(input_array[:,None] + extend_array).ravel()

rawDescription: Vectorize numpy array expansion

description: Vectorize numpy array expansion


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

e = np.e
X, Y = np.meshgrid(np.linspace(0, 5, 100), np.linspace(0, 5, 100))
F = X ** Y
G = Y ** X

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
plt.contour(X, Y, (F - G), [0])
plt.plot([e], [e], 'g.', markersize=20.0)
plt.show()

rawDescription: matplotlib: add circle to plot

description: Matplotlib: add circle to plot


code: sum(len(x) for x in d['childs'].itervalues())

rawDescription: Count the number of items from a dictionary inside another dictionary in Python


code:
import math
def turnpixel(Nix,Niy):
    for ix in range(sx):
        for iy in range(sy):
            r=int(math.sqrt((Nix-ix)**2+(Niy-iy)**2))
            def convfunc(o,v):
                return o+int(v/(r*20+1))
            px2[Nix,Niy]=tuple(map(convfunc,px2[Nix,Niy],px[ix,iy]))
            if sum(px2[Nix,Niy])>=3*250:
                return

rawDescription: Simple "blurring" of an array representing an image in python from first principles


code: in_df = pd.read_excel("test.xls", header=0)

rawDescription: Pandas - read_table read selected lines

description: Pandas - read_table read selected lines


code:
data[a]['state'] = lines[i + 1].split('"')[1]
# etc. for each call of lines[i + 1]

rawDescription: Splitting or stripping a variable number of characters from a line of text in Python?


code: endProgram = userInput == 'no'

rawDescription: Validating user input strings in Python

description: Validating user input strings in Python


rawDescription: randomly fill 2d matrix with conditions

description: Randomly fill 2d matrix with conditions


code: ddot = np.einsum('ij,jk,ik->i',x,inv,x)

rawDescription: How to write this numpy code in vectorized form?

description: Write this numpy code in vectorized form


code:
from __future__ import unicode_literals
from django.contrib.auth.backends import ModelBackend
from ai60.accounts.models import Account
from ai60.accounts.phone_token import PhoneTokenGenerator

from mezzanine.utils.models import get_user_model

User = get_user_model()

class AI60AccountBackend(ModelBackend):
    """
    Extends Django's ``ModelBackend`` to allow login via phone and token, or
    phone and password, or email and password.
    """

    def authenticate(self, **kwargs):
        if not kwargs:
            return

        if 'phone' in kwargs and 'token' in kwargs:
            phone = kwargs.pop('phone', None)
            request = kwargs.pop('request', None)
            token = kwargs.pop('token', None)

            phone_token = PhoneTokenGenerator(request)
            if phone_token.check_token(phone, token) == '':
                try:
                    user = Account.objects.get(phone=phone).user
                    return user
                except Account.DoesNotExist:
                    return

        if 'phone' in kwargs and 'password' in kwargs:
            phone = kwargs.pop('phone', None)
            password = kwargs.pop('password', None)
            try:
                user = Account.objects.get(phone=phone).user
                if user.check_password(password):
                    return user
            except Account.DoesNotExist:
                return

        if 'email' in kwargs and 'password' in kwargs:
            email = kwargs.pop('email', None)
            password = kwargs.pop('password', None)
            try:
                user = User.objects.get(email=email)
                if user.check_password(password):
                    return user
            except User.DoesNotExist:
                return

rawDescription: How to make custom authentication not based on User model

description: Make custom authentication not based on User model


rawDescription: Adding column In table with Python

description: Adding column In table with Python


rawDescription: Accessing data in a Pandas dataframe with one row


rawDescription: numpy array that is (n,1) and (n,)

description: Numpy array that is (n,1) and (n,)


code: df.replace([np.inf, -np.inf], np.nan).dropna(subset=["col1", "col2"], how="all")

rawDescription: dropping infinite values from dataframes in pandas?

description: Dropping infinite values from dataframes in pandas


rawDescription: Matrix multiplication gives unsual result in Python (SciPy/PyLab)


code:
for name in request.POST:
    if not name.startswith('order['): continue
    id_ = name.split('[')[1].split(']')[0]
    order = request.POST[name]
    # Do something with `id_`, `order`

rawDescription: Saving the order of items

description: Saving the order of items


code:
def delete_substring_blocks(s, blocks):
    return ''.join(delete_blocks(s, blocks))

rawDescription: Python: delete substring by indices

description: Python: delete substring by indices


code:
def transpose_matrix(matrix):
    return list(map(list, zip(*matrix)))

rawDescription: Transpose this matrix(python3)

description: Transpose this matrix(python3)


code:
import numpy as np

import pandas as pd
from sklearn import datasets, linear_model

# Load the diabetes dataset
diabetes = datasets.load_diabetes()

# Use only one feature
diabetes_X = diabetes.data[:, np.newaxis, 2]

# Split the data into training/testing sets
diabetes_X_train = diabetes_X[:-20]
diabetes_X_test = diabetes_X[-20:]

# Split the targets into training/testing sets
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]

# Create linear regression object
regr = linear_model.LinearRegression()

# Train the model using the training sets
regr.fit(diabetes_X_train, diabetes_y_train)

print(regr.predict(diabetes_X_test))

df = pd.DataFrame(regr.predict(diabetes_X_test))

print(df)

rawDescription: Adding scikit-klearn (sklearn) prediction to pandas data frame


rawDescription: Hexagonal Self-Organizing map in Python

description: Hexagonal Self-Organizing map in Python


code:
s = 'UAE \xe2\x80\xaa>\xe2\x80\xaa\n            \n                Dubai \xe2\x80\xaa>\xe2\x80\xaa\n            \n                Business Bay \xe2\x80\xaa>\xe2\x80\xaa\n            \n                Executive Towers \n            \n\n\n        \n\n\n\t    \n\t        \n\t    \n\t\n\n\n        \n        ;\n        \n            \n                \n                    1.4 km from Burj Khalifa Tower'
cleanup(s)

rawDescription: python strip function not working properly

description: Python strip function not working properly


code:
mergedData = {}
with open('file1.txt', 'r') as file1, open('file2.txt', 'r') as file2, open('mergedData.txt', 'w') as outfile:
    for line in file1:
        mergedData[line.split()[0].lstrip('0')] = [line]
    for line in file2:
        mergedData[line.split()[0]].append(" ".join(line.split()[:4]))
    for k in mergedData:
        outfile.write("\n".join(mergedData[k]) + "\n")

rawDescription: Python: Search a text file and then output specific data


code:
import bisect

def caught_speeding(speed):
   tickets = [60, 80]
   return bisect.bisect_left(tickets, speed)

rawDescription: How to get rid of bunch of ifs

description: Get rid of bunch of ifs


code:
from collections import defaultdict
defdic = defaultdict(int)
for letter, frequency in zip(level, frequency):
    defdic[letter] += frequency

x,y = list(defdic.keys()), list(defdic.values())

# or better yet as proposed by Bharel
x, y = zip(*defdic.items())

rawDescription: Python calculations in two groups

description: Python calculations in two groups


code:
class NewEntry(webapp.RequestHandler):

    def post(self):
        form_data =  EntryForm(self.request.POST)

        if form_data.is_valid():
            c = self.request.get("category")
            cat_get = Category.all().filter("title =", c).get()
            new_entry = form_data.save(commit=False)
            new_entry.category = cat_get
            new_entry.put()
            self.redirect("/main" )
        else:
            self.response.set_status(500)

rawDescription: GAE: How to use ReferenceProperty in django forms?


code:
numbers = set([1,2,5,8,13,15,26,38])
target = 10
for first in numbers:
    second = target - first
    if second > first and second in numbers:
        print(first, second)

rawDescription: Why is my for loop skipping an element in my list?


code:
self.labelVariable
self.entryVariable

rawDescription: python to add variables to list by identifying from a line

description: Python to add variables to list by identifying from a line


code:
f = open("outfile.txt", "w")
f.write("First ")  # No newline, line continues
f.write("line")
f.write("\n")      # Line ends!
f.write("Second line\n")  # Newline character in the same write
f.close()

rawDescription: python script to automatically write a text file

description: Python script to automatically write a text file


code:
def addLink(url):
    self.UI.addLink(url[0], url[1])

self.Scraper.GetSubUrls(url, addLink)

rawDescription: Using an anonymous function in Python

description: Using an anonymous function in Python


rawDescription: Merge Dictionaries in Python

description: Merge Dictionaries in Python


rawDescription: Normalize Array in Python

description: Normalize Array in Python


code:
def yad(decorators):
    def decorator(f):
        for d in reversed(decorators):
            f = d(f)
        return f
    return decorator

rawDescription: Apply a list of decorators to a callable?


rawDescription: Set DataFrame row index to a different column


code:
from datetime import datetime
s = '2012-12-24T00:00:00Z'
d = datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')
'{0:%A}'.format(d)

rawDescription: Find Out What Days an Event is On With Google Calendar?


code:
import example
d = example.make_derived()
d.foo()
class Spam(example.Base):
    def foo(self):
        return 101

s = Spam()
s.foo()

rawDescription: how to access derived class object from abstract class in boost python

description: Access derived class object from abstract class in boost python


code:
shutil.copytree('/Full/Path', 'target',
              ignore=lambda directory, contents: ['Common'] if directory == '/Full/Path/To/aDir' else [])

rawDescription: Filter directory when using shutil.copytree?


code: np.savez("tmp.npz", *(np.arange(i) for i in range(2, 100)))

rawDescription: Python: How to pass a generator to a function?


code:
from numpy.ctypeslib import ndpointer
import ctypes
so = ctypes.CDLL('plainc.so')
foobar_c = so.foobar
foobar_c.restype = None
foobar_c.argtypes = (
    ctypes.c_long,
    ctypes.c_long,
    ndpointer(dtype=np.int64, ndim=1),
    ndpointer(dtype=np.float64, ndim=2),
    ndpointer(dtype=np.float64, ndim=1)
)

t4 = clock()
foobar_c(mixinsize, count, xs, mixins, acc)
t5 = clock()
print("elapsed time with plain C: %g ms" % (1000*(t5-t4),))

rawDescription: How to shove this loop into numpy?

description: Shove this loop into numpy


code:
scores = {}
read = open("C:/Users/renato/Desktop/HTML Files/myfile.txt")
for cont in read:
    (name,score)=cont.split()
    scores[float(score)] = name
read.close()

print("The top scores are: ")
for eachscore in sorted(scores.keys(), reverse = True):
    print("Surfer "+scores[eachscore]+" scored "+str(eachscore))

rawDescription: Sorted() function Python

description: Sorted() function Python


code:
phone_number = toasted_tree.xpath('//b/text()')[0]
phone_number = int(phone_number.replace('-', ''))

rawDescription: Convert List to Int with Python

description: Convert List to Int with Python


code:
import csv
my_d = []
for i in datalist:
    my_d.append({x:y for x,y in i})

with open("file.csv",'wb') as f:
   # Using dictionary keys as fieldnames for the CSV file header
   writer = csv.DictWriter(f, my_d[1].keys())
   writer.writeheader()
   for d in my_d:
      writer.writerow(d)

rawDescription: How to write a list of tuple in python with header mapping

description: Write a list of tuple in python with header mapping


code:
ENUM = 247

CHAR = TINY
INTERVAL = ENUM

def create_dict( dicForReversing ):
  fieldTypeDic = {}
  for key, value in dicForReversing.items():
    if isinstance(value, int):
      if not value in fieldTypeDic:
        fieldTypeDic[ value ] = set()
      fieldTypeDic[ value ].add( key )
  return fieldTypeDic
fieldTypeDic = create_dict( vars() )

rawDescription: is there a way to get a (static) method to be called when a class (not an instance) is created?

description: Is there a way to get a (static) method to be called when a class (not an instance) is created


rawDescription: check for value in list of Pandas data frame columns

description: Check for value in list of Pandas data frame columns


code:
def dump(self, file_name, page_size=10, vtimeout=10, sep='\n'):
    """Utility function to dump the messages in a queue to a file
    NOTE: Page size must be < 10 else SQS errors"""

rawDescription: How to get all messages in Amazon SQS queue using boto library in Python?

description: Get all messages in Amazon SQS queue using boto library in Python


code:
def integral(integrand,initial_value,dt):
    int_rec = cons_stream(initial_value,
                          add_streams(scale_stream(integrand,dt),
                                      int_rec))
    return int_rec

rawDescription: SICP "streams as signals" in Python

description: SICP "streams as signals" in Python


rawDescription: compare similar items nested in a list, and removing them

description: Compare similar items nested in a list, and removing them


code:
L = [1,2,3,4,5,6]
it = zip(*[iter(L)] * 2)
[y for x in it for y in x + (None,)]

rawDescription: How to insert None into a list?

description: Insert None into a list


rawDescription: Selenium Webdriver Python page object MainPageLocators class why does it use an asterisk infront of the class name


code:
mylist = [1,2,3]
mylist.append(5).append(3) # Throws error 'NoneType' object has no attribute 'append'

rawDescription: Return statement in method that modifies in-place


code:
import struct

def float_from_integer(integer):
    return struct.unpack('!f', struct.pack('!I', integer))[0]

assert float_from_integer(1066192077) == 1.100000023841858

rawDescription: How to interpret a integer as a float

description: Interpret a integer as a float


rawDescription: Django slice template tag not working with negative indices


code: divisibleBySeven = [num for num in inputList if num and num % 7]

rawDescription: Return Subset of List that Matches Condition


code: array ^= numpy.random.rand(len(array)) < prob

rawDescription: python, numpy boolean array: negation in where statement

description: Python, numpy boolean array: negation in where statement


code: from common import logtool

rawDescription: define python logger in one script and use it in all other scripts

description: Define python logger in one script and use it in all other scripts


code: bases = Foo.mro()

rawDescription: Get the list of a class's variables & methods in Python


code: y = ['Relationships', 'Games', ...]

rawDescription: How do I use use the tfidf-calculating functions in scikit-learn?

description: Use use the tfidf-calculating functions in scikit-learn


code: maxlist = max(myDict.values())

rawDescription: How to pass a dynamic number of arguments to a function?

description: Pass a dynamic number of arguments to a function


code:
def right_shift(data, bits):
    sign = (data >> 31) & 1
    if sign:
       fills = ((sign << bits) - 1) << (32 - bits)
    else:
       fills = 0
    return ((data & 0xffffffff) >> bits) | fills

rawDescription: Special JS operators in python

description: Special JS operators in python


code:
print("Calculator")

var1 = input("Give the first number: ")
var2 = input("Give the second number: ")

print("(1) +\n(2) -\n(3) *\n(4) /\n(5)Change numbers\n(6)Quit")
print("Current numbers: " + var1 + " " + var2)

while True:
    opcion = input("Please select something (1-6): ")
    if (opcion == "1"):
        var3 = int(var1) + int(var2)
        print("The result is: " + str(var3))
    elif (opcion == "2"):
        var3 = int(var1) - int(var2)
        print("The result is: " + str(var3))
    elif (opcion == "3"):
        var3 = int(var1) * int(var2)
        print("The result is: " + str(var3))
    elif (opcion == "4"):
        var3 = int(var1) / int(var2)
        print("The result is: " + str(var3))
    elif (opcion == "5"):
        var1 = input("Give the first number: ")
        var2 = input("Give the second number: ")
    elif (opcion == "6"):
        break
    else:
        print("Selection was not correct.")

print("Thank you!")

rawDescription: Python: I fell in an infinite loop

description: Python: I fell in an infinite loop


code:
s = frozenset('PMMM')
# now s == frozenset({'P', 'M'})

rawDescription: Python: converting string to flags

description: Python: converting string to flags


code:
def make_fun(parameters):
    exec("def f_make_fun({}): pass".format(', '.join(parameters)))
    return locals()['f_make_fun']

rawDescription: Programmatically create function specification


code:
titles =  ['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']
pages =  [1, 2, 3]

finalDict = {}
for title, page in zip(titles, pages):
    for word in title.split(" "):
        if word not in finalDict.keys():
            finalDict[word] = [int(page)]
        else:
            finalDict[word] += [int(page)]

print(finalDict)

rawDescription: python create dictionary from list of strings and list of integers

description: Python create dictionary from list of strings and list of integers


code:
global binoInitiated
binoInitiated=False;
def binoMixture(minimum,maximum,sampleSize):
    global centers
    binoNumber=10;
    if (not binoInitiated):
        centers=np.random.randint(minimum,maximum+1,binoNumber)
    sigma=maximum-minimum-2
    sam=np.array([]);
    while sam.size<sampleSize:
        i=np.random.choice(binoNumber);
        temp=np.random.binomial(sigma, 0.5,1)+centers[i]-sigma/2+1
        sam=np.append(sam,temp)
    return sam

rawDescription: Generating a mixture of binomial distributions


code: realPassword = passwords[whichUser]

rawDescription: How to check if the second list element on a line in a file contains 'x'?

description: Check if the second list element on a line in a file contains 'x'


code: result += final

rawDescription: parse text using bash/python

description: Parse text using bash/python


code:
args = parser.parse_args()
num_players = args.number if args.number else 30

rawDescription: Python - Optional Command Line Argument

description: Python - Optional Command Line Argument


code:
for item in func_list:
     if item.startswith('__'):
         getattr(self, '_' + self.__class__.__name__+ item)()
     else:
         getattr(self, item)()

rawDescription: Call methods by string

description: Call methods by string


rawDescription: OSX : Defining a new URL handler that points straight at a Python script


code: # Create or update the resource group using the specified template file and template parameters file

rawDescription: How to create azure virtual machine via api?? (not the classic one, the one which on new azure manage portal)

description: Create azure virtual machine via api?? (not the classic one, the one which on new azure manage portal)


code:
a = ['a','b','c','d']
for i,x in enumerate(a):
    print(i,x)

rawDescription: Urllib and saving multiple urls to different filenames


code:
if __name__ != '__main__':
    from ._import_package_files import *  # defines __all__
    __all__.remove('__all__')  # prevent export (optional)

rawDescription: Importing Python classes from different files in a subdirectory


code:
reader = csv.reader(f, delimiter='\t')
reader = csv.reader(f, delimiter=' ')

rawDescription: Finding A Total Cost

description: Finding A Total Cost


code:
def __init__(self,master):
    self.master = master
    self.create_widgets()

rawDescription: Creating buttons with Python GUI

description: Creating buttons with Python GUI


code:
import lxml.etree as ET

...

dom = ET.fromstring(response.text)
tree_out = ET.tostring(dom, pretty_print=True)

xmlfile = open('Output.xml', 'wb')
xmlfile.write(tree_out)
xmlfile.close()

rawDescription: Write Python NTLM XML response to local XML file


code: res_x, res_y = calculate_coordinates(spam, ham, eggs)

rawDescription: Assign attribute to function

description: Assign attribute to function


code:
wordcount = {}

with open('alice.txt') as file:  # with can auto close the file
    for word in file.read().split():
        if word not in wordcount:
            wordcount[word] = 1
        else:
            wordcount[word] += 1

wordcount = sorted(wordcount.items(), key=lambda x: x[1], reverse=True)

for k, v in wordcount[:5]:
    print(k, v)

rawDescription: Python word count program from txt file

description: Python word count program from txt file


code:
list1 = [1,2,3]
list2 = [3,4,5,3,3]

itemcounter = {item:count for item, count in [(item, list2.count(item)) for item in set(list1)]}
final_counts = [(item, count) for item, count in itemcounter.iteritems()]

print(final_counts)

rawDescription: Frequency of common elements between lists in python 2.7


rawDescription: pandas date column subtraction

description: Pandas date column subtraction


code:
#!/home/myuser/my_python/bin/python

import numpy

# script here

rawDescription: Python web hosting: Numpy, Matplotlib, Scientific Computing


rawDescription: Binary I/O in Python

description: Binary I/O in Python


code:
__author__ =  'Isaac Alderton'
__authorEmail__ =  'Isaacary92@gmail.com'
from Tkinter import *

class Application(Frame):
    """ My smart board application"""
    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid(column=0, row=0, sticky="ew")
        self.create_widgets()
        for i in range(5):
            self.columnconfigure(i, weight=1)
        self.rowconfigure(0, weight=1)

    def create_widgets(self):

    #Button1
    #buttons ment to span across the width of the page
    #needs linking to google calander
        self.button1 = Button(self, text = "        Calandar        ")
        self.button1.grid(row=0, column = 0, sticky="ew")

    #button2
        self.button2 = Button(self, text = "        weather        ")
        self.button2.grid(row=0, column = 1, sticky="ew")

    #button3
    #defult home menu in the future user sets a new home
        self.button3 = Button(self, text = "        Whiteboard        ")
        self.button3.grid(row=0, column = 2, sticky="ew")

    #button4
        self.button4 = Button(self, text = "        Internet        ")
        self.button4.grid(row=0, column = 3, sticky="ew")

    #button5
        self.button5 = Button(self, text = "        Settings        ")
        self.button5.grid(row=0, column = 4, sticky="ew")
    #def settings():
        #pop up window where the settings options have wifi screen brightness     sleep options
        #and also account settings
        #One day also ui changes so color themes etc

#Canvas
#canvas ment to be part of whiteboard screen not a "pop-up"
#canvas is ment to fill the whole page

def xy(event):
    global lastx, lasty
    lastx, lasty = event.x, event.y

def addLine(event):
    global lastx, lasty
    canvas.create_line((lastx, lasty, event.x, event.y))
    lastx, lasty = event.x, event.y

root = Tk()
root.columnconfigure(0, weight=1)
root.rowconfigure(1, weight=1)

canvas = Canvas(root)
canvas.grid(column=0, row=1, sticky="nesw")
canvas.bind("<Button-1>", xy)
canvas.bind("<B1-Motion>", addLine)

#endof canvas
#root = Tk()
root.title("Smartboard")
#Geometry is ment to fit device????

root.geometry("530x500")
app = Application(root)

root.mainloop()

 #  Copyright {2015} {Isaac Alderton}

rawDescription: I cant get the canvas to work how i wanted it to


code:
#!/usr/bin/env python

orig=[]
nex=[]

with open("bat.txt") as fd:
    fd.readline()
    for line in fd:
        orig.append(line.split()[0])
        nex.append(line.split()[2])

col=[i for i in zip(orig, nex)]

rawDescription: Read selected columns from text file into a list in python


code:
nums = numpy.ones(1000)
nums[:100] = 0
numpy.random.shuffle(nums)

rawDescription: Generate random array of 0 and 1 with specific ratio (python , numpy)


code: c = Counter(result)

rawDescription: Count how many times a tuple appears in ouput results


code: row = np.random.randint(0,100, size=(1,100))

rawDescription: What is the best way to incrementally build a numpy array?


rawDescription: What happened to thread.start_new_thread in python 3


code:
logmax = log(Xmax + 1, b)
X = b ** (logmax * (V - Vmin) / (Vmax - Vmin)) - 1
V = (Vmax - Vmin) * log(X + 1, b) / logmax + Vmin

rawDescription: Linear X Logarithmic scale

description: Linear X Logarithmic scale


code:
import json
from json import dumps

json_dict = {}
json_dict['group_list'] = []
for grp, grp_data in df.groupby('Group'):
    grp_dict = {}
    grp_dict['group'] = grp
    for cat, cat_data in grp_data.groupby('Category'):
        grp_dict['category_list'] = []
        cat_dict = {}
        cat_dict['category'] = cat
        cat_dict['p_list'] = []
        for p, p_data in cat_data.groupby('P'):
            p_data = p_data.drop(['Category', 'Group'], axis=1).set_index('P')
            for d in p_data.to_dict(orient='records'):
                cat_dict['p_list'].append({'p': p, 'date_list': [d]})
        grp_dict['category_list'].append(cat_dict)
    json_dict['group_list'].append(grp_dict)
json_out = dumps(json_dict)
parsed = json.loads(json_out)

rawDescription: DataFrame to nested JSON

description: DataFrame to nested JSON


code:
s = "baab"
s = s.replace('a','',1)
s

rawDescription: How do I remove a character once from a string [python]?

description: Remove a character once from a string [python]


code: newArray = 0.5*(originalArray[0::2] + originalArray[1::2])

rawDescription: Fast way to take average of every N rows in a .npy array


code: res_T = res.T

rawDescription: Seeking a more efficient python numpy ravel+reshape


code:
class City(object):
   # ...
   @property
   def text_string(self):
      return self.text_strings.text_string

rawDescription: How to query multiple tables in SQLAlchemy ORM

description: Query multiple tables in SQLAlchemy ORM


code:
def pad_or_truncate(some_list, target_len):
    return some_list[:target_len] + [0]*(target_len - len(some_list))

rawDescription: Most pythonic way to extend a list to exactly a certain length?


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

# Need to display the result of imshow on an axis
fig=plt.figure()
ax=fig.add_subplot(111)

# Save fig a with one cmap
a=np.random.rand(20,20)
figa=ax.imshow(a,cmap='jet')

# Save fig b with a different cmap
b=np.random.rand(20,20)
figb=ax.imshow(a,cmap='copper')

# Have to show the figure to generate the rgbacache
fig.show()

# Get the array of data
figa=figa._rgbacache
figb=figb._rgbacache

# Stitch the two arrays together
figc=np.concatenate((figa,figb),axis=1)

# Save without a cmap, to preserve the ones you saved earlier
plt.imsave('figc.png',figc,cmap=None)

rawDescription: concatenate two images from plt.imsave with different cmaps without installing another package

description: Concatenate two images from plt.imsave with different cmaps without installing another package


code: perms = Permission.objects.filter(**{user_groups_query + '__pk': user_obj})

rawDescription: Error while logging in when primary key of Django `User` is a `CharField`


code:
import nltk  # Natural Language Toolkit
from collections import Counter
sum(x in {"Spot", "brown", "hair"} for x in nltk.wordpunct_tokenize(s))

rawDescription: Counting occurrences of multiple strings in another string


rawDescription: How can I detect when a Django server is started without a settings module?

description: Detect when a Django server is started without a settings module


rawDescription: ChromeDriver Quits Unexpectedly

description: ChromeDriver Quits Unexpectedly


code:
grouped = live.groupby(by=['prglength', 'first_babies']).size()
unstacked_count = grouped.size().unstack()

rawDescription: Stacked bar plots from two different sources in Pandas


code:
arr = np.empty((3, 5))  # the size of the final, biggest array
smallarr = arr[:, :-1]

rawDescription: Best way to add a new column to a Numpy array

description: Add a new column to a Numpy array


rawDescription: Pandas: Take the median accross multiple dataframe


code:
import lxml.html, lxml.etree

url_cooking = 'http://cooking.stackexchange.com/feeds'

ns = 'http://www.w3.org/2005/Atom'
ns_map = {'ns': ns}

data = lxml.etree.parse(url_cooking)
summary_nodes = data.xpath('//ns:feed/ns:entry/ns:summary', namespaces=ns_map)
print('Found ' + str(len(summary_nodes)) + ' summary nodes')

rawDescription: lxml - difficulty parsing stackexchange rss feed

description: Lxml - difficulty parsing stackexchange rss feed


code:
import numpy as np
import pandas as pd

# Sample 100 rows of data to determine dtypes.
df_test = pd.read_csv(filename, nrows=100)

float_cols = [c for c in df_test if df_test[c].dtype == "float64"]
float32_cols = {c: np.float32 for c in float_cols}

df = pd.read_csv(filename, engine='c', dtype=float32_cols)

rawDescription: How to force pandas read_csv to use float32 for all float columns?

description: Force pandas read_csv to use float32 for all float columns


code:
import types
ns = types.SimpleNamespace(alfa = 1, bravo = 2, charlie = 3)
[x for x in dir(ns) if not x.startswith('__')]

rawDescription: How to get all user defined attributes in types.SimpleNamespace type?

description: Get all user defined attributes in types.SimpleNamespace type


code:
for word in words:
    unicode(word, "utf-8").isalpha()

rawDescription: Check whether a string is alphabetical for languages other than english


code:
from operator import add

def to_lower(s, trans=dict(zip(UPPERCASE, LOWERCASE))):
    return reduce(add, (trans.get(ch,ch) for ch in s), '')

rawDescription: Creating my own string functions

description: Creating my own string functions


rawDescription: How do you stop the scipy.optimize.fmin function and start it again using the optimization history?

description: Stop the scipy.optimize.fmin function and start it again using the optimization history


rawDescription: Why does setattr fail on a bound method

description: Why does setattr fail on a bound method


code:
get_with_default('blue', colours, 'green')
get_with_default('black', colours, 'green')

rawDescription: Filter a list of dictionaries to always return a single dictionary, given a default key value to lookup


rawDescription: Conditional indexing with Numpy ndarray

description: Conditional indexing with Numpy ndarray


rawDescription: Pivoted pandas dataframe to dictionary

description: Pivoted pandas dataframe to dictionary


rawDescription: How to split csv files into multiple files using the delimiter? python

description: Split csv files into multiple files using the delimiter? python


rawDescription: How to hide herokuapp.com site built in Django when the site is live

description: Hide herokuapp.com site built in Django when the site is live


code:
for l in fruit:
    print(l[1])

rawDescription: Python - Iterate through list of list strings


code:
img = client.images.find(name='cirros-0.3.2-x86_64-uec')

file_name = "%s.img" % img.name
image_file = open(file_name, 'w+')

for chunk in img.data():
    image_file.write(chunk)

rawDescription: Openstack python API: how to download image from glance using the python api


rawDescription: Find indexes of matching rows in two 2-D arrays


code:
def identity(arg): return arg

def plural_identity(*args): return args

rawDescription: Is there a standard Python function that takes any number of arguments and does nothing?


code:
for n in range(1,max+1):
    n=n+1

rawDescription: Euler's pentagonal number function in python