code:
[
    {
        'data': 'Root',
        'children': [
            {
                'data': 'Articles',
                'children': [
                    {
                        'data': 'Fiction',
                        'children': [
                            { 'data': 'Fantasy' },
                            { 'data': 'Sci-fi' }
                            ]
                    },
                    { 'data': 'Reference' }
                ]
            },
            { 'data': 'Portfolio' },
            { 'data': 'Contact' }
        ]
    }
]

rawDescription: Modified Preorder Tree Traversal to Python structure


code:
def align_yaxis(ax1, v1, ax2, v2):
    """adjust ax2 ylimit so that v2 in ax2 is aligned to v1 in ax1"""
    _, y1 = ax1.transData.transform((0, v1))
    _, y2 = ax2.transData.transform((0, v2))
    inv = ax2.transData.inverted()
    _, dy = inv.transform((0, 0)) - inv.transform((0, y1-y2))
    miny, maxy = ax2.get_ylim()
    ax2.set_ylim(miny+dy, maxy+dy)

rawDescription: Matplotlib: align origin of right axis with specific left axis value


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

def make_sparse_array():
    A = np.arange(ncol*nrow).reshape(nrow, ncol)
    row, col = zip(*np.ndindex(nrow, ncol))
    val = A.ravel()

    A = sparse.coo_matrix(
        (val, (row, col)), shape=(nrow, ncol), dtype='float')
    A = A.todia()
    # A = sparse.diags(np.ones(5), 1)
    # A = sparse.diags([np.ones(4),np.ones(3)*2,], [2,3])
    print(A.toarray())
    return A

nrow, ncol = 10, 5
A = make_sparse_array()
diags = {offset:(diag[offset:nrow+offset] if 0<=offset<=ncol else
                 diag if offset+nrow-ncol>=0 else
                 diag[:offset+nrow-ncol])
         for offset, diag in zip(A.offsets, A.data)}

for offset, diag in sorted(diags.iteritems()):
    print('{o}: {d}'.format(o=offset, d=diag))

rawDescription: Extract non-main diagonal from scipy sparse matrix?


code: FILE = open('report.pdf', "wb")

rawDescription: Write PDF file from URL using urllib2

description: Write PDF file from URL using urllib2


code:
from numpy import isfinite
isfinite(arr_a) * isfinite(arr_b)

rawDescription: create mask of non-nan matrix intersections

description: Create mask of non-nan matrix intersections


code:
import requests
import requests.packages.urllib3
from requests.packages.urllib3.fields import RequestField, guess_content_type
import six

old_iter_field_objects = requests.packages.urllib3.filepost.iter_field_objects
def iter_field_objects(fields):
    if isinstance(fields, dict):
        i = six.iteritems(fields)
    else:
        i = iter(fields)

    for field in i:
      if isinstance(field, RequestField):
        yield field
      else:
        name, value = field
        filename = value[0]
        data = value[1]
        content_type = value[2] if len(value)>2 else guess_content_type(filename)
        headers = None
        if isinstance(content_type, (tuple, list)):
            content_type, headers = content_type
        rf = RequestField(name, data, filename, headers)
        rf.make_multipart(content_type=content_type)
        yield rf
requests.packages.urllib3.filepost.iter_field_objects = iter_field_objects

rawDescription: How to add per-file custom header to multipart upload with requests?

description: Add per-file custom header to multipart upload with requests


code:
df
pd.to_datetime(df.Timestamp)

rawDescription: Python Reading in Tick Data Pandas

description: Python Reading in Tick Data Pandas


code:
items = object.items()
items.sort()

rawDescription: Readably print out a python dict() sorted by key


rawDescription: Print Decimal value from long string of little endian hex values


code:
Foo
a

rawDescription: Python function as a variable - different number of arguments


code:
class ilist(list):
    def __init__(self, r=None, dft=None):
        if r is None:
            r = []
        list.__init__(self, r)
        self.dft=dft

    def _ensure_length(n):
        maxindex = n
        if isinstance(maxindex, slice):
            maxindex = maxindex.indices(len(self))[1]
        while len(self) <= maxindex:
            self.append(self.dft)

    def __getitem__(self, n):
        self._ensure_length(n)
        return super(ilist, self).__getitem__(n)

    def __setitem__(self, n, val):
        self._ensure_length(n)
        return super(ilist, self).__getitem__(n)

rawDescription: Is there a simple way to override the list object's method __getitem__?


code:
def readingWritting(filename, data):
    with open(filename, 'w') as f:
        f.write('/'.join(data))

dataOfInputs = []
more = 'yes'

while more != '':
    name = input(">> ")
    price = input(">> ")
    count = input(">> ")

    dataOfInputs.append(name)
    dataOfInputs.append(price)
    dataOfInputs.append(count)

    print("\nDo you want to add more products?")
    more = input(">> ")

readingWritting("someFile.txt", dataOfInputs)
print("\nSuccesifully!\n")

rawDescription: Writting to file until I want to stop

description: Writting to file until I want to stop


code:
seen = set()
ans = []

ans

rawDescription: Get Unique Tuples from List , Python

description: Get Unique Tuples from List , Python


code:
def my_help(*args):
    return your_cleanup_function_here(help(*args))

rawDescription: restructuredText, docstring and python interactive shell

description: RestructuredText, docstring and python interactive shell


code:
class BeforeAfterSuite(unittest.TestSuite):
    def run(self, result):
        if len(self._tests) < 1:
            return unittest.TestSuite.run(self, result)

        first_test = self._tests[0]
        if "before" in dir(first_test):
            first_test.before()
        result = unittest.TestSuite.run(self, result)
        if "after" in dir(first_test):
            first_test.after()
        return result

rawDescription: How can I create a class-scoped test fixture in pyUnit?

description: Create a class-scoped test fixture in pyUnit


code:
def make_func(a, b):
    def f(n):
        return n**a + b
    return f

rawDescription: Is there a way to write a Python script that creates and executes code?


code: def f(): pass

rawDescription: Is a Python function stored as an object?


code:
from collections import Counter

trial = 100
counts = Counter(random.randint(1,10) for _ in range(trials))
print(counts)
Counter({3: 17, 7: 12, 8: 12, 9: 12, 4: 11, 6: 9, 2: 8, 10: 8, 5: 6, 1: 5})

for i in range(1,11):
    print("Hay exactamente un {}% de {}".format(100 * counts[i] / float(trials),i))

rawDescription: How could I make this code more "automated"?


code:
frame_count = 0
animation_frames = 4
while quit == False:
    # ...
    # snip
    # ...
    area = pygame.Rect(
        image_number * 100,
        (frame_count % animation_frames) * 150,
        100,
        150
    )
    display.blit(sprite, sprite_pos, area)
    pygame.display.flip()
    frame_count += 1

rawDescription: Pygame: Sprite animation Theory - Need Feedback


code:
import numpy as np
np.array([0.006534, -.1232], np.float16).tostring()
np.array([0.006534, -.1232], '>f2').tostring() # big-endian

rawDescription: Floating point to 16 bit Twos Complement Binary, Python


code:
from itertools import product
s1 = set((0, 1))
set(product(s1, repeat = 3))

rawDescription: Set products in Python

description: Set products in Python


rawDescription: PyQt5 QTextEdit auto completion

description: PyQt5 QTextEdit auto completion


code: el.xpath('./..')[0].styleUrl = objectify.StringElement('#' + to)

rawDescription: Replace contents of lxml StringElement with starting a namespace war?


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

data1, data2 = np.random.random((2,10,10))

fig, ax = plt.subplots()
ax.imshow(data1, extent=[-10, 0, -10, 0])
ax.imshow(data2, extent=[10, 20, 10, 20])

plt.show()

rawDescription: Matplotlib matrix/image explicitly state axis values


rawDescription: get table columns from sqlAlchemy table model

description: Get table columns from sqlAlchemy table model


rawDescription: how to get name of a file in directory using python

description: Get name of a file in directory using python


code:
class DBwithTransformation(Transformation, DB):
    pass

db = DBwithTransformation(arg1, arg2, ...)

rawDescription: Is it possible to emulate Scala's traits in Python?


code:
from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)

class UTCtzinfo(tzinfo):
    def utcoffset(self, dt):
        return ZERO

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return ZERO

utc = UTCtzinfo()
t = datetime(2015, 2, 1, 15, 16, 17, 345, tzinfo=utc)

rawDescription: How do I construct a UTC `datetime` object in Python?

description: Construct a UTC `datetime` object in Python


code:
from django import forms
from my_app.models import Product
from django.contrib.admin import widgets

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)
        self.fields['mydate'].widget = widgets.AdminDateWidget()
        self.fields['mytime'].widget = widgets.AdminTimeWidget()
        self.fields['mydatetime'].widget = widgets.AdminSplitDateTime()

rawDescription: Using Django time/date widgets in custom form


code:
exec('y=3')
y

rawDescription: eval SyntaxError: invalid syntax in python

description: Eval SyntaxError: invalid syntax in python


rawDescription: Easiest way to get a specific section of a file path


rawDescription: unbound method when using type builtin to create a dynamic object

description: Unbound method when using type builtin to create a dynamic object


code:
f = Foo()
f.x = 5
f.set_readonly("y", 9)
f.x, f.y
f.x = 7
f.y = 1

rawDescription: Setting a property inside a Python method


code:
@conditional(cache_region('long_term'))
def get(self, arg):
    return arg + 1

rawDescription: Conditionally disable caching decorator based on instance variable


code:
for g in (' '.join(x) for x in ngrams(input, 2)):
   grams.setdefault(g, 0)
   grams[g] += 1

rawDescription: Computing N Grams using Python

description: Computing N Grams using Python


code:
import numpy as np
import os
fname = os.path.expanduser('~/test/data')
data = np.genfromtxt(
    fname,
    names = True, #  If `names` is True, the field names are read from the first valid line
    comments = '#', # Skip characters after #
    delimiter = '\t', # tab separated values
    dtype = None)  # guess the dtype of each column
print(data)
# [(1.2, 5.3, 2.8, 9.5) (3.1, 4.5, 1.1, 6.7) (1.2, 5.3, 2.8, 9.5)
#  (3.1, 4.5, 1.1, 6.7) (1.2, 5.3, 2.8, 9.5) (3.1, 4.5, 1.1, 6.7)]

print(data['1'])
# [ 1.2  3.1  1.2  3.1  1.2  3.1]

rawDescription: Numpy genfromtxt - column names

description: Numpy genfromtxt - column names


code:
def find_letter(item):
    word="".join([letter for letter in item if letter!='a'])
    lst=[letter for letter in item if letter=='a']
    return lst,word

rawDescription: Append/pop specific element of a string to the list when iterating over it


rawDescription: How to print graph call as tree?

description: Print graph call as tree


code:
import numpy as np

array = np.array(["cat", "in", "a", "hat"])
array[2] = "Seuss"
print(array)
# ['cat' 'in' 'Seu' 'hat']
print(array.dtype)
# dtype('|S3')
print(array.dtype.itemsize)
# 3

rawDescription: cython: memory view of ndarray of strings (or direct ndarray indexing)

description: Cython: memory view of ndarray of strings (or direct ndarray indexing)


code:
def __init__(self, key, default):

    self.key = key
    self.kind = type(default)
    self.default = default

def __get__(self, instance, owner):
    if self.key not in instance.__dict__:
        return self.default
    return instance.__dict__[self.key]

rawDescription: Using Python descriptors: How best to write a general validation getter-setter


rawDescription: Splitting a url into a list in python

description: Splitting a url into a list in python


code:
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

class PaginatedCourseSerializer():
    def __init__(self, courses, request, num):
        paginator = Paginator(courses, num)
        page = request.QUERY_PARAMS.get('page')
        try:
            courses = paginator.page(page)
        except PageNotAnInteger:
            courses = paginator.page(1)
        except EmptyPage:
            courses = paginator.page(paginator.num_pages)
        count = paginator.count

        previous = None if not courses.has_previous() else courses.previous_page_number()
        next = None if not courses.has_next() else courses.next_page_number()
        serializer = CourseSerializer(courses, many=True)
        self.data = {'count':count,'previous':previous,
                 'next':next,'courses':serializer.data}

rawDescription: Django Rest Framework 3.1 breaks pagination.PaginationSerializer


code:
def foo(*x):    # x will always will be tuple, whatever you pass
    """I will print or use x,y, and z differently"""
    for i in range(len(x)):
        print(x[i])           # instead of printing, you can assign values

rawDescription: How can i use multiple lists as arguments in a function and receive them differently?

description: Use multiple lists as arguments in a function and receive them differently


code:
from datetime import datetime
a=  datetime.now()
b = datetime.now() # after a few seconds
delta = b - a
delta.total_seconds()

rawDescription: python time difference in second

description: Python time difference in second


rawDescription: Python regex negating metacharacters

description: Python regex negating metacharacters


code:
arg_list = [{'key':self.key, 'foo':False}, {'key':self.key}, ... ]
handlers = [KeyReleaseEvent, KeyToggleEvent, ...]
for handler, args in zip(arg_list, handlers):
    g_events, r_events = handler(*args)
    self.GameEvents.extend(g_events)
    self.RealEvents.extend(r_events)
heapq.heapify(self.GameEvents)
heapq.heapify(self.RealEvents)

rawDescription: Gathering multiple multiple lists together


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

data = np.arange(100).reshape(10, 10)

cmap = plt.cm.gray
norm = plt.Normalize(data.min(), data.max())
rgba = cmap(norm(data))

# Set the diagonal to red
rgba[range(10), range(10), :3] = 1, 0, 0

fig, ax = plt.subplots()
ax.imshow(rgba, interpolation='nearest')

# Add the colorbar using a fake (not shown) image.
im = ax.imshow(data, visible=False, cmap=cmap)
fig.colorbar(im)

plt.show()

rawDescription: Changing colours of pixels of plt.imshow() image


code:
def rotT(T, gggg):
    return np.dot(gggg.transpose((1, 3, 5, 7, 0, 2, 4, 6)).reshape((81, 81)),
                  T.reshape(81, 1)).reshape((3, 3, 3, 3))

rawDescription: Fast tensor rotation with NumPy

description: Fast tensor rotation with NumPy


code:
def bell(x):
    if x == 0:
        return ()
    if x == 1:
        return ((set([1]),),)
    previous = bell(x - 1)
    new = []
    for sets in previous:
        r = []
        for mark in range(len(sets)):
            l = [s | set([x]) if i == mark else s for i, s in enumerate(sets)]
            r.append(tuple(l))
        new.extend(r)
        new.append(sets + (set([x]),))
    cache[x] = tuple(new)
    return new

rawDescription: Why is my code slower in pypy than the default python interpreter?


code:
# Do this when using Maya's cmds for your UI code
import maya.cmds as cmds

# ...

from contextlib import contextmanager
@contextmanager
def neat_indent():
    # OPTIONAL: This is also an opportunity to do something before the block of code runs!
    try:
        # During this is where your indented block will execute
        # Leave it empty
        yield
    finally:
        # OPTIONAL: This is where you can write code that executes AFTER your indented block executes.
        pass

rawDescription: Is there a way to indent Python without affecting the code


code:
from datetime import date, timedelta

today = date.today()
yesterday = today - timedelta(1)

# do your setup...

user_id = 'user email address'

# Dates have to formatted in YYYY/MM/DD format for gmail
query = "before: {0} after: {1}".format(today.strftime('%Y/%m/%d'),
                                        yesterday.strftime('%Y/%m/%d'))

response = service.users().messages().list(userId=user_id,
                                           q=query).execute()
# Process the response for messages...

rawDescription: New Python Gmail API - Only Retrieve Messages from Yesterday


code:
html = '''

        Taxonomy: Mollusca, Gastropoda, Littorinimorpha, Hydrobiidae, Hydrobia

        Identifiers: AF118324[sampleid]

        Depository: Mined from GenBank, NCBI

       '''
soup = BeautifulSoup(html, 'html.parser')
obj = soup.find('span', text='Identifiers:').nextSibling
print(obj)

rawDescription: Access value in BeautifulSoup4

description: Access value in BeautifulSoup4


code:
with open('Myfile.txt') as f:
    non_descriptions = filter(lambda line: not line.startswith(' '), f)
    values = (line.split(None, 2) for line in non_descriptions)

rawDescription: Skipping lines and splitting them into columns in python text parser


code:
abcdef

abcdef

abcdef

abcdef

abcdef

rawDescription: Unable to read huge (20GB) file from CPython


code:
to_match = ['http\S+',
            '@\S+',
            'something_else_you_might_want_to_remove']

re.sub('|'.join(to_match), '', sent)

rawDescription: replace more than one pattern python

description: Replace more than one pattern python


code: db.execute(i, all_data)

rawDescription: How to implement session.add on this code:

description: Implement session.add on this code:


code: minimize(f,array([1,2]),method='Newton-CG',jac = f_jac, hess= f_hes, options={'xtol': 1e-30, 'disp': True})

rawDescription: scipy.optimize.minimize : compute hessian and gradient together

description: Scipy.optimize.minimize : compute hessian and gradient together


rawDescription: Declaring multiple variables using the same function in Python


rawDescription: Algorithm in Python To Solve This Problem


code:
from ctypes import c_longlong

class ll(int):
    def __new__(cls, n):
        return int.__new__(cls, c_longlong(n).value)

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

    def __radd__(self, other):
        return ll(other.__add__(self))

    def __sub__(self, other):
        return ll(super().__sub__(other))

    def __rsub__(self, other):
        return ll(other.__sub__(self))

    ...

rawDescription: Python type long vs C 'long long'

description: Python type long vs C 'long long'


rawDescription: Re-shape pandas dataframe stack/unstack

description: Re-shape pandas dataframe stack/unstack


code:
Output
['text0 text1', ['item1', 'item2'], 'text2 sib']

rawDescription: Python, lxml - access text

description: Python, lxml - access text


code:
for y in final_rows:
    for x in y:
        if x == 'P':
            render_P()
        elif x == 'f':
            render_fly()
        #... etc.

rawDescription: character responding to key on keyboard, and being moved accross the map and other functions?

description: Character responding to key on keyboard, and being moved accross the map and other functions


code:
lock = Lock()

def f():
  with lock:
    _g()
    _h()

def g():
  with lock:
    _g()

def _g():
  _h()
  do_something1()

def h():
  with lock:
    _h()

def _h():
  do_something2()

rawDescription: What is the difference between Lock and RLock


code: data16 = (65535 * data).round().astype(uint16)

rawDescription: Binary storage of floating point values (between 0 and 1) using less than 4 bytes?


rawDescription: pytest parametrized fixture - parameters from json?

description: Pytest parametrized fixture - parameters from json


code:
d1 = { 'a':1, 'b':2, 'c': 3}
d2 = { 'b':2 ,'c':3, 'd': 1}
d3 = {}
def add_dict(target, d):
    for key in d:
        target.setdefault(key, []).append(d[key])

add_dict(d3, d1)
add_dict(d3, d2)

rawDescription: Merging of two dictionaries

description: Merging of two dictionaries


code:
def primeFinder(userInput):
    aVar = 2 # This is a possible factor
    divisorList = []  # This is a factor list of userInout, the inputted number
    while aVar <= userInput: # Checking until the variable cannot be a factor
            if userInput % aVar == 0: # If userInput divided by the variable has a remainder of zero, it means it is a factor
                    divisorList.append(aVar) # Adding the factor to th factor list
                    aVar+=1 # Making the possible factor numeral one bigger to test again
            else:
                    aVar +=1 # Making the possible factor numeral one bigger to test again

    #print divisorList
    if len(divisorList) > 1:  # If there are more than one factor...
            return False
    else:
            return True

rawDescription: how to use the break clause in this specific case

description: Use the break clause in this specific case


code:
# original points
pts = [(137.8, -10.6),
       (153.2, -10.6),
       (153.2, -28.2),
       (137.8, -28.2)]

# Interpret result from gdal.InvGeoTransform
# see http://www.gdal.org/classGDALDataset.html#af9593cc241e7d140f5f3c4798a43a668
xoff, a, b, yoff, d, e = inv_geomatrix

for x, y in pts:
    xp = a * x + b * y + xoff
    yp = d * x + e * y + yoff
    print((xp, yp))

rawDescription: affine_transform xy coords from gda94

description: Affine_transform xy coords from gda94


code: list(map(data.get, order))

rawDescription: sort dict by key list

description: Sort dict by key list


code:
def _getrow(self, idx):
    return self.m[idx]

def __getitem__(self, idx):
    if isinstance(idx, (numbers.Integral, slice)):
        return self._getrow(idx)
    rowidx, colidx = idx
    if isinstance(rowidx, numbers.Integral):
        return self._getrow(rowidx)[colidx]
    else:
        return [row[colidx] for row in self._getrow(rowidx)]

rawDescription: Implementing 2D slicing in Python

description: Implementing 2D slicing in Python


code:
model_dict = {
    'name': capfirst(model._meta.verbose_name_plural),
    'object_name': model._meta.object_name,
    'perms': perms,
}

rawDescription: Django dynamic name values in model overview on admin site


code:
def xyz_there(string):
    return string.count(".abc") != string.count("abc")

rawDescription: How to find a particular string within another string as quickly as possible?

description: Find a particular string within another string as quickly as possible


code:
def group(seq, sep):
    g = []
    for el in seq:
        if el == sep:
            yield g
            g = []
        g.append(el)
    yield g

ex = ['A', 'WORD', 'B' , 'C' , 'WORD' , 'D']
result = list(group(ex, 'WORD'))
print(result)

rawDescription: Python spliting a list based on a delimiter word


code: f = open("myfile.txt", "w") # Use "a" instead of "w" to append to file

rawDescription: Saving output of a for-loop to file

description: Saving output of a for-loop to file


code:
for file_ in allFiles:
    names = ['Date', 'Open', 'High', 'Low', 'Close', 'Vol', 'OI', 'Roll']
    df_temp = pd.read_csv(file_, index_col = None, names = names)
    df_temp['Roll'] = 0
    df_temp.iloc[-2,-1] = 1
    filename, file_extension = os.path.splitext(file_)
    df_temp['name'] = os.path.basename(filename)
    df = df.append(df_temp)

df = df.reset_index(drop=True)
df.set_index('name', inplace=True)
df.index.name = None
df = df[names]

df = df.drop_duplicates('Date') ## remove duplicate rows with same date

rawDescription: pandas dataframe, setting index_col to my csv name

description: Pandas dataframe, setting index_col to my csv name


code:
x = cos(theta)
y = sin(theta)

rawDescription: Defining velocity in a boid simulation

description: Defining velocity in a boid simulation


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

cmap = LinearSegmentedColormap.from_list('name', ['green', 'yellow', 'red'])

# Generate some data similar to yours
y, x = np.mgrid[-200:1900, -300:2000]
z = np.cos(np.hypot(x, y) / 100) + 1

fig, ax = plt.subplots()

cax = ax.contourf(x, y, z, cmap=cmap)
cbar = fig.colorbar(cax)
cbar.set_label('Z-Values')

plt.show()

rawDescription: Matplotlib Half color axis

description: Matplotlib Half color axis


rawDescription: Looking for a Python shorthand way of parsing a url encoded string into tuples


code:
sentence = re.sub(r'\bbeans\b', 'cars', sentence)
# 'robert likes to sell his cars'

rawDescription: How to replace all occurrences of specific words in Python

description: Replace all occurrences of specific words in Python


code:
for item in listWidget.selectedItems():
    item.setForeground(QBrush(Qt.green, Qt.SolidPattern))

rawDescription: Is it possible to highlight (not select) multiple rows in QListWidget?? (Python/PyQt)


code:
class TestConsumer(unittest.TestCase):

    def test_consume_food_consumes_the_apple(self):
        c = Consumer()
        c.consume_food()
        self.assertTrue(c.apple.consumed,
                        "Expected apple to be consumed")

    def test_consume_food_cuts_the_food(self):
        c = Consumer()
        c.consume_food()
        self.assertTrue(c.apple.been_cut,
                        "Expected apple to be cut")

    def test_pick_food_always_selects_the_apple(self):
        c = Consumer()
        food = c.pick_food()
        self.assertEquals(c.apple, food,
                          "Expected apple to have been picked")

if __name__ == '__main__':
    unittest.main()

rawDescription: Python unittesting for a class method

description: Python unittesting for a class method


rawDescription: Opening a file- How to make a .txt file return a list of lists


code:
for pos in range(sz - chunk, 0, -chunk):
    print('seek({}) and read({})'.format(pos, chunk))

if pos > 0:
    print('seek({}) and read({})'.format(0, pos))

rawDescription: Reading a binary file on backwards using python


code:
def initialize(self, data):
     self.data = data

rawDescription: How to share data between requests in Tornado Web

description: Share data between requests in Tornado Web


rawDescription: Get session info and place into a django form


code:
import sys
import ruamel.yaml as yaml

yaml_str = """\
a: 1   # comment 1
b: 2
c: 3
d: 4
e: 5
"""

data = yaml.round_trip_load(yaml_str)
data.yaml_add_eol_comment('comment 2', key='c')
data.yaml_add_eol_comment('#  comment 3', key='e', column=8)
yaml.round_trip_dump(data, sys.stdout)

rawDescription: Ruamel.yaml: How to access merge keys and comments in loaded OrderedDict


code: data = data.reshape( shape )  # where shape = (20,50)

rawDescription: represent an index inside a list as x,y in python

description: Represent an index inside a list as x,y in python


code: matline += yentry

rawDescription: Python: array values somehow getting changed


code: dCPI <- ts(CPI[-1] - CPI[-length(CPI)], start=2008, frequency=12)

rawDescription: Seasonal Adjustment in R or Python

description: Seasonal Adjustment in R or Python


code:
self.p_handler = urllib.request.ProxyHandler({'http' : self.proxy})
self.opener = urllib.request.build_opener(self.p_handler)
result = self.opener.open(url)
with open(filename, 'wb') as f:
    for chunk in iter(lambda: result.read(1024), ''):
        f.write(chunk)

rawDescription: Make local urllib settings local?

description: Make local urllib settings local


rawDescription: pandas: concatenate dataframes, forward-fill and multiindex on column data

description: Pandas: concatenate dataframes, forward-fill and multiindex on column data


code:
def onKeyDown(serialID):
    global node
    if serialid == '1':
        node.color = "FF8000"

rawDescription: libavg custom event handler

description: Libavg custom event handler


code:
def reverseDisplay(n):
    tmp = n % 10       # Determine the rightmost digit,
    print(tmp, end="") #  and print it with no space or newline.
    if n == tmp:       # If the current n and the rightmost digit are the same...
        print()        #    we can finally print the newline and stop recursing.
    else:              # Otherwise...
        reverseDisplay(n // 10)  # lop off the rightmost digit and recurse.

rawDescription: I am using a recursive function and need to print from within the function just once


code: del Singleton.instance

rawDescription: Singleton destructor for unit testing in Python


code:
loglh = ss.gamma.logpdf(data, fit_alpha, fit_loc, fit_beta).sum()
loglh

rawDescription: How to get log likelihood for exponential and gamma distributions

description: Get log likelihood for exponential and gamma distributions


code:
def main():
    UPDOWN = False # if true go up, else go down
    while True:
        #update the position
        if UPDOWN:
            baddieRect.move_ip(0, -5)
        elif not UPDOWN:
            baddieRect.move_ip(0, 5)

        # where your code is not quite right
        if baddieRect.bottom > WINDOWHEIGHT: #correct
            UPDOWN = True
        #yours baddieRect.bottom < WINDOWHEIGHT
        #mine elif baddieRect.top < 0
        elif baddieRect.top < 0: # tests if the 'baddie' hits the top
            UPDOWN = False

rawDescription: how to get a sprite to move top to bottom in a loop

description: Get a sprite to move top to bottom in a loop


code:
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy import UniqueConstraint, ForeignKey
from sqlalchemy.orm import relationship, scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.associationproxy import association_proxy

# Configure test data SA
engine = create_engine('sqlite:///:memory:', echo=True)
session = scoped_session(sessionmaker(bind=engine))
Base = declarative_base(engine)
Base.query = session.query_property()

def _tag_find_or_create(tag_name):
    tag = Tag.query.filter_by(tag_name=tag_name).first()
    return tag or Tag(tag_name=tag_name)

class Book(Base):
    __tablename__ = 'book'
    id = Column(Integer, primary_key=True)
    book_name = Column(String)

    # relationship
    _tags = relationship('Tag', secondary='book_tag')
    tags = association_proxy('_tags', 'tag_name', creator=_tag_find_or_create)

class BookTag(Base):
    __tablename__ = 'book_tag'
    __tableargs__ = (UniqueConstraint('book_id', 'tag_id', name='book_tag_uc'),)

    id = Column(Integer, primary_key=True)
    book_id = Column(Integer, ForeignKey('book.id'))
    tag_id = Column(Integer, ForeignKey('tag.id'))

class Tag(Base):
    __tablename__ = 'tag'
    id = Column(Integer, primary_key=True)
    tag_name = Column(String, unique=True)

# CREATE SCHEMA
Base.metadata.create_all()

def _insert_test_data():
    book = Book(book_name="book-1")
    book.tags.append("fiction")
    book.tags.append("history")
    session.add(book)
    session.commit()

    assert 1 == len(Book.query.all())
    assert 2 == len(Tag.query.all())

    book2 = Book(book_name="book-2")
    book2.tags.append("history")
    book2.tags.append("crime")
    session.add(book2)
    session.commit()

    assert 2 == len(Book.query.all())
    assert 3 == len(Tag.query.all())

def _add_new_book(book_name, tags):
    book = Book.query.filter(Book.book_name == book_name).first()
    assert not(book), "Book with name '{}' already found [{}]".format(
        book_name, book)

    book = Book(book_name=book_name)
    for tag in tags:
        book.tags.append(tag)
    session.add(book)
    session.commit()

if __name__ == '__main__':
    _insert_test_data()
    _add_new_book('SuperMan', ['fiction', 'romance'])

rawDescription: Correct pattern for inserting row in SQLAlchemy


code:
def find_base_nbytes(obj):
    if obj.base is not None:
        return find_base_nbytes(obj.base)
    return obj.nbytes

rawDescription: Size of numpy strided array/broadcast array in memory?


code:
@asyncio.coroutine
def get_input():
    loop = asyncio.get_event_loop()
    return (yield from loop.run_in_executor(None, stdin_q.get))  # None == use default executor.

rawDescription: Python queue linking object running asyncio coroutines with main thread input


code:
from flask import current_app, Blueprint, render_template

flat_pages = Blueprint('flat_pages', __name__, template_folder='templates')

@flat_pages.record
def record(state):
    db = state.app.config.get("flat_pages.db")

    if db is None:
        raise Exception("This blueprint expects you to provide "
                        "database access through flat_pages.db")

@flat_pages.route('/<page>')
def show(page):
    db = current_app.config["flat_pages.db"]
    page_object = db.find_page_by_name(page)
    return render_template('pages/{}.html'.format(page), page=page_object)

rawDescription: Using Flask-SQLAlchemy in Blueprint models without reference to the app


code:
if choice == "1":
    for song, name in songs.items():
        print(name, song)

rawDescription: Can't read file after split line?

description: Can't read file after split line


code:
service_args = [
    '--proxy=xxx.xxx.xx.xxx:xxxx',
    '--proxy-auth=username:password',
    '--proxy-type=http',
    ]

rawDescription: How to assign to workers a proxy that requires user name - password and a custom user agent?

description: Assign to workers a proxy that requires user name - password and a custom user agent


code: totalDollars, totalPennies = divmod(totalCents, 100)

rawDescription: Truncating ints without rounding?

description: Truncating ints without rounding


rawDescription: Python: iterating by match to regex

description: Python: iterating by match to regex


code: return x, y

rawDescription: trying to call a string that is assigned within a function

description: Trying to call a string that is assigned within a function


code:
extract_data("apto E1-E10 tower 1-2 sanit")
extract_data("apto IN2-IN1-IN4-E12-IN10 mamp")
extract_data("E-2-7-3-9-12; IN1-4-10 T 1-2 inst. hidr.")

rawDescription: Extracting data according to a list

description: Extracting data according to a list


code:
def isabcde(s):
    filtered = [i for i in s.lower() if i in 'abcdefghijklmnopqrstuvxyz']
    for i in range(len(filtered) - 1):
        if filtered[i] > filtered[i+1]:
            return print(s, "is not abcdearian")
    return print(s,  "is abcdearian")

while True:
    try:
        s = input("The string? ")
    except EOFError:
        break
    except TypeError:
        break
    isabcde(s)

rawDescription: Python: How to ignore non-letter characters and treat all alphabetic characters as lower case?


rawDescription: protecting user uploaded files django

description: Protecting user uploaded files django


code:
items = [x for x in _finalizer_registry.items() if f(x)]
items.sort(reverse=True)

for key, finalizer in items:
    sub_debug('calling %s', finalizer)
    try:
        finalizer()
    except Exception:
        import traceback
        traceback.print_exc()

rawDescription: Context managers and multiprocessing pools


code:
for i in reflist:
    os.system('open ' + '%s' % i)

rawDescription: Python: Adding Variable paths into os.system("open"+filename)


code:
from .index import index
from .other_view import other_view_method
...

rawDescription: Django sub-directory views and import all files from __init__.py


code:
def flattenlen(a):
    return sum(flattenlen(i) if isinstance(i, list) else 1 for i in a)

rawDescription: Retrieving the length of a list after flattening


code:
import tkinter as tk

# Change all label backgrounds
def change_colour():
    c = user.get() #Get the entered text of the Entry widget
    for wid in widget_list:
        wid.configure(bg = c)

# Create GUI
root = tk.Tk()

tk.Label(root, text='Enter a colour').pack()

user = tk.Entry(root)
user.pack()

label_frame = tk.Frame(root)
label_frame.pack()

btn = tk.Button(root, text='Change Colour', command = change_colour)
btn.pack()

widget_list = [user, btn] # Add defined widgets to list

#Dynamicly create labels for example
for x in range(10):
    lbl = tk.Label(label_frame, text='Label '+str(x))
    lbl.pack(side = tk.LEFT)
    widget_list.append(lbl) #Add widget object to list

root.mainloop()

rawDescription: How to change the colour of everything in a tkinter GUI at once

description: Change the colour of everything in a tkinter GUI at once


code: some_date = today + relativedelta(**{'years': 10})

rawDescription: Python - convert string to argument (or dynamically choose increment duration type for date)?


rawDescription: Need to match values from two different columns and then print out values from a corresponding column


code:
def func(s):
    for i in range(1, 100):
        t = i
        p = t * 2 + s * 2
        # Next iteration of the loop just overwrites p
    # Returns only the last p
    return p

rawDescription: How can I use a 'for' loop for just one variable in a function which depends on two variables?

description: Use a 'for' loop for just one variable in a function which depends on two variables


code:
words=[next((t for t in v if t[8] in final_count),None) for v in d.values()]
words

rawDescription: Compare Characters Within a String

description: Compare Characters Within a String


code:
from bs4 import BeautifulSoup

data = "your HTML here"
soup = BeautifulSoup(data)

span_texts = [span.text for span in soup.find_all('span')]
a_titles = [a['title'] for a in soup.find_all('a', title=True)]
b_texts = [b.text for b in soup.select('span[class] > b')]

result = span_texts + a_titles + b_texts

rawDescription: How to combine all 3 in 1 re.findall() ??(python 2.7 && Regular Expressions)

description: Combine all 3 in 1 re.findall() ??(python 2.7 && Regular Expressions)


rawDescription: Unexpected behaviour of np.sum which acts as np.ravel


code:
## DataFrame from 2D-arrays
x = X.reshape(1600)
y = Y.reshape(1600)
z = Z.reshape(1600)
df = pd.DataFrame({'x': x, 'y': y, 'z': z}, index=range(len(x)))

# Plot using `.trisurf()`:

ax.plot_trisurf(df.x, df.y, df.z, cmap=cm.jet, linewidth=0.2)
plt.show()

rawDescription: How to surface plot/3d plot from dataframe?

description: Surface plot/3d plot from dataframe


code: from class2_file import class2

rawDescription: Python Passing Class Object in to anther Class


code:
import random

my_list = [1, 2, 3, 4, 5]
n = len(my_list)
other_list = []

for _ in xrange(30):
  start = random.randint(1, n-2)
  a = my_list[start:]
  other_list.append(a)

rawDescription: renaming a variable in loop using Jython

description: Renaming a variable in loop using Jython


code:
from collections import defaultdict

def DFS(G,v,seen=None,path=None):
    if seen is None: seen = []
    if path is None: path = [v]

    seen.append(v)

    paths = []
    for t in G[v]:
        if t not in seen:
            t_path = path + [t]
            paths.append(tuple(t_path))
            paths.extend(DFS(G, t, seen, t_path))
    return paths

edges = [['1', '2'], ['2', '4'], ['1', '11'], ['4', '11']]

G = defaultdict(list)
for (s,t) in edges:
    G[s].append(t)
    G[t].append(s)

#print G.items()

all_paths = DFS(G, '1')
max_path  = max(all_paths, key=lambda l: len(l))
print("All Paths:")
print(all_paths)
print("Longest Path:")
print(max_path)
print("Longest Path Length:")
print(len(max_path))

rawDescription: finding longest path in a graph

description: Finding longest path in a graph


code:
jobnum = request.GET.get('jobnum')
job_list = Job.objects.filter(jobnum=jobnum)

rawDescription: Using jquery variable to get specific ajax request


code: d = dict((str(k), v) for k, v in self.arguments.values_list('key', 'value').iteritems())

rawDescription: Why is Django reverse() failing with unicode?


code:
user_input_list[0] # George
user_input_list[1] # 25

rawDescription: How to assign user input to a variable or list

description: Assign user input to a variable or list


code:
from matplotlib.mathtext import MathTextParser
from matplotlib.image import imsave
parser =  MathTextParser('bitmap')
data, someint = parser.parse("$\\alpha$", dpi=1000)
imsave("alpha.png",data.as_array(),cmap='gray')

rawDescription: How can I use matplotlib's mathtext rendering outside of matplotlib in another tk widget?

description: Use matplotlib's mathtext rendering outside of matplotlib in another tk widget


code:
bool(re.search(r'^[a-z]$', 'a',re.I))
bool(re.search(r'^[a-z]$', 'B',re.I))

rawDescription: Locating index of item via REGEX in Python


code:
from itertools import izip_longest

nums = [1646,
        2089,
         345]

revs = [str(n)[-1::-1] for n in nums]        # nums as reversed strings
izl  = izip_longest(*revs, fillvalue = '0')  # zip the digits together
xsum = lambda ds: str(sum(map(int, ds)))[-1] # digits -> last digit of their sum
rres = ''.join(xsum(ds) for ds in izl)       # result, but as reversed string
res  = int(rres[-1::-1])                     # result: 3960

rawDescription: Add numbers without carrying

description: Add numbers without carrying


code:
import pandas as pd
import numpy as np

my_df = pd.DataFrame(rows)

rawDescription: How to transfer SQL Group by results to a Pandas dataframe

description: Transfer SQL Group by results to a Pandas dataframe


code: df2['index'] = df2['index'] + pd.to_timedelta('1ms') * df2['cumcnt']

rawDescription: reshape dataframe from multiple columns to one

description: Reshape dataframe from multiple columns to one


code:
conf = {
    "port":     None,
    "host":     None,
    "query":    None,
    "no_serve": None,
    "no_load":  None,
    "debug":    None,
}
arg_dict = conf.copy()
args = lambda var: arg_dict[var]
args.func_dict = arg_dict
args('debug')
args.debug
args.debug = 'bar'
args('debug')
args.debug

rawDescription: Confusing code involving lambda function


code:
x = np.linspace(exp_constants[0], exp_constants[-1], 1000)
plt.plot(exp_constants, means, 'ko', x, popt[0]*np.exp(popt[1]*x), 'r')
plt.show()

rawDescription: Exponential Fit Between 2 Lists

description: Exponential Fit Between 2 Lists


code:
from pyspark.sql.functions import col, avg, when

df = sc.parallelize([
    (10, 0, 0), (20, 0, 0), (-1, 1, 0), (-1, 0, 1)
]).toDF(["age", "missing_age", "unknown_age"])

avg_age = df.where(
    (col("unknown_age") != 1) & (col("missing_age") != 1)
).agg(avg("age")).first()[0]

df.withColumn("age_imp", when(
    (col("unknown_age") == 1) | (col("missing_age") == 1), avg_age
).otherwise(col("age")))

rawDescription: Pyspark Dataframe Imputations -- Replace Unknown & Missing Values with Column Mean based on specified condition


rawDescription: Indexing and printing tuples

description: Indexing and printing tuples


rawDescription: python dictionary parsing using format and get new data

description: Python dictionary parsing using format and get new data


code:
mylist = ['index_1    200', 'index_2    500', 'index_3    50']
mydict = {k:int(v) for (k,v) in (line.split() for line in mylist)}
mydict

rawDescription: Convert only one item with dictionary comprehension


code:
from collections import OrderedDict
ret_dict = OrderedDict()
for element in data:
    # To remove 'id' from the dict 'element' use element.pop('id')
    # element.pop('id') return the value of id
    ret_dict.setdefault(element.pop('id'), []).append(element.values())

rawDescription: Python - Convert JSON object data into a List


code:
bnumer = enumerate(b)
for i, v in bnumer:
  try:
    a[i][1] = v
  except IndexError:
    break

# extend the list with the remaining default values from b
a.extend([None,v] for v in bnumer)

rawDescription: filling one dimension of two-dimensional array with other array

description: Filling one dimension of two-dimensional array with other array


code:
for name, num in group:
    counter += 1
    second[num] = counter

rawDescription: Dictionary value sorting

description: Dictionary value sorting


rawDescription: Python the simplest way to plot 3d surface


code: result[:] = 1

rawDescription: pandas - group and count nunique values

description: Pandas - group and count nunique values


code:
for item in generator_or_range_or_whatever:
    print(item)

rawDescription: python 3 print generator

description: Python 3 print generator


code: r'\b[submarine]+\b'

rawDescription: Efficient unordered substing matching

description: Efficient unordered substing matching


rawDescription: Python script calling PHP script while passing $_GET parameters


code:
def islice(iterable, *args):
    # islice('ABCDEFG', 2) --> A B
    # islice('ABCDEFG', 2, 4) --> C D
    # islice('ABCDEFG', 2, None) --> C D E F G
    # islice('ABCDEFG', 0, None, 2) --> A C E G
    s = slice(*args)
    it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
    nexti = next(it)
    for i, element in enumerate(iterable):
        if i == nexti:
            yield element
            nexti = next(it)

rawDescription: itertools.islice compared to list slice

description: Itertools.islice compared to list slice


code:
interval = 600
chunks = [text[idx:idx+interval] for idx in range(0, len(text), interval)]

rawDescription: How can I look inside of different chunks of strings in my Python program?

description: Look inside of different chunks of strings in my Python program


code:
from Tkinter import *

class Right(Frame):
    '''just a frame widget with a black background'''
    def __init__(self, parent):
        Frame.__init__(self, parent, width=200, height=200)
        self.config(bg='black')

if __name__ == "__main__":
    # if this script is run, just do this:
    root = Tk()
    Right(root).pack()
    root.mainloop()

rawDescription: How to Open Multiple Tkinter windows in one window


code:
['file1', 'dir1']
['file2', 'directory2']

rawDescription: Extract values from within strings in a list - python


code:
with open(Response, 'rU', encoding='utf-8') as data:
    separated = data.read().split('","')
    try:
        x = ElementTree.XML(separated[3])
        print(x)
        xml.etree.ElementTree.dump(x)
        y = ElementTree.XML(separated[4])
        xml.etree.ElementTree.dump(y)
    except Exception as e:
       print(e)

rawDescription: Understanding how to quote XML string in order to serialize using Python's ElementTree


code:
from funcbuilder import OperatorMachinery

class FuncOperations(metaclass=OperatorMachinery):
     def __init__(self, function):
          self.func = function
     def __call__(self, *args, **kwargs):
          return self.func(*args, **kwargs)

def func(self, *n, oper=None):
    if not n:
        return type(self)(lambda x: oper(self.func(x)))
    return type(self)(lambda x: oper(self.func(x), n[0](x)))

FuncOperations.apply_operators([func, func])

rawDescription: product of two functions

description: Product of two functions


code: self.files = self.options.get('--files', "").replace(',', '\n').split() or None

rawDescription: In Python, what is a minimal way of assigning a value to a variable depending on whether a dictionary contains a key?


code: preprocess(myDict)

rawDescription: fetching values from dictionary. Range match on keys

description: Fetching values from dictionary. Range match on keys


code:
import threading, collections

class QLock:
    def __init__(self):
        self.lock = threading.Lock()
        self.waiters = collections.deque()
        self.count = 0

    def acquire(self):
        self.lock.acquire()
        if self.count:
            new_lock = threading.Lock()
            new_lock.acquire()
            self.waiters.append(new_lock)
            self.lock.release()
            new_lock.acquire()
            self.lock.acquire()
        self.count += 1
        self.lock.release()

    def release(self):
        with self.lock:
            if not self.count:
                raise ValueError("lock not acquired")
            self.count -= 1
            if self.waiters:
                self.waiters.popleft().release()

    def locked(self):
        return self.count > 0

rawDescription: How Do I Queue My Python Locks?

description: How Do I Queue My Python Locks


code:
index = DatetimeIndex(s)
index
index.date

rawDescription: Get MM-DD-YYYY from pandas Timestamp

description: Get MM-DD-YYYY from pandas Timestamp


code:
df1 = DataFrame({'A' : np.arange(5), 'B' : np.random.randn(5)})
df2 = DataFrame({'A' : np.arange(5)+10, 'B' : np.random.randn(5)})
df1.to_hdf('test1.h5','df',mode='w',format='table',data_columns=['A'])
df2.to_hdf('test2.h5','df',mode='w',format='table',data_columns=['A'])

rawDescription: Maintain data columns when converting pandas hdfstore with odo


code:
func_to_run = globals()[ran_test_opt]
func_to_run()

rawDescription: Convert string into a function call

description: Convert string into a function call


code:
df.mean(axis=1)['Growth %']['One']
df.mean(axis=1)['Growth %']['Two']

rawDescription: How to access multiindex levels in pandas?

description: Access multiindex levels in pandas


code:
from math import pi, sqrt

class Integer(object):
    def __init__(self, name):
        self.name = name        # stores name of the managed object's attribute

    def __get__(self, instance, cls):
        if instance is None:
            return self
        else:
            return instance.__dict__[self.name]

    def __set__(self, instance, value):
        if not isinstance(value, int):
            raise TypeError('Expected an int')
        else:
            instance.__dict__[self.name] = value

class Computations(object):
    def __init__(self, name):
        self.name = name   # default value for area, circumference, distance to origin

    def __get__(self, instance, cls):
        if instance is None:
            print('this is the __get__ if statement running')
            return self
        else:
            print('this is the __get__ else statement running')
            return instance.__dict__[self.name]

    def __set__(self, instance, value):
        if hasattr(instance, self.name + 'is_set'):
            raise ValueError('Cannot set {} again.'.format(self.name[1:]))
        if isinstance(value, int):
            raise RuntimeError('Cant set formulas')
        else:
            instance.__dict__[self.name] = value
            setattr(instance, self.name + 'is_set', True)

class Circle(object):
    x = Integer('_x')   # Use _x and _y as the __dict__ key of a Point
    y = Integer('_y')   # These will be the storage names for a Point
    r = Integer('_r')

    area = Computations('_area')   # class variable of Computations
    circumference = Computations('_circumference')
    distance_to_origin = Computations('_distance_to_origin')

    def __init__(self, x, y, r):
        self.x = x      # invokes Integer.x.__set__
        self.y = y      # invokes Integer.y.__set__
        self.r = r      # for radius/invokes Integer.r.
        self.area = pi * self.r * self.r
        self.circumference = 2 * pi * self.r
        self.distance_to_origin = abs(sqrt(self.x * self.x + self.y * self.y) - self.r)

rawDescription: Using descriptor class to raise RuntimeError when user tries to change object's value


rawDescription: Converting date and time string to appropriate format for arithmetic calculations


code:
isinstance(b, A)
type(b) == A

rawDescription: Why use isinstance() instead of type()?

description: Why use isinstance() instead of type()


code:
from selenium import webdriver

driver = webdriver.Firefox()
driver.get('yoururl')
htmlpage = driver.page_source
outputfile = open('workfile','w')
outputfile.write(htmlpage)
outputfile.close()
driver.close()

rawDescription: Python2.7: get html of website, href becomes "javascript:void(0)"


code: alist.sort(key=lambda x: (int(x[1]), int(x[2])))

rawDescription: Python3 - Change the type of specific list elements


code:
p = re.compile("^TestVar\s+(\d{8})\s+(\S+)", re.MULTILINE)
m = p.findall(input)

rawDescription: get characters from string in python

description: Get characters from string in python


code:
class Singleton:
    def __init__(self, x):
        self.x = x

    def __getitem__(self, i):
        if not isinstance(i, int): raise TypeError(i)
        elif not (0 <= i < len(self)): raise IndexError(i)
        else: return self.x

    def __len__(self): return 1

rawDescription: Generating 3 billion-th element of a sequence in python


code:
class SetupPackage(object):
    optional = False

    def check(self):
        """
        Checks whether the dependencies are met. [...]
        """
        pass

    def get_packages(self):
        """
        Get a list of package names to add to the configuration.
        These are added to the `packages` list passed to
        `distutils.setup`.
        """
        return []

    def get_namespace_packages(self):
        """
        Get a list of namespace package names to add to the configuration.
        These are added to the `namespace_packages` list passed to
        `distutils.setup`.
        """
        return []

    def get_py_modules(self):
        """
        Get a list of top-level modules to add to the configuration.
        These are added to the `py_modules` list passed to
        `distutils.setup`.
        """
        return []

    ...

class Numpy(SetupPackage):
    ...

rawDescription: Allowing a python package requirement to fail in setup


code: hex_str = "".join([hex(i)[2:].zfill(2).upper() for i in xrange(256)])

rawDescription: Python - counting up in hex

description: Python - counting up in hex


code:
# get a function's limit numerically
def limit(f, eps=1.0e-11):
  previous_value = f(0)
  next_value = f(1)
  i = 2
  while abs(next_value - previous_value) > eps:
    previous_value = next_value
    next_value = f(i)
    i += 1
  return next_value

rawDescription: Recurrence sequence in Java / Python / Mathematica


rawDescription: Getting digits in an order (left to right) after OCR from x,y coordinates


code:
df = pd.DataFrame(pd.np.arange(25).reshape(5,5)).set_index(0)
df
df.loc[[10,15],[2,3,4]] = "x"
df

rawDescription: Modify certain cells depending on given conditions using pandas


code: lines = [map(float,line.strip().split(',')) for line in open(filename)]

rawDescription: what is a quick way to import a text file in python?

description: What is a quick way to import a text file in python


rawDescription: Buggy Heap Sort

description: Buggy Heap Sort


code: print(u'%s' % printObj)

rawDescription: What is the difference between these codes, and what does the repr do?


code:
for n in itertools.product(*([l] * (i+1))):
    ...

rawDescription: Passing arguments in function dynamically in Python 3


code:
categories = NewsCategory.objects.all()
user_preferences = [item.id for item in Profile.preference.all()]

rawDescription: A help in concept and a database query question (Django/Python)


code:
import imp
module = imp.load_source( 'mymodule', module_full_path )

rawDescription: python and dynamic imports of sub directories

description: Python and dynamic imports of sub directories


code:
from collections import deque

with open('somefile') as fin, open('outputfile', 'w') as fout:
    fout.writelines(deque(fin, 3))

rawDescription: Copy the last three lines of a text file in python?


code:
class EdgeTrigger(object):
    def __init__(self, callback):
        self.value = None
        self.callback = callback

    def __call__(self, value):
        if value != self.value:
            self.callback(self.value, value)
        self.value = value

rawDescription: Python One-Shot, level-trigger, edge-trigger


code: all_match = all(test(x) for x in stuff)

rawDescription: Python equivalent of LINQ All function?

description: Python equivalent of LINQ All function


code:
conditions = {
    "flag1": lambda: x < 10,
    "flag2": lambda: x < 3,
    "flag3": lambda: x < 5}

x = 0
while conditions["flag2"]():
    print(x)
    x += 1

rawDescription: Python: While Loops, Executing the same code under different conditions. Elegance and overhead


code:
with open('file.txt') as input_file:
    long_list = [line.strip() for line in input_file]

rawDescription: Python List Maker

description: Python List Maker


code:
from urllib import unquote
unquote("%DD%F2%EE%20%F2%E5%F1%F2")

rawDescription: How to decode string to use with Google Language Detection API?

description: Decode string to use with Google Language Detection API


rawDescription: adding values to default dict list of values

description: Adding values to default dict list of values


rawDescription: Hierarchical Tags in Google App Engine ndb


rawDescription: Separate layout and controller in kivy gui


code:
for line in testFile:
    for word in re.findall(r'\w+', line.lower()):
        if word in vocab_counter:
            vocab_counter[word] += 1

rawDescription: Trying to find word count in a text file using a different text file as "dictionary"


code:
import example
e = example.Human.Emotion
e
hasattr(e, 'joy')

rawDescription: expose public struct inside a class for boost::python

description: Expose public struct inside a class for boost::python


code:
results.append(newnumber)
results = [results[i] for i in range(0,len(results)-1) if results[i]%newnumber!=0]

rawDescription: deconstructing word solution

description: Deconstructing word solution


code:
full_pattern = re.compile('[^a-zA-Z0-9\\\/]|_')

def re_replace(string):
    return re.sub(full_pattern, '', string)

rawDescription: How to replace all characters except letters, numbers, forward and back slashes

description: Replace all characters except letters, numbers, forward and back slashes


code:
def subscribe_handleResponseEvent(dnp):
    def handleResponseEvent(request, response):
        #code to execute when event handler is called
        #code references additional method from dnp instance
        dnp.method3()
        ...

    dnp.method2.RequestEvent += handleResponseEvent

def main():
    C1 = DNPClass()
    C1.method1(arg1, arg2, arg3, arg4, arg5)

    # subscribing to event
    subscribe_handleResponseEvent(C1)
    ...

rawDescription: Function inside a function best approach?


code:
def combine (l1,l2, sort_l=None):
    if sort_l is None:
       sort_l = []
    if l1 == []:
        return l2
    elif l2 == []:
        return l1
    elif l1 == [] and l2 == []:
        return []
    index = 0
    for num in l1:
        if num <= l2[0]:
            sort_l.append(num)
            index += 1
        else:
            return combine(l2, l1[index:], sort_l) # pass it here
    return sort_l + l2

combine([1,3,5,7,9],[0,2,4,6,8]) # Don't pass any list, it will be created in first call.

rawDescription: combine two list and sort recursively

description: Combine two list and sort recursively


code: df.ix[:,:'Col4'] # to select Col1, Col2, Col3 and Col4

rawDescription: How to select n-1 column in a dataframe

description: Select n-1 column in a dataframe


code:
df
df.shift() != df

rawDescription: pandas DataFrame delete contiguous duplicates

description: Pandas DataFrame delete contiguous duplicates


code: [x for x in G.nodes_iter() if G.out_degree(x)==0 and G.in_degree(x)==1]

rawDescription: Find end nodes (leaf nodes) in radial (tree) networkx graph


code:
sortB = [(n, max(s)) for n,s in scores.items()]
sortB.sort(key=lambda x: x[1], reverse=True)
for name, highScore in sortB:
    print(name, highScore)

rawDescription: Outputting Highest/Average Score From List Of 3 (Value) For Each Student (Key) In A Dictionary Sorted From Highest To Lowest?


code:
pts = self.map.scatter(x, y, 90)
self.figure.canvas.mpl_connect('pick_event', DataCursor(plt.gca()))
pts.set_picker(5)

rawDescription: Pop up annotations on matplotlib within wxPython


code:
def copy(self, child_node):
  child_node.farmer = self.farmer

rawDescription: Python: Parent and Child responding to child-specific changes in boolean values. Why is this happening?


code:
def get_module_url(self, module_name='default'):
    host_name = modules.get_hostname(module=module_name)
    if os.environ.get('SERVER_SOFTWARE').startswith('Development'):
        return 'http://' + host_name
    app_name = app_identity.get_application_id()
    split_name = self.request.host.split(':')[0].split('.')
    if split_name[-2] == 'appspot':
        new_host_name = app_name if module_name == 'default' else module_name + '-dot-' + app_name
    else:
        # custom hostname-based domain mapping, default module goes to `www`.mydomain.com
        new_host_name = 'www' if module_name == 'default' else module_name
        if app_name.endswith('-staging'):
            #  copy of the GAE app for staging purposes on mydomain.com
            new_host_name += '-staging'
    return '.'.join(['https://' + new_host_name] + split_name[1:])

rawDescription: Resolve Discovery path on App Engine Module


code:
import example
ints = example.get_ints()
assert(isinstance(ints, tuple))
assert(ints == (21, 42))

rawDescription: How to return a std::vector<const T*> to python?

description: Return a std::vector<const T*> to python


code:
import pkgutil
stuff = [thing[1] for thing in pkgutil.iter_modules()]
stuff.sort() # To make it easy to look through
print(stuff)

rawDescription: Importing the entire Python standard library


rawDescription: Iterate through triple nested tuple Python 3.4


code:
fruits['durian'] = ['2.25', '2.33']
print( fruits )

rawDescription: How do I generate a list for each list item

description: Generate a list for each list item


rawDescription: Append index of items in one list to another in Python 2.7


code:
for i in range(0, len(File), 2):
    Username.append(File[i])

rawDescription: Gathering every other string from list / line from file


code:
distance = math.sqrt(diff[0]**2, diff[1]**2) # instead of `vector = ...`
diff_norm = (diff[0] / distance, diff[1] / distance) # instead of `distance = ...`

rawDescription: Python - PyGame - Learning vectors/animation


code: getattr(obj, prop)

rawDescription: Python achieve pointer like behaviour

description: Python achieve pointer like behaviour


code:
data_db = [
    {
        "id": 1,
        "data": { "status_code": 2, "desc": "Description sample1" }
    },
    {
        "id": 2,
        "data": { "status_code": 4, "desc": "Description sample2" }
    },
    {
        "id": 3,
        "data": { "status_code": 5, "desc": "Description sample3" }
    },
    {
        "id": 4,
        "data": { "status_code": 5, "desc": "Description sample4" }
    }
]

data_api = [
    { "status_code": 1, "desc": "Description sample5" },
    { "status_code": 4, "desc": "Description sample6" },
    { "status_code": 5, "desc": "Description sample3" }
]

#   checking the dicts in data_api against the 'data' sub-dicts in data_db
missing_from_db = [d for d in data_api if d not in [x['data'] for x in data_db]]

#   using similar comprehension to extract the 'id' vals of the 'data' in data_db which aren't in data_api
missing_from_api = [d['id'] for d in data_db if d['data'] not in data_api]

rawDescription: Comparing lists of dictionaries in Python


code:
list1=['1A','1B','1C','1D','1E']
list2=['_foo','_bar','_baz','_qux']
_foo=['30','40']
_bar=[]
_baz=['60','70']
_qux=[]
comb = {}

# NEW
for _i in list2:
    comb[_i] = globals()[_i]

for _i in list1:
    output=[]
    for _j in list2:
        output.extend([_i+'-'+ _k for _k in comb[_j]])
    print(','.join(output))

rawDescription: combine items in different list, python

description: Combine items in different list, python


code: #text.bind("<Key>", key)

rawDescription: tkinter shortcuts impossible to enable

description: Tkinter shortcuts impossible to enable


code:
yield from comb(S.replace('?','0',1))
yield from comb(S.replace('?','1',1))

rawDescription: Replace a character with multiple characters using Python


code:
for line in fileinput.input():
    do_something_with(line)

rawDescription: Running python from windows command prompt on many files


code: A

rawDescription: How to counter at even numbers only

description: Counter at even numbers only


rawDescription: How to get numpy sub-array view when array ndim is not known until runtime?

description: Get numpy sub-array view when array ndim is not known until runtime


code: resulting_list = [item_to_return for item in items if condition]

rawDescription: What's the most efficient way to access sibling dictionary value in a Python dict?


code:
li=[(i, c) for i, c in enumerate(original_string)]
li

rawDescription: Mapping modified string indices to original string indices in Python


rawDescription: Split string into all possible search strings


code: #!/usr/bin/env python

rawDescription: What's the best way to set up symbolic links to current installs, e.g python -> python2.6


code: unified = numpy.sort(unified, axis=0)

rawDescription: Numpy sorting by increasing datetime

description: Numpy sorting by increasing datetime


code:
d = {value: foo(value) for value in sequence if bar(value)}

def key_value_gen(k):
   yield chr(k+65)
   yield chr((k+13)%26+65)
d = dict(map(key_value_gen, range(26)))

rawDescription: Create a dictionary with list comprehension in Python


code:
from prettytable import PrettyTable

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])

...

data = x.get_string()

with open('test.txt', 'wb') as f:
    f.write(data)

rawDescription: How do I save table from prettytable >

description: Save table from prettytable >


code:
from flask import Flask, url_for
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware

app = Flask(__name__)
app.config['APPLICATION_ROOT'] = '/abc/123'

@app.route('/')
def index():
    return 'The URL for this page is {}'.format(url_for('index'))

def simple(env, resp):
    resp(b'200 OK', [(b'Content-Type', b'text/plain')])
    return [b'Hello WSGI World']

app.wsgi_app = DispatcherMiddleware(simple, {'/abc/123': app.wsgi_app})

if __name__ == '__main__':
    app.run('localhost', 5000)

rawDescription: Add a prefix to all Flask routes

description: Add a prefix to all Flask routes


rawDescription: how to stack numpy array in a list

description: Stack numpy array in a list


code:
"Burlington, VT"
"Saint Paul - Minneapolis, MN"

rawDescription: writing to CSV in python

description: Writing to CSV in python


code:
class Symbol(object):
    def __init__(self, name):
        self.name = name
    def __add__(self, other):
        return Add(self, other)
    def __repr__(self):
        return self.name

class Add(object):
    def __init__(self, left, right):
        self.left = left
        self.right = right
    def __repr__(self):
        return self.left + '+' + self.right

rawDescription: How does sympy work? How does it interact with the interactive Python shell, and how does the interactive Python shell work?


code:
if weight < 0.5:
    out.write('{} -> {} [ label="{}" color="red" ];\n'.format(start,end,weight))
else:
    out.write('{} -> {} [ label="{}" ];\n'.format(start,end,weight))

rawDescription: How can python write a dot file for GraphViz asking for some edges to be colored red?


code:
params = {'title': 'My entry 1', 'content': 'My content 1',
          'tags': 'zinnia, test', 'slug': 'my-entry-1',
          'status': PUBLISHED}
self.entry_1 = Entry.objects.create(**params)
self.entry_1.authors.add(self.authors[0])
self.entry_1.categories.add(*self.categories)
self.entry_1.sites.add(*self.sites)

rawDescription: Create a entry object in zinnia for the view function -basic python


rawDescription: How to read those tuple and convert int type during forloop?

description: Read those tuple and convert int type during forloop


code:
catalog = {}
for line in input_file:
    if line in catalog:
        catalog[line] += 1
    else:
        catalog[line] = 1

rawDescription: Using conditionals with variable strings in python


code:
import sys
sys.float_info.dig
s = '3.14159265358979'    # decimal string with 15 significant digits
format(float(s), '.15g')  # convert to float and back -> same value

rawDescription: how to keep the precision when convert string to double value

description: Keep the precision when convert string to double value


code:
car_dict = {'brand1': ['brand1_model1', 'brand1_model2'],
            'brand2': ['brand2_model1', 'brand2_model2'],
            'brand3': ['brand3_model1', 'brand3_model2']}

rawDescription: Based on user selection, display brand models python


code:
for i in reversed(range(len(yourList))):
    item = yourList[i]
    ...

rawDescription: Best method for changing a list while iterating over it


rawDescription: Best data structure to use in python to store a 3 dimensional cube of named data


code: (lambda x: x and x - 1)((str.find(substr) + 1) or None)

rawDescription: Expression evaluating to None when substr is not found


code:
from httplib2 import Http
from urllib import urlencode
h = Http()
data = dict(name="Joe", comment="A test comment")
resp, content = h.request("http://bitworking.org/news/223/Meet-Ares", "POST", urlencode(data))
resp

rawDescription: Simple URL GET/POST function in Python

description: Simple URL GET/POST function in Python


code:
a=np.arange(2*3*4).reshape(2,3,4)
b=np.arange(2*3).reshape(2,3)
np.einsum('ijx,ij->ix',a,b)
np.diagonal(np.dot(b,a)).T

rawDescription: Black voodoo of NumPy Einsum

description: Black voodoo of NumPy Einsum


code:
from os import system
st = input().strip()
if st.index('tts') == 0:
        say = st[st.index("'"):]
        say = say.replace("'","")
        cmd = 'CSCRIPT <enter path to script here, forward slashes> '+ say
        system(cmd)

rawDescription: is it possible to get python to write text in another program

description: Is it possible to get python to write text in another program


code:
from collections import defaultdict

id_value_dict = defaultdict()
for line in open(idfile.txt).readlines():
    id, value = line.strip().split()
    if id not in id_value_dict:
        id_value_dict[id] = int(value)
    else:
        if id_value_dict[id] < int(value):
            id_value_dict[id] = int(value)

rawDescription: From an (ID, number) pair keep only those pairs that contain the largest number


code: k = re.findall(r"/(\S+)", data)

rawDescription: regex find what's after slash without showing the slash

description: Regex find what's after slash without showing the slash


code:
def somefunc():
        print("This is indented using 4 spaces")
        print("This is indented using a tab")

rawDescription: how to make python ignore the -tt option

description: Make python ignore the -tt option


code:
from collections import defaultdict

class missingdict(defaultdict):
    def __missing__(self, key):
        return self.default_factory()

rawDescription: Python defaultdict that does not insert missing values


code:
import sys

with open(sys.argv[1].strip) as f:
    file_contents = f.readlines()
    # Do basic transformations on file contents here
    transformed_file_contents = format(file_contents)

# Do the rest of your actions outside the with block,
# this will allow the file to close and is the idiomatic
# way to do this in python

rawDescription: Multiple arguments with stdin in Python

description: Multiple arguments with stdin in Python


code:
x = pd.Series(np.random.randint(8,24,23892344)) # make some random data
when = pd.date_range(start=pd.datetime(2013,1,1),freq='S',periods=len(x))
when

rawDescription: How to add date and time information to time series data using python numpy or pandas

description: Add date and time information to time series data using python numpy or pandas


code:
from functools import partial
f = partial(f, "dummy1", "dummy2")

rawDescription: How to pass an integer series as argument to a python function?

description: Pass an integer series as argument to a python function


code:
class OrderedCallSequence(object):
    def __init__(self, test_case):
        self._expectation_count = 0
        self._evaluated = 0
        self._test_case = test_case

    def assertOrder(self):
        self._expectation_count += 1
        expected_position = self._expectation_count

        def side_effect(*args, **kwargs):
            self._evaluated += 1
            self._test_case.assertEquals(self._evaluated, expected_position,
                                         msg="Invoked in incorrect sequence")
        return side_effect

rawDescription: Testing call order across mock objects with Mox and Python


code:
def doit(instances, x):
    curr = x
    for inst in instances: curr=inst.calc(curr)
    return curr

rawDescription: Python dynamically generate dependencies between class instances


rawDescription: Python find continuous interesctions of intervals


code:
from example import Counter
counter = Counter(5)
assert(counter[:]    == [0,1,2,3,4])
assert(counter[:-2]  == [0,1,2])
assert(counter[-2:]  == [3,4])
assert(counter[::2]  == [0,2,4])
assert(counter[1::2] == [1,3])
assert(counter[100:] == [])

rawDescription: How to deal with Python slice objects in boost::python?

description: Deal with Python slice objects in boost::python


rawDescription: Python: downsample a population using frequency data


code: texts = [textOf(n) for n in soup.findAll('a', href=re.compile('^notizia.php\?idn=\d+'))]

rawDescription: BeautifulSoup - easy way to to obtain HTML-free contents


code:
def handler(event):
    if event.char in ('e','s','r'):
       return #Don't want to handle this keypress
    #code to clear-screen, etc.

your_frame.bind('<Key>',handler)

rawDescription: Waiting for keypress in Tkinter

description: Waiting for keypress in Tkinter


code:
# source should the code to execute
# filename should be a pseudo-filename that the code's from
# (it doesn't actually have to exist; it's used for error messages)
code_object = compile(source, filename, 'exec')

rawDescription: python importing code from a string

description: Python importing code from a string


code:
files = ['file9.txt', 'file10.txt', 'file11.txt', '32foo9.txt', '32foo10.txt']
sorted(files)
sorted(files, key=numericalSort)

rawDescription: Reading files in a particular order in python


code:
import pandas as pd
s = pd.read_csv('file.txt', sep=' ', header=None, index_col=0, squeeze=True)

rawDescription: Create iterable list from very large number of entries


code:
class MyClass(object):
    """
    Description for class

    :ivar var1: initial value: par1
    :ivar var2: initial value: par2
    """

    def __init__(self, par1, par2):
        self.var1 = par1
        self.var2 = par2

    def method(self):
        pass

rawDescription: how to show instance attributes in sphinx doc?

description: Show instance attributes in sphinx doc


code:
conditions = {'name_contains': 'franz',
              'birthdate_date': date(2005, 5, 2),
              'param3_contains': 'lorem'}

rawDescription: How to join multiple params dynamically for django Q object

description: Join multiple params dynamically for django Q object


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


code: S2 = A[ sorted(list(set(range(100)) - set(inx))) ]

rawDescription: numpy random.choice elements that are not selected

description: Numpy random.choice elements that are not selected


code:
full = ['Organization name} ', '> (777) 777-7777} ', ' class="lsn-mB6 adr">1 Address, MA 02114 } ', ' class="lsn-serpListRadius lsn-fr">.2 Miles} MORE INFO YOUR LISTING MAP if (typeof(serps) !== \'undefined\') serps.arrArticleIds.push(\'4603114\'); ', 'Other organization} ', '> (555) 555-5555} ', ' class="lsn-mB6 adr">301 Address, MA 02121 } ', ' class="lsn-serpListRadius lsn-fr">.2 Miles} MORE INFO CLAIM YOUR LISTING MAP if (typeof(serps) !== \'undefined\') serps.arrArticleIds.push(\'4715945\'); ', 'Organization} ']
regex = re.compile(r'\b[A-Z]{3,}\b')
# use only one of the following lines, whichever you prefer
filtered = filter(lambda i: not regex.search(i), full)
filtered = [i for i in full if not regex.search(i)]

rawDescription: In Python, how do I remove from a list any element containing certain kinds of characters?


code: sorted(key.lower() for key in c.__dict__.keys())

rawDescription: Python dict.keys to list results in duplicates


code:
import MySQLdb
conn = MySQLdb.connect(db='test')
cur = conn.cursor()
cur.execute('select * from foo; show tables;')
cur.fetchall()
cur.nextset()
cur.fetchall()

rawDescription: executing django query in same statement

description: Executing django query in same statement


code: data = ['this is the code', {'some':'other', 'stuff':'here'}]

rawDescription: How to make a specific key the first key in a dictionary?

description: Make a specific key the first key in a dictionary


code: Data = [re.sub('(ing|ed|al)$', '', w) for w in wordlist]

rawDescription: Conditional Removal of suffix from words in a python list


code: from tkinter.filedialog import askopenfilename

rawDescription: filedialog, tkinter and opening files

description: Filedialog, tkinter and opening files


rawDescription: Include user named variables in existing python script


code:
def word_to_int(word):
    return sum(ord(i) for i in word.strip())

rawDescription: how to perform XOR of all words in a file

description: Perform XOR of all words in a file


code:
from pyparsing import *

def give_desired_output(s):
    return "desired"

TAKE_THIS = Suppress("take_this") + Suppress(Word(printables))
AND_PROC = Suppress("and_process_it")
AND_GIVE = Keyword("and_give_me_the_output")
AND_GIVE.setParseAction(give_desired_output)

LANGUAGE_LINE = TAKE_THIS | AND_PROC | AND_GIVE

LANGUAGE = ZeroOrMore(LANGUAGE_LINE)

def parse_language(text):
    lst = LANGUAGE.parseString(text)
    assert len(lst) == 1  # trivial language returns a single value
    return lst[0]

if __name__ == "__main__":
    from_a_dsl_file = \
"""
   take_this 'abc'
   and_process_it
   and_give_me_the_output
"""

    print(parse_language(from_a_dsl_file))  # prints the word: desired

rawDescription: dsl in python example needed like in ruby

description: Dsl in python example needed like in ruby


code:
select_elements(range(10), 50)
select_elements(range(10), 33)
select_elements(range(10), 25)

rawDescription: How should a certain percentage of evenly-distributed elements of a Python list be extracted?


code: k = np.array(range(1, N+1))

rawDescription: Filling a numpy array using an arbitrary function


code:
def after_step(context, step):
    if step.status == "failed":
        take_the_shot(context.scenario.name + " " + step.name)

rawDescription: How to get the current behave step with Python?

description: Get the current behave step with Python


code:
def my_plural(str, end_ptr = None, rep_ptr = ""):
    if end_ptr and str.endswith(end_ptr):
        return str[:-1*len(end_ptr)]+rep_ptr
    else:
        return str+'s'

rawDescription: How to pluralize a name in a template with jinja2?

description: Pluralize a name in a template with jinja2


code:
class FakeMethod(object):
    def __init__(self, name, parent):
        self.name = name
        self.parent = parent

    def __call__(self, *args, **kwargs):
        self.parent.send_message(self.name, args, kwargs)

class MainClass(object):
    def build_API(self):
        methods = dict(meth1='arg1', meth2='arg2')
        for key in methods.iterkeys():
            setattr(self, key, FakeMethod(key, self))
    def send_message(self, called_as_name, *args, **kwargs):
        print("Sending message:", called_as_name, args, kwargs)

rawDescription: Find name of dynamic method in Python

description: Find name of dynamic method in Python


rawDescription: What is the best way to create a moving window in 2D array ond order pixels


code: fields = ('id','attribute')

rawDescription: Django-rest framework structure not capturing post or put request


code:
import numpy
import itertools
numpy.std([i for i in itertools.izip(*myList)[i] if i>=0])

rawDescription: finding standard deviation down a column of data in python

description: Finding standard deviation down a column of data in python


code:
result.shape
L1, L2 = result
np.allclose(L1, LIST1)
# etc

rawDescription: Split a large numpy array into separate arrays with a list of grouped indices


rawDescription: open file named with two digit year-Python

description: Open file named with two digit year-Python


code:
parseRange('123')
parseRange('123-')
parseRange('-456')
parseRange('123-456')

rawDescription: Python regular expressions: match a range of numbers with a separator


code:
from datetime import datetime
list_of_dicts = [
    {'country' : 'India', 'date' : '18-Mar-14'},
    {'country' : 'India', 'date' : '18-Apr-14'},
    {'country' : 'India', 'date' : '18-May-14'},
    {'country' : 'Australia', 'date' : '18-Mar-14'},
    {'country' : 'Australia', 'date' : '18-Apr-14'},
    {'country' : 'Australia', 'date' : '18-May-14'},
    {'country' : 'China', 'date' : '18-Mar-14'},
    {'country' : 'China', 'date' : '18-Apr-14'},
    {'country' : 'China', 'date' : '18-May-14'}
]
max_dates = {}
for entry in list_of_dicts:
    date = datetime.strptime(entry['date'], '%d-%b-%y')
    country = entry['country']
    if country not in max_dates or date > max_dates[country][0]:
        max_dates[country] = (date, entry)

[entry for date, entry in max_dates.values()]

rawDescription: Python: get maximum value object for unique key


code: multiples = list(range(first, low, -num))

rawDescription: Count even and odd numbers and the totals (python)


rawDescription: Placing a numpy record array inside another record array python


code:
{"outlook":"overcast", "temperature":"hot", "humidity":"high","windy":"FALSE","result":"yes"},
...

rawDescription: Formatting values using header indexing with csv


rawDescription: Find intervals given a list of tuples

description: Find intervals given a list of tuples


code:
import regex # $ pip install regex

with open(filename, encoding=character_encoding) as file:
    character_count = sum(len(regex.findall(r'\X', line)) for line in file)

rawDescription: Calculate bytes of the unicode character in python


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

fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111, projection='polar')

N = 8
theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)
radii = np.ones(N)
width = 2 * np.pi / N
bars = ax.bar(theta, radii, width=width, bottom=0.6)

colors = plt.cm.Spectral(np.linspace(0, 1, N))

for color, bar in zip(colors, bars):
    bar.set_facecolor(color)

xlabels = np.array([0,21,18,15,12,9,6,3])
ax.set_xticks(theta)
ax.set_xticklabels(xlabels, rotation=270, fontsize=60)

ax.set_yticklabels([])
ax.grid(False)

plt.show()

rawDescription: How to add space for xticklabels in python?

description: Add space for xticklabels in python


code:
# override.py
import sys
class LimitedWriter:

    def __init__(self, limit):
            self.limit = limit
            self.old_stdout = sys.stdout
            self.active = True
    def toggle(self, flag):
            self.active = flag

    def write(self, value):
            if len(value) > self.limit and self.active:
                    value = value[:self.limit] + "..."
            self.old_stdout.write(value)

__lw__ = LimitedWriter(15) # limit to 15 characters
sys.stdout = __lw__

rawDescription: Is there any way to hack IDLE (or Python itself) to cut off large prints when working with large text files?


rawDescription: Using Python to find the intersection of two equations


code: p1 = Process(target=_While.main)  # Note the lack of function call

rawDescription: Python Multithreading (while and apscheduler)


rawDescription: How to convert numpy datetime64 into datetime

description: Convert numpy datetime64 into datetime


code:
file = [file for file in zipfilelist.namelist() if file.split('/')[-1] == target]
if file:
    return file

rawDescription: Traversing ZIP Files

description: Traversing ZIP Files


code:
from requests.auth import AuthBase
import hmac
import hashlib
import time

class CryptsyAuth(AuthBase):
    """Authenticates a given HTTP request using the Cryptsy Auth scheme"""
    def __init__(self, api_key, api_secret):
        self.key = api_key
        self.secret = api_secret

    def __call__(self, r):
        r.body += '&nonce=%d' % int(time.time())
        h = hmac.new(self.secret, r.body, hashlib.sha512).hexdigest()

        r.headers['Key'] = self.key
        r.headers['Sign'] = h
        return r

rawDescription: Authenticating API calls using requests and requests-oauthlib in Python 3.3


code: x=  numberlist.listX[:]  #or list(numberlist.listX)

rawDescription: How to reinitialize list in loop iteration?

description: Reinitialize list in loop iteration


code: response.headers['Cache-Control'] = 'public, max-age=SECONDS'

rawDescription: Browser caching with BottlePy/GAE

description: Browser caching with BottlePy/GAE


code:
import random

def weighted_choice(items):
    """items is a list of tuples in the form (item, weight)"""
    weight_total = sum((item[1] for item in items))
    n = random.uniform(0, weight_total)
    for item, weight in items:
        if n < weight:
            return item
        n = n - weight
    return item

rawDescription: Probability distribution in Python

description: Probability distribution in Python


rawDescription: Calculate during merge using pandas

description: Calculate during merge using pandas


code:
from dis import dis

mat = []

def test_append():
    for i in range(10):
        #mat += [i]
        mat.append(i)

def test_iadd2(mat):
    for i in range(10):
        mat += [i]

print('test_append')
dis(test_append)

print('\ntest_iadd2')
dis(test_iadd2)

rawDescription: Why is list.append(x) more efficient than list += l[x]?


code:
tasks = [a.request for a in self.types["social"]]
#        ^^^^^^^^^
grabbers = executeChainResults(tasks, [(query, 0)] * len(tasks))
#                                     ^^^^^^^^^^^^^^^^^^^^^^^^^

rawDescription: Polymorphism with callables in Python

description: Polymorphism with callables in Python


code:
df['wt_quant'] = df.groupby(['item','price']).region.apply(f) * df.quantity
df

rawDescription: apply a function to a pandas Dataframe whose retuned value is based on other rows

description: Apply a function to a pandas Dataframe whose retuned value is based on other rows


rawDescription: Pandas: Change dataframe values based on dictionary and remove rows with no match


rawDescription: Table join using the Django ORM

description: Table join using the Django ORM


code:
adate = datetime.datetime.strptime(yourvalue, '%d/%m').date()
adate = adate.replace(year=datetime.date.today().year)

rawDescription: Convert strange date format to standard date format


code:
import string
x = 'hello, what is your name?'

x.strip(string.punctuation).split()[-1]

rawDescription: Extracting last character from a string in python?


code: df.groupby(['year','dico'],as_index=False).mean() #don't have 2013 in your df

rawDescription: basic panda questions related to slicing and aggregating tables

description: Basic panda questions related to slicing and aggregating tables


code:
N,K=10,15
data = np.arange(K)+10
data
np.array([data[np.arange(N)+i] for i in range(K-N+1)])

rawDescription: Creating an overlap array with conditions - Python


code: df['CourseNr'] = df.groupby('UserID').cumcount().apply(lambda x: 'Course%i' % (x+1))

rawDescription: Flatten and create new columns in Pandas


code:
import subprocess
clear_screen_seq = subprocess.check_output('clear')

rawDescription: Python - Clearing the terminal screen more elegantly


code:
text = """

    <title>This tag includes 'some_text'</title>

A h2 tag

"""
doc = lxml.etree.fromstring(text)
doc.xpath("//*[contains(text(),'some_text')]/following-sibling::*[1]")
# [<Element h2 at 102eeef70>]

rawDescription: How to get siblings when using contains(text(), ) in xpath

description: Get siblings when using contains(text(), ) in xpath


code:
import easygui
correct_answers = 0 # start with none correct
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    answer = easygui.enterbox("What is " + str(i) + ' times 8?')
    if int(answer) == i * 8:
        easygui.msgbox("That is correct!")
        correct_answers += 1 # increment
    else:
        easygui.msgbox("Wrong!")

rawDescription: Multiplication program

description: Multiplication program


code:
with open("file.dat", "r") as data:
    for line in data:
        runFunction(*line[:4])

rawDescription: Given a large dataset in file A, how can I reference it in a simulation in file B?


code:
import re

with open("f1.txt", "r") as infile1:
    udict = dict(line.strip().split("\t", 1) for line in infile1)

with open("f2.txt", "r") as infile2, open("out.txt", "w") as outfile:
    for line in infile2:
        for word in re.findall(r"\w+", line):
            if word in udict:
                line = line.replace(word, udict[word])
        outfile.write(line)

rawDescription: python beginner - faster way to find and replace in large file?

description: Python beginner - faster way to find and replace in large file


code:
common_users = common_users.sort_values('pair of websites')
common_users = common_users.drop_duplicates(subset=['used_at','sort'])
#print common_users

graph_by_common_users = common_users.pivot(index='pair of websites', columns='used_at', values='common users')
#print graph_by_common_users

#change order of columns
graph_by_common_users = graph_by_common_users[[2015,2014]]
graph_by_common_users = graph_by_common_users.sort_values(2014, ascending=False)

ax = graph_by_common_users.plot(kind='barh', width=0.5, figsize=(10,20))
[label.set_rotation(25) for label in ax.get_xticklabels()]

rects = ax.patches
labels = [int(round(graph_by_common_users.loc[i, y])) for y in graph_by_common_users.columns.tolist() for i in graph_by_common_users.index]
for rect, label in zip(rects, labels):
    height = rect.get_height()
    ax.text(rect.get_width() + 20, rect.get_y() - 0.25 + rect.get_height(), label, fontsize=8)

#sorting values of legend
handles, labels = ax.get_legend_handles_labels()
# sort both labels and handles by labels
labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))
ax.legend(handles, labels)

rawDescription: Sort strings in column and print graph

description: Sort strings in column and print graph


code: op = defer_huge_operation(w)

rawDescription: Python: How to condition the execution of a part of a function on the return values


code:
df = df.astype('float64')
tmp = pd.DataFrame([{"score1": df.score1.sum(), "score2":df.score2.sum(), "time1":df.time1.mean(), "time2":df.time2.median()}])
out = tmp.to_html(index=False)

rawDescription: Pandas: how to collapse a categorical column returning aggregate values


code: (list(tup) for tup in itertools.product(iterable1, iterable2, etc))

rawDescription: itertools.product - return list instead of tuple

description: Itertools.product - return list instead of tuple


code:
urlpatterns += patterns('django.views.generic.simple',
    (r'^$', 'direct_to_template', {'template': 'base.html'}),
)

rawDescription: Django template tag to display Django version


code:
from collective.documentviewer.interfaces import ILayer as IDocumentViewerLayer
class ICustomLayer(IDocumentViewerLayer):
    """
    custom layer class
    """

rawDescription: Plone - Override Zope Schema fields

description: Plone - Override Zope Schema fields


code: integer, value = divmod(12345, 100)

rawDescription: Divmod alternative method

description: Divmod alternative method


code: partial(re.compile(r'\s*#define ([A-Z_]+) (.*)').sub, r'def \1():\n    return \2'),

rawDescription: converting include file in C to python

description: Converting include file in C to python


code:
decimal_values = [float(val) for val in string_values[3:5]]
decimal_values

rawDescription: CSV string to decimal in python list

description: CSV string to decimal in python list


code:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(2015)

raw = (np.random.random(1000) - 0.5).cumsum()
smooth = raw.reshape(-1,10).mean(axis=1)

x1 = np.linspace(0, 1, 1000)
x2 = np.linspace(0, 1, 100)
plt.plot(x1, raw)
plt.plot(x2, smooth)
plt.show()

rawDescription: Plotting two different arrays of different lengths


rawDescription: Python - Iterate through, and extract, elements of a dictionary type list


rawDescription: How to get class name when there is attribute attached?

description: Get class name when there is attribute attached


code:
from itertools import chain
with open("in.txt") as f:
    lines = set(chain.from_iterable(x.split() for x in f))
    with open("in.txt","w") as f1:
        f1.writelines("\n".join(lines))

rawDescription: Merge Columns and Remove Duplication

description: Merge Columns and Remove Duplication


code:
sp_info = soup.select('.left-room-info')[i].text.strip().split('\r')
if len(sp_info) > 1:
    sp_info = [ info.strip() for info in sp_info ]
elif not sp_info[0]: # check for empty string
    sp_info = ["N/A"] # keep sp_info a list for consistancy

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


rawDescription: Regex for file encoded with CP1252

description: Regex for file encoded with CP1252


key: Negative

key: Neutral

key: Positive

rawDescription: Pandas - turning a DF column into an Index but without duplication


code: dict((k, v['id1']) for k,v in a.iteritems() if 'id1' in v )

rawDescription: Filter a dict of dict

description: Filter a dict of dict


code:
from Tkinter import *

def select_all():
    lb.select_set(0, END)

root = Tk()
lb = Listbox(root, selectmode=MULTIPLE)
for i in range(10): lb.insert(END, i)
lb.pack()
Button(root, text='select all', command=select_all).pack()
root.mainloop()

rawDescription: Select all in a tkinter Listbox

description: Select all in a tkinter Listbox


code:
example[0][-1]
example[1][-1]

rawDescription: Python taking a certain string from a list


code:
idx = df.duplicated(['longitude', 'latitude'])
idx *= -1
idx += 1
idx.ix[0] = 0
df = df.set_index(idx.cumsum(), append=True).swaplevel(0,1)

rawDescription: MultiIndexing in pandas based on column conditions


code:
obj = YourObj(a=4, b=5)
obj(a=current - 4 + current * current)

rawDescription: Is it possible to create a variable as a placeholder for 'current' value of a class in python?


code: coords = zip(rows, cols); coords

rawDescription: How can I find the indices in a numpy array that meet multiple conditions?

description: Find the indices in a numpy array that meet multiple conditions


rawDescription: Beautiful soup meta content tag

description: Beautiful soup meta content tag


rawDescription: coordinating comparisons with lists inside lists lists

description: Coordinating comparisons with lists inside lists lists


code: body1 = OneOrMore(~kw + (Word(alphas + nums) | PUNC))('Body')

rawDescription: getting a grammar to read more than one keyword in the text

description: Getting a grammar to read more than one keyword in the text


rawDescription: Search for loops of linked numbers

description: Search for loops of linked numbers


code: GqlQuery('SELECT * FROM A_db_model WHERE valueA IN :1', ['aaa', 'bbb'])

rawDescription: Google app engine or query (python)

description: Google app engine or query (python)


code:
import argparse

parser = argparse.ArgumentParser()
subs = parser.add_subparsers()

s_parser = subs.add_parser('sname')
s_parser.add_argument('file_directory1')
s_parser.add_argument('-o', dest='file_directory2')

rawDescription: argparse with different modes

description: Argparse with different modes


code:
lst = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
dct = {x:[] for x in lst}
for x,y in enumerate(lst, 1):
    dct[y].append(x)
dct

rawDescription: Find indices of elements in a list in Python


code:
('Launch Date:', u'1981-09-24')
(u'Launch\xa0Vehicle:', u'Delta')
(u'Launch\xa0Site:', u'Cape Canaveral, United States')
('Mass:', u'550.0\xa0kg')

rawDescription: How to parse a htmlpage with lxml with <br /> screwing up?

description: Parse a htmlpage with lxml with <br /> screwing up


code:
import math
some_list = [5.43, 12.01, 10.23, 3.33]
sorted(some_list, key=lambda f: math.modf(f))
sorted(some_list, key=lambda f: f % 1)

rawDescription: How can I sort a list by the decimals only?

description: Sort a list by the decimals only


code:
import calendar
import time
calendar.timegm(time.strptime('Jul 9, 2009 @ 20:02:58 UTC', '%b %d, %Y @ %H:%M:%S UTC'))

rawDescription: How to get the seconds since epoch from the time + date output of gmtime() in Python?

description: Get the seconds since epoch from the time + date output of gmtime() in Python


code:
import re

X1 = 206.9799
Y1 = 0.1218346

for i, line in enumerate(lines):
    r = re.match(r'^\s*vertex (\d+\.\d+e[-+]\d+) (\d+\.\d+e[-+]\d+) \d+\.\d+e[-+]\d+\s*$', line)
    if r and X1 == float(r.group(1)) and Y1 == float(r.group(2)):
        m.write("start" + "\n")

rawDescription: How to refer a certain place in a line in Python

description: Refer a certain place in a line in Python


code:
simplejson.dumps(get_values(Projects.objects.all(),
    go_into={'projectManager': {'go_into': 'teams'}}))

rawDescription: Django Serializer returns JSON for parent class objects only and leave child objects as same?


code:
import requests
result = requests.get('http://127.0.0.1:1234/1251.html')
result.encoding = 'windows-1251'
u'Привет' in result.text

rawDescription: Send request to page with windows-1251 encoding from python


code:
n, bins, patches = plt.hist([setA,setB,setC], bins=mybins,
                            label = ['setA','setB','setC'],
                            normed=True)

rawDescription: Normalising Histograms Matplotlib

description: Normalising Histograms Matplotlib


code: math.floor(gamma(101)) == gamma(101)

rawDescription: conversion float to long in python

description: Conversion float to long in python


code:
from tkinter import *

def hide_me(event, widget, pos):
    widget.grid_forget()

def show_me(event, widget, pos):
    widget.grid(row = pos)

root = Tk()
lbl = Label(root, text="Victim")
lbl.grid(row = 0)

btn = Button(root, text="Hide the victim")
btn.bind('<Button-1>', lambda event: hide_me(event, lbl, 0))
btn.grid(row = 1)

btn2 = Button(root, text="Show the victim")
btn2.bind('<Button-1>', lambda event: show_me(event, lbl, 0))
btn2.grid(row = 2)

root.mainloop()

rawDescription: Lift and raise a Canvas over a Canvas in tkinter


code:
diffs = [y-x for x,y in zip(d1, d1[1:])]
diffs
for diff in diffs:
    print(diff)

rawDescription: Difference between two time items

description: Difference between two time items


code:
#views.py
from django.utils.html import escape
valid_part = " hello1 " #needs escaping
invalid_part = " hello2 " #needs escaping
error = "{0} {1}".format(escape(valid_part),escape(invalid_part))
return render_to_response('my.html',{"error":error})

rawDescription: How to escape partially a template variable in Django

description: Escape partially a template variable in Django


code:
my_list = [1, 2, 3]
dict.fromkeys(my_list, 0)

rawDescription: Is there a better way to convert a list to a dictionary in Python with keys but no values?


code:
C = np.array(C)
df = pd.DataFrame(data=C.T, columns=pd.MultiIndex.from_tuples(zip(A,B)))
df

rawDescription: Constructing 3D Pandas DataFrame

description: Constructing 3D Pandas DataFrame


code:
class GCSServingHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self):
        blob_key = self.request.get('id')
        if (len(blob_key) > 0):
            self.send_blob(blob_key)
        else:
            self.response.write('no id given')

rawDescription: Get Public URL for File - Google Cloud Storage - App Engine (Python)