code:
Base() * 2
2 * Base()
Base() * 2.5
2.5 * Base()
'sdfsdfsdfds' * Base()
(lambda: 23) * Base()

rawDescription: How to determine which instance of an operator is being called?

description: Determine which instance of an operator is being called


code: l = PyRun_String("lambda *args: None", Py_eval_input, PyEval_GetGlobals(), NULL);

rawDescription: How to create lambda's from Python/C

description: Create lambda's from Python/C


code:
def clean(a, thresh=128, under=0, over=255):
    return np.where(a<128, under, over)

rawDescription: How do I avoid looping through an image pixel by pixel with opencv & numpy

description: Avoid looping through an image pixel by pixel with opencv & numpy


code:
string = ''
for t in range(1,8):
    if t % 2 == 0:                   # if t is even multiply t by 3 and add t to the string
        string += str(t * 3) + ' '
    else:                            # if t is odd simply add t to the string
        string += str(t) + ' '

print(string)

rawDescription: multiplying numbers in a string

description: Multiplying numbers in a string


code:
import numpy as np
import time

a=np.random.random_sample(int(1e9))

t1=time.time()
b=a[a>0.5]
print(time.time()-t1,'seconds')

rawDescription: Speed up NumPy's where function

description: Speed up NumPy's where function


code:
from collections import defaultdict
lookup = defaultdict(list)
for typeB in typeBlist:
    lookup[typeB.typeA].append(typeB)

rawDescription: if typeA in [typeB.typeA for typeB in typeBlist]: ... accessing typeB within the if clause?

description: If typeA in [typeB.typeA for typeB in typeBlist]: ... accessing typeB within the if clause


rawDescription: Conditional regular expression to split on commas


code: my_dict = CountedOrderedDict(key=lambda k: k[1])

rawDescription: Get key count from OrderedDict where key is a tuple


rawDescription: in python, how to match Strings based on Regular Expression and get the non-matching parts as a list?

description: In python, how to match Strings based on Regular Expression and get the non-matching parts as a list


code:
def sales(level, foo, bar):
    sale, x_cost, y_cost = levels_dict[level]
    x = x_cost + sale * foo
    y = y_cost + sale * bar
    ...

rawDescription: Python: how to avoid writing numerous if/elifs in a function?


code: sum(k*weights[j] for j,k in cfq)

rawDescription: Efficient way to decompress and multiply sparse arrays in python


code:
from kivy.base import runTouchApp
from kivy.lang import Builder

kv = '''
<ButImage@ButtonBehavior+AsyncImage>

FloatLayout:
    ButImage:
        id: but
        size_hint: .5, .5
        opacity: 1 if self.state == 'normal' else .5
        allow_stretch: True
        keep_ratio: False
        source: 'http://media1.policymic.com/site/article-items/2095/1_gif.gif'
        Label:
            center: but.center
            text: "Normal" if but.state == 'normal' else 'down'

'''

if __name__ == '__main__':
    runTouchApp(Builder.load_string(kv))

rawDescription: Changing background of a Button to a different shape and Styles like shadow effect etc in kivy python


code:
import operator
s.sort(key = operator.attrgetter('resultType'))

rawDescription: Python sorting - A list of objects

description: Python sorting - A list of objects


code: from csvkit.utilities.csvjson import CSVJSON

rawDescription: csvkit & django a.k.a. using csvkit as modules instead of from command line

description: Csvkit & django a.k.a. using csvkit as modules instead of from command line


rawDescription: How to add a matrix to itself in an iterative way?

description: Add a matrix to itself in an iterative way


code:
pattern = re.compile("(?![A-Z]{2}\d{2}\s+[A-Z]{3}$)")
foreign_numbers = [x for x in number_plates if pattern.match(x)]

rawDescription: How can I explain the function of filter and lambda in a line of code?

description: Explain the function of filter and lambda in a line of code


code:
def get_longest(seq):
    maxlen = -1
    ret = []
    for el in seq:
        if len(el) > maxlen:
            ret = [el]
            maxlen = len(el)
        elif len(el) == maxlen:
            ret.append(el)
    return ret

sequences = [['aaa'],['aaaa','bb'],[],['aaaaaa','bb','cccccc']]
example_output = list(map(get_longest, sequences))
print(example_output)

rawDescription: Extract longest strings from sublist within list . Python


code:
# two arrays with random start coordinates in area of dimensions
x0 = np.random.randint(dimensions[0], size=count)
y0 = np.random.randint(dimensions[1], size=count)

# random direction of each stick
dirrad = 2 * np.pi * np.random.rand(count)
# to destinguish between type1 and type2 sticks based on random values
stick_type = np.random.rand(count)
is_type1 = np.zeros_like(stick_type)
is_type1[stick_type < type1_content] = True

rawDescription: Time-efficient way for creation of many random stick coordinates with numpy


code:
import datetime
dt = datetime.datetime(2011, 12, 13, 10, 23)
import time
time.mktime(dt.timetuple())

rawDescription: python: convert year/month/day/hour/min/second to # seconds since Jan 1 1970

description: Python: convert year/month/day/hour/min/second to # seconds since Jan 1 1970


code:
import time
# print the resulting document to pdf
os.system('launch -p gowdercv.docx')
# wait for a maximum of 90 seconds
for x in xrange(0, 90):
    time.sleep(1)
    if os.path.exists('/path/to/expected/filename'):
        break

rawDescription: python: unable to find files in recently changed directory (OSx)

description: Python: unable to find files in recently changed directory (OSx)


code:
y = x.copy()
y[idx0s] = 0
idx0s += 1
idx_1s += 1
mask = np.zeros_like(y, dtype=np.bool)
mask[idx0s] = True
mask[idx_1s] = True
mask = np.logical_xor.accumulate(mask)
y[mask] = 1

rawDescription: Python/Numpy - Fill gaps between non-consecutive points?


code:
def download(url):
    with urllib.request.urlopen(url) as f:
        return f.read()

rawDescription: how to download multiple file simultaneously and join them in python?

description: Download multiple file simultaneously and join them in python


code:
result = []
for cpm, cpmile in zip(cost_per_minute, cost_per_mile):
    value = round(ride_time * cpm + ride_distance * cpmile, 1)
    result.append(value)
return result

rawDescription: How to get the result in single List?

description: Get the result in single List


code:
from numpy import array
array_data = array([1, -1, 1, -1, 1, -1, 1, -1, 1, -1])
coeff = Stream(array_data) # Cast from an array
(1 - coeff * z ** -2)([0, 1, 0, 0, 0, 0, 0]).take(inf)

rawDescription: Applying time-variant filter in Python

description: Applying time-variant filter in Python


rawDescription: How to auto-scroll a gtk.scrolledwindow?

description: Auto-scroll a gtk.scrolledwindow


rawDescription: Python Button Bind two functions and send arguments with the binding


rawDescription: dealing with multiple lists

description: Dealing with multiple lists


code:
use_date = use_date + datetime.timedelta(minutes=+10)
use_date = use_date + datetime.timedelta(hours=+1)
use_date = use_date + datetime.timedelta(days=+1)
use_date = use_date + datetime.timedelta(weeks=+1)

rawDescription: Is there a simple way to increment a datetime object one month in Python?


code:
import sys
import re

def process_char(c, stream, is_first=False):
    if c == '':
        return False
    if c == '[':
        stream.write('{' if is_first else ',{')
        return True
    if c == ']':
        stream.write('}')
        return True

def process_file(fname):
    with open(fname, "r") as mesh:
        c = mesh.read(1)
        if c == '':
            return
        sys.stdout.write('{')

        while True:
            c = mesh.read(8192)
            if c == '':
                return

            c = re.sub(r'\[', ',{', c)
            c = re.sub(r'\]', '}', c)
            sys.stdout.write(c)

if __name__ == '__main__':
    process_file(sys.argv[1])

rawDescription: Python - Opening and changing large text files


code:
#define AF_INET         2       /* Internet IP Protocol         */
#define AF_INET6        10      /* IP version 6                 */
#define AF_PACKET       17      /* Packet family                */

rawDescription: get MAC address for mobile broadband modem in python

description: Get MAC address for mobile broadband modem in python


rawDescription: Retrieve the ranking of elements in various list to compute the weighted average of their ranking scores Python


code:
phonebook = {}
phonebook ['ana'] = ['12345']
phonebook ['maria'] = ['23456' , 'maria@gmail.com']

rawDescription: How to add a another value to a key in python

description: Add a another value to a key in python


code:
no_data = [int(num) for num in new_data]
# or
no_data = map(int, new_data)

rawDescription: How to extract numerical data from a text file

description: Extract numerical data from a text file


code:
grouped = df.reset_index().groupby('B').first()
grouped

rawDescription: Pandas multiindex dataframe set first row in a column to 0


code:
T(lambda : 'one' in d.itervalues()).repeat()
T(lambda : 'one' in d.values()).repeat()
T(lambda : 'one' in d.viewvalues()).repeat()

rawDescription: How to check if a value exists in a dictionary (python)

description: Check if a value exists in a dictionary (python)


rawDescription: Find some value in column

description: Find some value in column


code:
{u'Category': u'Human',
 u'Location': {u'city': u'london'},
 u'Physical': {u'complexion': u'fair', u'skin_type': u'smooth'}}

rawDescription: Writing complex custom metadata on images through python


code:
...
result = gevent.joinall(threads)
for x in (t.value for t in threads):
    if x.u:
        return x

rawDescription: Comparing results of Gevent threads

description: Comparing results of Gevent threads


code:
toolbar_frame = tk.Frame(root)
statusbar_frame = tk.Frame(root)
content_frame = tk.Frame(root)

toolbar_frame.pack(side="top", fill="x")
statusbar_frame.pack(side="bottom", fill="x")
content_frame.pack(side="top", fill="both", expand=True)

rawDescription: Is there any better method to manage place in Tkinter in Python?


code:
def random_fruit(fruits=None):
    if fruits is None:
        fruits = ['apple','banana','coconut']
    return "I like " + random.choice(fruits)

rawDescription: How do I patch or modify a list inside of a function when running a unit test?

description: Patch or modify a list inside of a function when running a unit test


code: self.data_source.ix[:, :cur_n, :]

rawDescription: Pandas Panel Slicing - Improving Performance


code:
old_env = repo.git.update_environment(GIT_SSH=ssh_executable)
# If needed, restore the old environment later
repo.git.update_environment(**old_env)

rawDescription: GitPython and SSH Keys?

description: GitPython and SSH Keys


code:
def generateNumber(num):
    mylist = []
    for i in range(num+1):
         mylist.append(i)
    return mylist

x = generateNumber(10)

rawDescription: Python Sequence of Numbers

description: Python Sequence of Numbers


code: first_name, last_name = barInitial()

rawDescription: Python Function Return

description: Python Function Return


rawDescription: Refactor Python Code

description: Refactor Python Code


code:
Iniesta is out
['Messi', 'Neymar', 'Xavi']
Xavi is out
['Messi', 'Neymar', 'Iniesta']
Neymar is out
['Messi', 'Xavi', 'Iniesta']
Messi is out
['Neymar', 'Xavi', 'Iniesta']

rawDescription: Removing current element from a list

description: Removing current element from a list


code: out_arr_clip = Image.fromarray(arr.clip(0,255).astype('uint8'), 'RGB')

rawDescription: Image from array and image using point

description: Image from array and image using point


rawDescription: Python equivalent for Perl's pack(H*, $string)


rawDescription: Built-in method to Generate Random Strings of Fixed Length From Given Characters


rawDescription: Pandas: How to iterate over level one and randomly select from level 2 then add subselection to dataframe


code:
import pandas as pd
import io

temp1=u"""Sample;Chr;Start;End;Value
S1;1;100;200;1
S1;2;200;250;1
S2;1;50;75;5
S2;2;150;225;4"""
#after testing replace io.StringIO(temp1) to filename
dfline = pd.read_csv(io.StringIO(temp1), sep=";")

temp2=u"""Name;Chr;Position
P1;1;105
P2;1;60
P3;1;500
P4;2;25
P5;2;220
P6;2;240"""
#after testing replace io.StringIO(temp2) to filename
mapfile = pd.read_csv(io.StringIO(temp2), sep=";")

rawDescription: Python Pandas - Compare 2 dataframes, multiple parameters


rawDescription: How to transform a arithmetic expression to a Python arithmetic function?

description: Transform a arithmetic expression to a Python arithmetic function


code: Arguments = string.Format("{0} {1}", cmdToBeExecute, "\"Rahul done good\""),

rawDescription: How to pass string as command line argument in python using C#

description: Pass string as command line argument in python using C#


code:
if self.changed_single_score_locked:
    return
else:
    self.changed_single_score_locked = True

rawDescription: How to retain the selection when updating a PyGTK combobox?

description: Retain the selection when updating a PyGTK combobox


code:
import numpy as np
df['ids'] = df['ids'].apply(lambda x: np.unique(x))

rawDescription: How to merge two list columns when merging DataFrames?

description: Merge two list columns when merging DataFrames


code:
from myscript import *
myvar

rawDescription: examine the variables when running python script in python environment?

description: Examine the variables when running python script in python environment


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

# initialize the three axis:
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax3 = ax1.twinx()

# data ratio for the two left y-axis:
y3_to_y1 = 1/7.5

# y-axis limits:
YLIM = [0.0, 150.0,
        0.0, 150.0]

# set up dummy data
x = np.linspace(0,70.0,70.0)
y1 = np.asarray([xi**2.0*0.032653 for xi in x])
y2 = np.asarray([xi**2.0*0.02857 for xi in x])

# plot the data
ax1.plot(x,y1,'b')
ax2.plot(x,y2,'r')

# define the axis limits
ax1.set_xlim(0.0,70.0)
ax1.set_ylim(YLIM[0],YLIM[1])
ax2.set_ylim(YLIM[2],YLIM[3])

# when specifying the limits for the left-most y-axis
# you utilize the conversion factor:
ax3.set_ylim(YLIM[2]*y3_to_y1,YLIM[3]*y3_to_y1)

# move the 3rd y-axis to the left (0.0):
ax3.spines['right'].set_position(('axes', 0.0))

# set y-ticks, use np.arange for defined deltas
# add a small increment to the last ylim value
# to ensure that the last value will be a tick
ax1.set_yticks(np.arange(YLIM[0],YLIM[1]+0.001,10.0))
ax2.set_yticks(np.arange(YLIM[2],YLIM[3]+0.001,10.0))
ax3.set_yticks(np.arange(YLIM[2]*y3_to_y1,YLIM[3]*y3_to_y1+0.001, 2.0))

# for both letf-hand y-axis move the ticks to the outside:
ax1.get_yaxis().set_tick_params(direction='out')
ax3.get_yaxis().set_tick_params(direction='out')

plt.show()

rawDescription: Multiple y-axis conversion scales

description: Multiple y-axis conversion scales


code:
FuntionStr='AccName,S,Balance,N,AccrInterest,N'
it = iter(FuntionStr.split(","))

print(list(zip(it,it)))
[('AccName', 'S'), ('Balance', 'N'), ('AccrInterest', 'N')]

rawDescription: Python string to two dimensionals list

description: Python string to two dimensionals list


code:
class StrategyExample:
    def __init__(self, func=None):
        self.name = "Strategy Example 0"
        if func:
             self.execute = func

    def execute(self):
        print(self.name)

def executeReplacement1():
    print(self.name + " from execute 1")

def executeReplacement2():
    print(self.name + " from execute 2")

if __name__ == "__main__":
    strat0 = StrategyExample()
    strat1 = StrategyExample(executeReplacement1)
    strat1.name = "Strategy Example 1"
    strat2 = StrategyExample(executeReplacement2)
    strat2.name = "Strategy Example 2"

    strat0.execute()
    strat1.execute()
    strat2.execute()

rawDescription: How to write Strategy Pattern in Python differently than example in Wikipedia?

description: Write Strategy Pattern in Python differently than example in Wikipedia


rawDescription: A double preceding function with bug

description: A double preceding function with bug


code:
import ast

with open('mymodule.py') as f:
    mycode = f.read()

myast = ast.parse(mycode)
for thing in myast.body:
    if isinstance(thing, ast.ClassDef):
        print('class {}({})'.format(thing.name,
                                    ', '.join(base.id for base in thing.bases)))
        for subthing in thing.body:
            if isinstance(subthing, ast.FunctionDef):
                print('    def {}'.format(name))

rawDescription: How to make wxPython class browser

description: Make wxPython class browser


code:
def parse(filepath):
    with open(filepath) as f:
        contents = f.readlines()

    output = {}
    group = {}
    inside_group = False

    for line in contents:
        line = line.strip()
        if line == '':
            continue

        type, value = line.split('=')
        type = type.strip()
        value = value.strip()

        if type == 'OBJECT':
            inside_group = True
        elif type == 'END_OBJECT':
            output[value] = group
            inside_group = False
            group = {}
        elif inside_group:
            group[type] = value

    return output

rawDescription: extract specific text from several metadata files using python

description: Extract specific text from several metadata files using python


rawDescription: Get info from a table on a website where XPATH varies on each site, Python


code:
import string, random

f = open('test.txt', 'w')

for i in range(10):
    rand_list = list(string.ascii_letters)
    random.shuffle(rand_list)
    rand_str = "".join(rand_list[:9])
    f.write(".%d%s" % (len(rand_str), rand_str))

rawDescription: How can I treat a section of a file as though it's a file itself?

description: Treat a section of a file as though it's a file itself


code:
for id in uniquevalues:
    newdf = df[df['id'] == id]
    newdf.to_csv("dataframe "+id+".csv", sep='\t')

rawDescription: pandas, how to filter dataframe by column value

description: Pandas, how to filter dataframe by column value


code: {{ url_for('post_blueprint.get_post', **post) }}

rawDescription: Creating link to an url of Flask app in jinja2 template


code:
import os
def get_pname(id):
    return os.system("ps -o cmd= {}".format(id))
print(get_pname(1))

rawDescription: How to get the process name by pid in Linux using Python?

description: Get the process name by pid in Linux using Python


code:
class Paintable(object):
    def __init__(self, color):
        self.color = color

    def paint(self):
        print('So you want to paint your {}?'.format(type(self).__name__)) # this will replace 'car' in your original print with whatever the class name  of the Paintable is
        self.color = input('What color will it be?')

# Now we make car inherit Paintable
class Car(Paintable):
    def __init__(self, tires, color, age):
        super(Car, self).__init__(color) # this sets the color via Paintable's constructor
        self.tires = tires
        self.age = age

 # And from here the rest is the same

rawDescription: Do something for every instance of a class


code:
result = cycle_00z
result = cycle_02z.combine_first(result)
result = cycle_04z.combine_first(result)
result

rawDescription: How to use Pandas to keep most recent data from Series with overlapping times

description: Use Pandas to keep most recent data from Series with overlapping times


code:
import copy

template_dict = {day1: 0, day2: 0, day3: 0}
Dictionary['New York'] = copy.deepcopy(template_dict)

rawDescription: Dictionaries: added value to one key also gets added to other keys


code:
def re_range(lst):
    n = len(lst)
    result = []
    scan = 0
    while n - scan > 2:
        step = lst[scan + 1] - lst[scan]
        if lst[scan + 2] - lst[scan + 1] != step:
            result.append(str(lst[scan]))
            scan += 1
            continue

        for j in range(scan+2, n-1):
            if lst[j+1] - lst[j] != step:
                result.append(formatter(lst[scan], lst[j], step))
                scan = j+1
                break
        else:
            result.append(formatter(lst[scan], lst[-1], step))
            return ','.join(result)

    if n - scan == 1:
        result.append(str(lst[scan]))
    elif n - scan == 2:
        result.append(','.join(map(str, lst[scan:])))

    return ','.join(result)

rawDescription: Convert List of Numbers to String Ranges


rawDescription: using dictionaries and linked list python

description: Using dictionaries and linked list python


code:
key=lambda word: [alphabet.index(c) for c in word[0]]
key('af')
key('ax')

rawDescription: Sorting string values according to a custom alphabet in Python


code:
from ctypes import *
from ctypes.wintypes import *
from collections import namedtuple

__all__ = ['query_working_set', 'working_set_size']

kernel32 = WinDLL('kernel32', use_last_error=True)
psapi = WinDLL('psapi', use_last_error=True)

PROCESS_VM_READ           = 0x0010
PROCESS_QUERY_INFORMATION = 0x0400

ERROR_ACCESS_DENIED = 0x0005
ERROR_BAD_LENGTH    = 0x0018

ULONG_PTR = WPARAM
SIZE_T = c_size_t

class PSAPI_WORKING_SET_BLOCK(Union):
    class _FLAGS(Structure):
        _fields_ = (('Protection',  ULONG_PTR,  5),
                    ('ShareCount',  ULONG_PTR,  3),
                    ('Shared',      ULONG_PTR,  1),
                    ('Reserved',    ULONG_PTR,  3),
                    ('VirtualPage', ULONG_PTR, 20))
    _anonymous_ = '_flags',
    _fields_ = (('Flags', ULONG_PTR),
                ('_flags', _FLAGS))

class PSAPI_WORKING_SET_INFORMATION(Structure):
    _fields_ = (('NumberOfEntries',  ULONG_PTR),
                ('_WorkingSetInfo', PSAPI_WORKING_SET_BLOCK * 1))
    @property
    def WorkingSetInfo(self):
        array_t = PSAPI_WORKING_SET_BLOCK * self.NumberOfEntries
        offset = PSAPI_WORKING_SET_INFORMATION._WorkingSetInfo.offset
        return array_t.from_buffer(self, offset)

PPSAPI_WORKING_SET_INFORMATION = POINTER(PSAPI_WORKING_SET_INFORMATION)

def errcheck_bool(result, func, args):
    if not result:
        raise WinError(get_last_error())
    return args

psapi.QueryWorkingSet.errcheck = errcheck_bool
psapi.QueryWorkingSet.argtypes = (
    HANDLE,                         # _In_  hProcess
    PPSAPI_WORKING_SET_INFORMATION, # _Out_ pv
    DWORD)                          # _In_  cb

kernel32.GetCurrentProcess.restype = HANDLE

kernel32.OpenProcess.errcheck = errcheck_bool
kernel32.OpenProcess.restype = HANDLE
kernel32.OpenProcess.argtypes = (
    DWORD, # _In_ dwDesiredAccess
    BOOL,  # _In_ bInheritHandle
    DWORD) # _In_ dwProcessId

def query_working_set(pid=None):
    """Return the PSAPI_WORKING_SET_BLOCK array for the target process."""
    if pid is None:
        hprocess = kernel32.GetCurrentProcess()
    else:
        access = PROCESS_VM_READ | PROCESS_QUERY_INFORMATION
        hprocess = kernel32.OpenProcess(access, False, pid)
    info = PSAPI_WORKING_SET_INFORMATION()
    base_size = sizeof(info)
    item_size = sizeof(PSAPI_WORKING_SET_BLOCK)
    overshoot = 0
    while True:
        overshoot += 4096
        n = info.NumberOfEntries + overshoot
        resize(info, base_size + n * item_size)
        try:
            psapi.QueryWorkingSet(hprocess, byref(info), sizeof(info))
            break
        except OSError as e:
            if e.winerror != ERROR_BAD_LENGTH:
                raise
    return info.WorkingSetInfo

class PERFORMANCE_INFORMATION(Structure):
    _fields_ = (('cb',                DWORD),
                ('CommitTotal',       SIZE_T),
                ('CommitLimit',       SIZE_T),
                ('CommitPeak',        SIZE_T),
                ('PhysicalTotal',     SIZE_T),
                ('PhysicalAvailable', SIZE_T),
                ('SystemCache',       SIZE_T),
                ('KernelTotal',       SIZE_T),
                ('KernelPaged',       SIZE_T),
                ('KernelNonpaged',    SIZE_T),
                ('PageSize',          SIZE_T),
                ('HandleCount',       DWORD),
                ('ProcessCount',      DWORD),
                ('ThreadCount',       DWORD))
    def __init__(self, *args, **kwds):
        super(PERFORMANCE_INFORMATION, self).__init__(*args, **kwds)
        self.cb = sizeof(self)

PPERFORMANCE_INFORMATION = POINTER(PERFORMANCE_INFORMATION)

psapi.GetPerformanceInfo.errcheck = errcheck_bool
psapi.GetPerformanceInfo.argtypes = (
    PPERFORMANCE_INFORMATION, # _Out_ pPerformanceInformation
    DWORD)                    # _In_  cb

WorkingSetSize = namedtuple('WorkingSetSize', 'total shared private')

def working_set_size(pid=None):
    """Return the total, shared, and private working set sizes
       for the target process.
    """
    wset = query_working_set(pid)
    pinfo = PERFORMANCE_INFORMATION()
    psapi.GetPerformanceInfo(byref(pinfo), sizeof(pinfo))
    pagesize = pinfo.PageSize
    total = len(wset) * pagesize
    shared = sum(b.Shared for b in wset) * pagesize
    private = total - shared
    return WorkingSetSize(total, shared, private)

if __name__ == '__main__':
    import sys
    pid = int(sys.argv[1]) if len(sys.argv) > 1 else None
    try:
        total, shared, private = working_set_size(pid)
    except OSError as e:
        if e.winerror == ERROR_ACCESS_DENIED:
            sys.exit('Access Denied')
        raise
    width = len(str(total))
    print('Working Set: %*d' % (width, total))
    print('     Shared: %*d' % (width, shared))
    print('    Private: %*d' % (width, private))

rawDescription: Getting same process details as task manager in Windows


code:
old_stderr = os.dup(sys.stderr.fileno()) # keep a copy
fd = os.open('path/to/mylog', os.O_CREAT | os.O_WRONLY)
os.dup2(fd, sys.stderr.fileno())
# Now, stderr output, including NSLog output, should go to 'path/to/mylog'
...
os.dup2(old_stderr, sys.stderr.fileno())
#stderr restored to its old state

rawDescription: How to make NSLog work with Python's logging module when using PyObjC?

description: Make NSLog work with Python's logging module when using PyObjC


rawDescription: Matplotlib Image fit to equation?

description: Matplotlib Image fit to equation


code: [False, True, True, True]

rawDescription: Matching array with elements in rows of matrix


code: re.sub(r'[^D\s]+', r'', strs).split()

rawDescription: Filtering part of a list?

description: Filtering part of a list


code:
df = pd.DataFrame({"A": list("ABCDEF"), "B": "ABC ABD ABE ABC BC D".split()})
df["C"] = df["B"].str.contains("A")
df["D"] = df["B"].str.contains("C")
df

rawDescription: Not able to use 'if x in list' using pandas


code:
class User(db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128), unique=True)
    email = db.Column(db.String(255), unique=True)
    city = db.Column(db.String(255))
    country = db.Column(db.String(255))

rawDescription: Realistic data generator package available for Django


rawDescription: Printing X-type pattern in Python 2.7

description: Printing X-type pattern in Python 2.7


code:
import pandas as pd

data = pd.DataFrame({'Item':['Orange', 'Banana', 'Tomato', 'Laptop'],
                     'Type':['Edible, Fruit', 'Edible, Fruit', 'Edible, Vegetable', 'Non Edible, Electronic']})
print(data[data['Type'].str.contains('Fruit')])

rawDescription: Pandas - Groupby and create new DataFrame?


code:
result = []
for i in range(0, 5000):
    result.append(get_next_number())
print(result)

rawDescription: Generate random numbers without using the last n values in Python


code:
import csv

labels = [
    "Reading Comprehension", "Sentence Skills", "Arithmetic",
    "College Level Math", "Elementary Algebra"
]

with open('output.csv', 'wb') as outfile, \
     open('input.csv', 'rb') as infile:
    writer = csv.writer(outfile)
    reader = csv.reader(infile)

    for row in reader:
        head = row[:5]
        tail = []
        for label in labels:
            tail.append(next((i for i in row[5:] if i.startswith(label)), ""))
        writer.writerow(head + tail)

rawDescription: Reorder Columns by String Variable

description: Reorder Columns by String Variable


code:
schema_props = schema[exp][node]['properties']
schema_props['date'] = ...

rawDescription: short name for a string/dict/list index

description: Short name for a string/dict/list index


code:
mainMask = ' '.join(('_' for i in range(len(secretWord))))
numMask = ' '.join((str(i) for i in range(len(secretWord))))

rawDescription: displaying numbers underneath a mask in python

description: Displaying numbers underneath a mask in python


code:
def build_symmetric_list(n) :
    l = []
    for x in range(0,n) :
        ll = []
        for y in range(0,n) :
            if x<= y:
                ll.append((x,y))
            else :
                ll.append((y,x))
        l.append(ll)
    return l

@profile
def test_a():
    a = build_symmetric_list(1000)

test_a()

rawDescription: Large symmetric list in python: will references contribute to size in ram?


rawDescription: Import local testing version of a Python namespace package


code:
channels = [Ch1, Ch2]
channels

rawDescription: How to check user input in a list/tuple?

description: Check user input in a list/tuple


code:
from collections import OrderedDict

def one_more_one(s):
    for i, digit in enumerate(s):
        if digit == '0':
            yield s[:i] + '1' + s[i+1:]

bin_string = ['000', '100', '010', '001', '110', '101', '011', '111']
weights = [[-5, -13, -2], [16, -9], [-15, 2], [13, -13], [18], [-9], [18]]

d = OrderedDict()
for node, weight in zip(bin_string, weights):
    d[node] = OrderedDict(zip(one_more_one(node), weight))

rawDescription: Building a directed multigraph (Python)

description: Building a directed multigraph (Python)


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

time = np.arange(10)
temp = np.random.random(10)*30
Swdown = np.random.random(10)*100-10
Rn = np.random.random(10)*100-10

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

lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
lns2 = ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
lns3 = ax2.plot(time, temp, '-r', label = 'temp')

# added these three lines
lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=0)

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

rawDescription: Secondary axis with twinx(): how to add to legend?


rawDescription: What does this function do? (Python iterators)


rawDescription: How do do this list manipulation in Python? This is tricky


code:
class CaptainHook(object):
    def __init__(self, func):
        self.hooks = []
        self.func = func

    def __call__(self, *args, **kwargs):
        for hook in self.hooks:
            hook(*args, **kwargs)
        return self.func(*args, **kwargs)

rawDescription: How to mix *args, **kwargs and named arguments in decorator

description: Mix *args, **kwargs and named arguments in decorator


code:
for values in zip(*items.values()):
    item = dict(zip(items.keys(), values))
    print(item)

rawDescription: Turning list into dict

description: Turning list into dict


code: intervals = [d2[0] - d1[0] for (d1, d2) in zip(data, data[1:])]

rawDescription: Sum elements of a list (datetime) in one value


code:
import numpy as np
num_groups = 5
df['group'] = np.random.randint(num_groups, size=len(df))
dfs = [grp for key, grp in df.groupby('group')]

rawDescription: Divide pandas DataFrame rows in specific number of random sets


code:
def middle(x, y, z):
    return sorted([x, y, z])[1]

rawDescription: Finding the middle of three numbers

description: Finding the middle of three numbers


code: [nltk.tag.str2tuple(t) for t in sent.split() if t.split('/')[1] == 'NN']

rawDescription: exracting chunks in python using nltk

description: Exracting chunks in python using nltk


code:
from operator import itemgetter

dct = {}

with  open('data/titanic.csv') as infile, open('data/survivors.csv', 'w', newline='') as outfile:
    incsv = csv.reader(infile)
    outcsv = csv.writer(outfile)
    for survived, pclass, name, sex, age in map(itemgetter(0,1, 2, 3, 4), incsv):
        if survived == "1":
            last, first = name.split(",")
            dct[last] = [first, pclass, sex, age]

    sorted_names = sorted(dct)
    for last_name in sorted_names:
         outcsv.writerow( [last_name] + dct[last_name])

rawDescription: How do I split a csv field that has quotations into two fields?

description: Split a csv field that has quotations into two fields


rawDescription: Multiply Series by distributing across MultiIndex levels


code:
if isinstance(x, str):
    return True

rawDescription: Python Control Flow

description: Python Control Flow


code: finalDict = dict((k['id'], k['sigla']) for k in myDictList)

rawDescription: From List of Dictionary To Dictionary

description: From List of Dictionary To Dictionary


code:
if userobj is not None: # Make sure user exists
    username = userobj.name
    email = userobj.email

rawDescription: Referencing values using foreign key on flask sql-alchemy


rawDescription: How to merge Lists in Python?Merging python lists (0,1,2) & (A,B,C) to get (0A, 1B, 2C)

description: Merge Lists in Python?Merging python lists (0,1,2) & (A,B,C) to get (0A, 1B, 2C)


code:
df = pd.DataFrame({'F1': range(4)}, index=['x1', 'x2', 'y1', 'y2'])
df.groupby(lambda index: index[0]).sum()

rawDescription: The most effective way to organize info on Pandas dataframe


code:
def recursive_element_count(ob):
    if isinstance(ob, list):
        return sum(recursive_element_count(elem) for elem in ob)
    # anything that isn't a list counts as one element
    return 1

rawDescription: count number of elements with a list that also contains a list

description: Count number of elements with a list that also contains a list


code:
output = code.format(T=T) # where T is a string with a C++ class name
              # e.g. "int" or "std::vector<double>"

rawDescription: Cython: templates in python class wrappers


code:
def highscore(filename):
    if not os.path.isfile(filename):
        return 0
    with open(filename, 'r') as f:
        return int(f.read())

rawDescription: Python / Function parameters

description: Python / Function parameters


rawDescription: Python: How to find more than one pathway in a recursive loop when multiple child nodes refers back to the parent?


rawDescription: Slicing by start and stop string values in Python


code:
sums = (0, 0, 0)
for j in some_list:
    result = method(j)
    sums[0] += result[0]
    sums[1] += result[1]
    sums[2] += result[2]

rawDescription: Most pythonic way to 'or' tuples?

description: Most pythonic way to 'or' tuples


code:
s = "Hello %length there %0 man"
length = 0
args = ["something"]

rawDescription: Replace % followed by a number in a string


code: value = [ ",".join(str(x) for x in i) for i in value ]

rawDescription: Best way to convert value in nested list to string

description: Convert value in nested list to string


rawDescription: Safe conversion String of nested Lists to List - eval() and literal_eval()


code:
with open('sample.fastq') as fin, open('outfile.fastq', "w") as outf:
    for i, line in enumerate(fin):
        if i % 4 == 3:  # only change every fourth line
            # don't forget to do line[:-1] to get rid of newline
            qualities = [d[ch] for ch in line[:-1]]
            # take the average quality score. Note that as in your example,
            # this truncates each to an integer
            average = sum(qualities) / len(qualities)
            # new version; average with \n at end
            line = str(average) + "\n"

        # write line (or new version thereof)
        outf.write(line)

rawDescription: Read and replace the contents of a line using dictionary


code:
data[range(xmax)[::2],:] = 10
data

rawDescription: Multidimensional arrays, using range, while simultaneously having a set start, stop, and step?


code: 'get stuff from here'.partition('get')[-1].partition('here')[0]

rawDescription: Is that pythonic?

description: Is that pythonic


code:
table.setItem(rowPosition , 0, QtGui.QTableWidgetItem("text1"))
table.setItem(rowPosition , 1, QtGui.QTableWidgetItem("text2"))
table.setItem(rowPosition , 2, QtGui.QTableWidgetItem("text3"))

rawDescription: How to add a row in a tableWidget PyQT?

description: Add a row in a tableWidget PyQT


code:
def gu_pinv(a, rcond=1e-15):
    a = np.asarray(a)
    swap = np.arange(a.ndim)
    swap[[-2, -1]] = swap[[-1, -2]]
    u, s, v = np.linalg.svd(a)
    cutoff = np.maximum.reduce(s, axis=-1, keepdims=True) * rcond
    mask = s > cutoff
    s[mask] = 1. / s[mask]
    s[~mask] = 0

    return np.einsum('...uv,...vw->...uw',
                     np.transpose(v, swap) * s[..., None, :],
                     np.transpose(u, swap))

rawDescription: Python, simultaneous pseudo-inversion of many 3x3, singular, symmetric, matrices


code: self.assertTrue(myInt >= 3 and myInt <= 8)

rawDescription: Is there a python assert() method which checks between two boundaries?


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


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


code:
pd.DataFrame.denormalise = denormalise
df1.denormalise('wares', 'categories')
df1.denormalise('wares', 'categories').reset_index(drop=True)

rawDescription: Denormalise the data using Pandas

description: Denormalise the data using Pandas


code:
import urllib
import re
import lxml.html
import unicodedata
import os

class Song(object):
    def __init__(self, artist, title):
        self.artist = self.__format_str(artist)
        self.title = self.__format_str(title)
        self.url = None
        self.lyric = None

    def __format_str(self, s):
        # remove paranthesis and contents
        s = s.strip()
        try:
            # strip accent
            s = ''.join(c for c in unicodedata.normalize('NFD', s)
                         if unicodedata.category(c) != 'Mn')
        except:
            pass
        s = s.title()
        return s

    def __quote(self, s):
         return urllib.parse.quote(s.replace(' ', '_'))

    def __make_url(self):
        artist = self.__quote(self.artist)
        title = self.__quote(self.title)
        artist_title = '%s:%s' %(artist, title)
        url = 'http://lyrics.wikia.com/' + artist_title
        self.url = url

    def update(self, artist=None, title=None):
        if artist:
            self.artist = self.__format_str(artist)
        if title:
            self.title = self.__format_str(title)

    def lyricwikia(self):
        self.__make_url()
        try:
            doc = lxml.html.parse(self.url)
            lyricbox = doc.getroot().cssselect('.lyricbox')[0]
        except IOError:
            self.lyric = ''
            return
        lyrics = []

        for node in lyricbox:
            if node.tag == 'br':
                lyrics.append('\n')
            if node.tail is not None:
                lyrics.append(node.tail)
        self.lyric =  "".join(lyrics).strip()
        return self.lyric

rawDescription: Crawling this website to grab lyrics?

description: Crawling this website to grab lyrics


code:
import sqlite3
conn = sqlite3.connect(':memory:')
curs = conn.cursor()
results = curs.execute( """SELECT mycol
                             FROM mytable
                            WHERE somecol = ?;""", (some_var,) ).fetchall()
curs.close()
conn.close()

rawDescription: Loading SQLite3 values into Python variables


code:
index = 0
i = 0
while index < len(inputphrase):
    if inputphrase[index] in vowels:
        i += 1
    index += 1
print(i)

rawDescription: Python While loops with tuples

description: Python While loops with tuples


rawDescription: Match bullet numbers with regex using python


code:
from ast import literal_eval

with open("input.txt") as fp, open("output.txt", "wb") as out:
    result = []
    for line in fp:
        tup = literal_eval(line.rstrip())
        if not all(ii % 2 for ii in tup) and sum(tup) >= 80:
            out.write(line)

rawDescription: Filter list of tuples to removes lists with all odd number or sum less than 80


code:
def dispose(iterator):
    for i in iterator:
        pass

rawDescription: In Python, is there a way to call a method on every item of an iterable?


code: drawPropagation(1.0, 1.0, numpy.linspace(-2, 2, 10))

rawDescription: Matplotlib plot pulse propagation in 3d

description: Matplotlib plot pulse propagation in 3d


rawDescription: efficiently dstack arrays from dictionary python

description: Efficiently dstack arrays from dictionary python


code:
# do NOT use:
from a import balance
balance = balance + 1

# DO use:
import a
a.balance = a.balance + 1

rawDescription: How do I import and change a value from one script to another in python?

description: Import and change a value from one script to another in python


code: Panes = []

rawDescription: Why aren't my old boxes disappearing?

description: Why aren't my old boxes disappearing


code:
for i in range(16):
    dfs['B'+str(i)] = dfs['BINDATA'].str[i]

rawDescription: How to split a dataframe column into multiple columns

description: Split a dataframe column into multiple columns


code: isinstance(obj2, type(obj1))

rawDescription: Test an object is a subclass of the type of another instance


code:
[sum(x) for x in zip(*dict1.values())]
[sum(x) for x in zip(*dict2.values())]

rawDescription: Adding to List on For Loop (What do I set the List to initially?)


code:
sent = input("Sentence:").split()
lkupwrd = str(input("What word do you want to look up?")).lower()

wordList = [word.lower() for word in sent]

if lkupwrd in wordList:
    print([i for i,j in enumerate(wordList) if j == lkupwrd])

rawDescription: Python. user input(1) string to list. User input (2) finds if there is the word in the first user input


code: drugInfo.rename(columns = {drugInfo.columns[1]: 'col_1_new_name'}, inplace = True)

rawDescription: Pandas: Rename single DataFrame column without knowing column name


code: totalprice += foodprice

rawDescription: Nested while loop with trailer values

description: Nested while loop with trailer values


code:
import networkx as nx
import itertools as IT
import matplotlib.pyplot as plt

class BinaryTree(object):
   def __init__(self, data):
      self.data = data
      self.right = None
      self.left = None
      self.name = None
   def edgelist(self, counter = IT.count().next):
       self.name = counter() if self.name is None else self.name
       for node in (self.left, self.right):
           if node:
               node.name = counter() if node.name is None else node.name
               yield (self.name, node.name)
       for node in (self.left, self.right):
           if node:
               for n in node.edgelist(counter):
                   yield n

tree = [BinaryTree(i) for i in range(5)]
tree[0].left = tree[1]
tree[0].right = tree[2]
tree[2].left = tree[3]
tree[2].right = tree[4]

edgelist = list(tree[0].edgelist())
print(edgelist)

G = nx.Graph(edgelist)
nx.draw_spectral(G)
plt.show()

rawDescription: Edgelist from a binary tree

description: Edgelist from a binary tree


code:
def model(B, C, UV):
    U = UV[:len(UV)//2]
    V = UV[len(UV)//2:]
    H = np.dot(U, B+C) + 1j*np.dot(V, B+C)
    return H.view(float)

rawDescription: Constraining the least squares fitting in python


code:
if type(x) is type(y):
    fight()

rawDescription: Python: asking if two objects are the same class


code:
import clr
clr.AddReference("SharpSvn")

rawDescription: How to add .dll reference to ironpython VS2010 project?

description: Add .dll reference to ironpython VS2010 project


code:
@celery.task(name='app.expensive_greet', bind=True)
@send_emails
def expensive_greet(self, person, total):
    try:
        for i in range(total):
            time.sleep(0.1)
            self.update_state(state='PROGRESS',
                              meta={'current': i, 'total': total})
        return 'Greetings, {}!'.format(person)
    except SoftTimeLimitExceeded:
        # Note that raise this exception to allow the decorator catch it
        # and return the value of the exception
        raise NotifyException('Greetings, fallback!')

rawDescription: Send mail on Celery task success/failure reliably


code: colors = plt.get_cmap('Spectral')(np.linspace(0, 1, 10))

rawDescription: pyplot equivalent for pl.cm.Spectral in matplotlib

description: Pyplot equivalent for pl.cm.Spectral in matplotlib


code:
for p in Person.objects.raw('SELECT * FROM myapp_person'):
    print(p)

rawDescription: Is it possible to use raw SQL with python's django web framework?


code:
arr = aligned_array(2**4, ctypes.c_double, 512)
hex(ctypes.addressof(arr))
arr = aligned_array(2**8, ctypes.c_double, 512)
hex(ctypes.addressof(arr))
arr = aligned_array(2**12, ctypes.c_double, 512)
hex(ctypes.addressof(arr))
arr = aligned_array(2**16, ctypes.c_double, 512)
hex(ctypes.addressof(arr))

rawDescription: Python ctypes align data structure

description: Python ctypes align data structure


code:
for i in range(1,5):
    contentB = tree.xpath("//table[@class='yfnc_tabledata1']/tr[1]/td/table/tr[3]/td[{i}]".format(i=i))[0].text_content().strip()
    print(contentB)

rawDescription: LXML - parse td content within tr tag

description: LXML - parse td content within tr tag


code:
var = "C:\\level1\\level2\\level3\\level4\\level5\\level6\\level7\\level8"
var.split('\\', 7)
var.split('\\', 7)[-1]

rawDescription: Parse directory path to a variable in python


code:
import Tkinter as tk

def analyze(event=None):
    content = aEntry.get()
    if content == "":
        aEntry.insert(0, "default")

lord = tk.Tk()

aEntry = tk.Entry(lord)
aEntry.grid()

aText = tk.Text(lord, font=("Arial", "12", "bold"))
aText.grid()

aEntry.bind("<FocusOut>", analyze)

lord.mainloop()

rawDescription: Inserting a default value into tkinter Entry stops validation


code: new_string = re.sub(r'(@\w+)', r'<\g<0>>', old_string)

rawDescription: Python String Replace Behaving Weirdly

description: Python String Replace Behaving Weirdly


code: ZTASKD_URL = 'ipc:///tmp/%s_ztask.sock' % SITE_NAME

rawDescription: Django and SaaS + Ztask for backgroud tasks


code:
x = MyClass() # create an instance of MyClass
x.GET()

rawDescription: How to call a class's method in python?

description: Call a class's method in python


code:
program_top = 315 + 37.5 * idx
if not program_top % 1.0:
    program_top = int(program_top)

rawDescription: Replace the string

description: Replace the string


code:
f=open(file,"r")
lines=f.readlines()
result=[]
for x in lines:
    result.append(x.split(' ')[1])
f.close()

rawDescription: Reading specific columns from a text file in python


code:
set(['all',
     'and blotted by every',
     'first are born but',
     'are to be scrawled',
     'are',
     'spotless paper when',
     'white a sheet of',
     'quill'])

rawDescription: Find maximum length of all n-word-length substrings shared by two strings


code: logger = logging.getLogger(__name__)

rawDescription: Elegant setup of Python logging in Django


code:
yourdata = [{'key': {'subkey': 1}}, {'key': {'subkey': 10}}, {'key': {'subkey': 5}}]
yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)
yourdata

rawDescription: sorting list of nested dictionaries in python

description: Sorting list of nested dictionaries in python


rawDescription: How to post to Google Measurement protocol using Python?

description: Post to Google Measurement protocol using Python


code:
{
    status: "ok",
    url: "img1.jpg"
}

rawDescription: Call a dynamic python function after the webpage is loaded in Django


code:
list_keys = ['fname','lname','dob']
list_data = [['bob','smith','12121950'],['john','jones','10101940']]
[dict(zip(list_keys, data)) for data in list_data]

rawDescription: Python: convert 2 lists to dict and repeat the keys with each set of data


rawDescription: What is the correct way to store data N with associated properties if I've 100s of N to track?


code:
import tensorflow as tf

B = 2
N = 2
scores = tf.constant([0.5, 0.2, -0.1, 1., -0.5, 0.3])  # shape B * (N+1)

scores = tf.reshape(scores, [B, N+1])

scores_pos = tf.slice(scores, [0, 0], [B, 1])

scores_neg = tf.slice(scores, [0, 1], [B, N])

rawDescription: Max margin loss in TensorFlow

description: Max margin loss in TensorFlow


code: df.apply(lambda row: all(i in row.B for i in row.A), axis=1)

rawDescription: Pandas: How to Compare Columns of Lists Row-wise in a DataFrame with Pandas (not for loop)?


code:
for j in range(0,1):
   for i in range(0,ncols):
      np.append(z, [23])

rawDescription: Reshaping Arrays in Numpy with variables


code:
B = [0] * len(A)
for i, v in enumerate(A):
    B[v] = i

B

rawDescription: Swapping indices with values in a Python list?


rawDescription: Convering double backslash to single backslash in Python 3


rawDescription: Centering a Numpy array of images

description: Centering a Numpy array of images


code:
## NOTE: This is untested
def SliderDrawer(self):
    for i in range(0,self.Slider2.GetMax()):
        self.Slider2.SetValue(i+1)
        wx.Yield() ## Added the Yield function
        time.sleep(0.1) ## Increased time so that visual can be seen

def PlaySlider(self,event):
    wx.CallAfter(self.SliderDrawer)
    event.Skip()

rawDescription: wxPython - Play slider

description: WxPython - Play slider


code:
outliers = []
for p in points:
  (x,y) = p
  if not inAnyPolygons(x,y,polygons):
    outliers.append(p)
return outliers

rawDescription: Removing points inside several polygons

description: Removing points inside several polygons


code:
vals[0]
int(vals[0])
vals[2]
float(vals[2])

rawDescription: Dividing a string by type of data inside each line of file in python


code: pd_obj = pd.read_csv('test_csv.csv', header=None, index_col=0, names=range(5))

rawDescription: Python Pandas read_csv issue

description: Python Pandas read_csv issue


code:
[{'choices': [['',
               {'english': 'All Items',
                'french': 'All Items (fr translated)'}],
              [0, {'english': 'Item 0', 'french': 'Item 0 (fr translated)'}],
              [1, {'english': 'Item 1', 'french': 'Item 1 (fr translated)'}],
              [2, {'english': 'Item 2', 'french': 'Item 2 (fr translated)'}]],
  'id': 'field_1',
  'label': {'english': 'Items', 'french': 'Items (fr translated)'},
  'type': 'choicefield'},
 {'choices': None,
  'id': 'field_2',
  'label': {'english': 'Keywords', 'french': 'Keywords (fr translated)'},
  'type': 'textfield'},
 {'choices': None,
  'id': 'field_3',
  'label': {'english': 'Agree?'},
  'type': 'checkbox'}]

rawDescription: Merging dictionary values inPython

description: Merging dictionary values inPython


code:
Contact(
    contactName='xxx',
    channel=[ '1', '2' ],
    channelCode=[ChannelCodeType.TELEPHONE, ChannelCodeType.FAX]
)

rawDescription: XmlAttribute for an unbounded primitive type


rawDescription: Getting the attribute holder of an attribute


code:
df['country'] = df['season'].apply(get_country)
df

rawDescription: Find key from value for Pandas Series

description: Find key from value for Pandas Series


code:
@task
def bulk_create_notifications(fans, photo_id):
    fan_list = []
    for fan in fans:
        fan_list.append(PhotoObjectSubscription(viewer_id=fan, which_photo_id=photo_id, updated_at=time, seen=False, type_of_object='1'))
    PhotoObjectSubscription.objects.bulk_create(fan_list)

rawDescription: The right way to perform a task asynchronously in Django, via Celery


rawDescription: Unzipp recursively even when the zip file has no folders


code:
import cgi
from pprint import pformat
from javax.servlet.http import HttpServlet

class Index(HttpServlet):
    def doPost(self,req,res):
        res.setContentType("text/html")
        out = res.getWriter()

        out.println('Headers')

        headers = {}
        for n in req.headerNames:
                headers[n] = req.getHeader(n)
        out.println('
')
        out.println(pformat(headers))
        out.println('

')

        out.println('Form fields')

        # get the POST data fields
        form = {}
        for field in req.parameterMap:
                form[field] = list(req.parameterMap[field])

#        # Alternative - if you *really* want a FieldStorage object, construct
#        # one from the request body, headers and faked environment variables.
#        # N.B. assumes that the request body is one line of POST data only.
#        from StringIO import StringIO
#        request_body = req.reader.readLine()
#        form = cgi.FieldStorage(fp=StringIO(request_body),
#                    headers=headers,
#                    environ={'REQUEST_METHOD': 'POST',
#                             'CONTENT_LENGTH': len(request_body)})

        out.println('
%s

' % pformat(form))

rawDescription: Why fieldStorage is empty in Jython Servlet post request


code:
from StringIO import StringIO
import csv
csvfile = StringIO()
csvfile.seek(0)
fieldnames = ['first_name', 'last_name']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
csvfile.seek(0)

rawDescription: Mock CSV DictReader

description: Mock CSV DictReader


code:
_classdefs = {}
def getClassDef(name):
  global _classdefs, _classes
  _classdefs[name] = "class " + name + "(object):\n   def __init__(self):\n"
  classvars = _classes[name].split(" ")
  for x in classvars:
    vals = x.split(":")
    if (vals[1] == "array"):
      c = _classes[vals[0]].split(":")[0]
      if (not _classdefs.has_key(c)):
        getClassDef(c)
      _classdefs[name] += "    self." + vals[0] + " = []\n"
    elif (vals[1] == "text"):
      _classdefs[name] += "    self." + vals[0] + " = \"\"\n"
    elif (vals[1] == "numeric"):
      _classdefs[name] += "    self." + vals[0] + " = 0\n"
    elif (vals[1] == "object"):
      if (not _classdefs.has_key(vals[0])):
        getClassDef(vals[0])
      subclassvars = _classes[vals[0]].split(" ")
      for z in subclassvars:
        if (z.split(":")[0] == "variable_name"):
          _classdefs[name] += "    self." + z.split(":")[1] + " = " + vals[0] + "()\n"

rawDescription: using dynamic python class definition and amfast dynamic class mapping and code generation to generate ActionScript class

description: Using dynamic python class definition and amfast dynamic class mapping and code generation to generate ActionScript class


code:
def change_2(v):
    v = v[:]
    v[2] = 6
    return v

rawDescription: how to pass a list as value and not as reference?

description: Pass a list as value and not as reference


rawDescription: python string compare issue in a list

description: Python string compare issue in a list


code: set(['platinum-shakers.net', 'wmi.ns01.us', 'adservice.no-ip.org', 'samczeruno.pl', 'java.ns1.name', 'microsoft.dhcp.biz', 'ids.us01.us', 'devsite.quostar.com', 'orlandmart.com'])

rawDescription: Remove duplicates after altering items

description: Remove duplicates after altering items


code:
import numpy as np
poly=np.array([['610.0', '1150.0'],
   ['675', '1150'],
   ['675', '1215'],
   ['610', '1215'],
   ['610', '1150']],
  dtype='|S32')

print("poly", poly)

print()

#print(poly.shape())

print("poly.tolist()", poly.tolist())

#print(poly.T)
print()

print("poly.transpose()", poly.transpose())

rawDescription: Transform numpy ndarray from a column list to row list


rawDescription: How to insert duplicated values in dictionary?

description: Insert duplicated values in dictionary


code:
dictionary = {'time': allTimes,
              'type': allTypes,
              'who': allWhos,
              'id': allIds,
              'msg': allMsgs}

rawDescription: How do I make one python dictionary to csv with headers?

description: Make one python dictionary to csv with headers


code:
import re, math, pprint
import requests, urlparse
from bs4 import BeautifulSoup, SoupStrainer

def get_pages(root):
    links = []
    r = requests.get(root)

    mat = re.search(r'We have (\d+) apartments for rent', r.text)
    num_results = int(mat.group(1))                     # 182 at the moment
    num_pages = int(math.ceil(num_results/20.0))        # ceil(182/20) => 10

    # Construct links for pages 1-10
    for i in range(num_pages):
        links.append("%s?page=%d" % (root, (i+1)))

    return links

def get_listings(page):
    links = []
    r = requests.get(page)

    for link in BeautifulSoup(r.text, parse_only=SoupStrainer('a')):
        if link.has_attr('href') and link.has_attr('data-listingid') and 'name' in link.get('class'):
            links.append(urlparse.urljoin(root, link.get('href')))

    return links

root='http://www.apartmentguide.com/apartments/Alabama/Hartselle/'
listings = []
for page in get_pages(root):
    listings += get_listings(page)

pprint.pprint(listings)
print(len(listings))

rawDescription: Get list of all paginated URL's from links in txt file in python requests


code:
def flatten(lst):
    try:
        return flatten(sum(lst, []))
    except TypeError:
        return lst

rawDescription: How to print list of list into one single list in python without using any for or while loop?

description: Print list of list into one single list in python without using any for or while loop


rawDescription: Implementing XorShift the same in Java and Python


rawDescription: Storing a string and a set in a dictionary


code:
from datetime import datetime
from werkzeug.routing import BaseConverter, ValidationError

class DateConverter(BaseConverter):
    """Extracts a ISO8601 date from the path and validates it."""

    regex = r'\d{4}-\d{2}-\d{2}'

    def to_python(self, value):
        try:
            return datetime.strptime(value, '%Y-%m-%d').date()
        except ValueError:
            raise ValidationError()

    def to_url(self, value):
        return value.strftime('%Y-%m-%d')

app.url_map.converters['date'] = DateConverter

rawDescription: date in Flask URL

description: Date in Flask URL


code:
def save_model(self, request, obj, form, change):
    # do something with obj and request here....
    obj.save()

rawDescription: How to access REMOTE_ADDR in a model's save() method

description: Access REMOTE_ADDR in a model's save() method


code:
b = x.read(1)
firstfivebits = b >> 3

rawDescription: How I can read a bit in Python?

description: How I can read a bit in Python


rawDescription: Python: Taking an array and break it into subarrays based on some criteria


code:
from bs4 import BeautifulSoup as soup

x = ['Wal-Mart Stores, Inc.	', 'Sinopec Group	']
tmp = [soup(y).find('td').find('a') for y in x]
lst = [x['title'].strip() for x in tmp if x.has_attr('title')]
print(lst)

rawDescription: Python Regex expression for parsing HTML document


code:
def test_corrcoef():
    a = np.array([
        [1, 2, 3, 4],
        [1, 3, 1, 4],
        [8, 3, 8, 5]])

    r1, p1 = corrcoef(a)
    r2, p2 = corrcoef_loop(a)

    assert np.allclose(r1, r2)
    assert np.allclose(p1, p2)

rawDescription: Correlation coefficients and p values for all pairs of rows of a matrix


code: list(res)

rawDescription: How do you join all items in a list in python

description: Join all items in a list in python


code: value = number in my_true_numbers

rawDescription: Reducing memory used by a large dict

description: Reducing memory used by a large dict


rawDescription: Unable to remove additional double quotes in json string added by python


rawDescription: Python image conversion

description: Python image conversion


code:
from collections import Counter

c = Counter("text")
print(c.most_common())

rawDescription: Find Rare Characters with Python

description: Find Rare Characters with Python


code:
def x_intercept(m, b):
    """
    Return the x intercept of the line M{y=m*x+b}.  The X{x intercept}
    of a line is the point at which it crosses the x axis (M{y=0}).

    This function can be used in conjuction with L{z_transform} to
    find an arbitrary function's zeros.

    @type  m: number
    @param m: The slope of the line.
    @type  b: number
    @param b: The y intercept of the line.  The X{y intercept} of a
              line is the point at which it crosses the y axis (M{x=0}).
    @rtype:   number
    @return:  the x intercept of the line M{y=m*x+b}.
    """
    return -b/m

rawDescription: How do I specify input and output data types in python comments?

description: Specify input and output data types in python comments


code:
from django.utils import formats
date_format = get_format('DATE_FORMAT')

rawDescription: Get datetime mask for a given locale

description: Get datetime mask for a given locale


code:
class Enemy(object):
   def __init__(self, name, strength, armour, health):
      self.name = name
      # Rest of the attributes

rawDescription: How to assign multiple values to one variable

description: Assign multiple values to one variable


code:
def round_robin_odd(d, n):
    for i in range(n):
        h = [[d[j], d[-j-1]] for j in range(n/2)]
        h[-1].append(d[n/2])
        yield h
        d.rotate()

rawDescription: Generating all unique pair permutations

description: Generating all unique pair permutations


code:
if row_id in ids_to_keep:
    out.write(line)

rawDescription: Improve efficiency in Python matching

description: Improve efficiency in Python matching


code:
ind = zip(*[pat0+pat1])
named_ind = pandas.MultiIndex.from_tuples(ind, names = ['Patients'])
df = pandas.DataFrame({'T1avg':ser})
df['Slice']=pandas.Series(numpy.append(slc, slc), index=df.index)

rawDescription: Combining MultiIndex and Index in a PANDAS DataFrame


code:
def restore_state():
    try:
        with open('saveit', 'r') as f:
            a = int(f.read())
    except IOError:
        a = 0
    return a

rawDescription: Python counter between running code

description: Python counter between running code


code:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
DEFAULT_FROM_EMAIL = 'Whatever <whatever@example.com>'

rawDescription: Django + Postfix

description: Django + Postfix


code:
delta = xx - yy
D = np.sqrt(np.einsum('nj,jk,nk->n', delta, VI, delta))

rawDescription: Calculate Mahalanobis distance using NumPy only


code:
day:     {{ countdown|date:"D" }}
hour:    {{ countdown|date:"g" }}
minute:  {{ countdown|date:"i" }}
second:  {{ countdown|date:"s" }}

rawDescription: Django DateTimeField to a day hour minute second


code:
import operator
# Below is a mapping of op symbols to their corresponding functions
ops = {
    '+' : operator.add,
    '-' : operator.sub,
    '*' : operator.mul,
    '/' : operator.truediv,
    '==' : operator.eq,
    '>' : operator.gt,
    '<' : operator.lt
}
def func(op, x, y):
    try:
        return ops[op](x, y)
    except KeyError:
        return 'ERROR'

rawDescription: Make use of binary operation sign in a variable


code:
r = requests.get("http://minewind.com/forums",
    headers={'User-Agent': 'Mozilla'})
r.status_code
r.url
r.history

rawDescription: Why am I not able to grab from the url?

description: Why am I not able to grab from the url


code:
values = [1,1,1,1,2,2,3,4,5,3]

def get_next_item_ind(x, ind):
    my_dict = get_matches(x)
    indexes = my_dict[x[ind]]
    temp_ind = indexes.index(ind)
    if len(indexes) > temp_ind + 1:
        return(indexes)[temp_ind + 1]
    return None

rawDescription: Optimize search to find next matching value in a list


code:
Cook, Chef, Fireman
Cook, Chef, Fireman
Cook, Chef, Fireman
Cook, Chef, Fireman
House, Farm, Road

rawDescription: Change case of first letter in every cell in spreadsheet


rawDescription: Consolidating row data from DB into a list of dicts


code:
def set_description(build_url, desc):
    req_data = urllib.urlencode({'description': desc})
    req = urllib2.Request(build_url + '/submitDescription', req_data)
    req.add_header('Content-Type', 'application/x-www-form-urlencoded')
    urllib2.urlopen(req)

rawDescription: Set Hudson Build Description via Web API


code:
labels = ['a', 'b', 'c', 'd', 'e']

for column, label in zip(arr.T, labels):
    ax.plot(column, label=label)

rawDescription: Assign label names for line plot from numpy 2D array


rawDescription: Selecting the first index after a certain timestamp with a pandas TimeSeries


code:
bad_values = filter(lambda value_tuple: value_tuple[1],
                    [(myvalue, why_bad(myvalue)) for myvalue in all_values])

rawDescription: python list_comprehension to get multiple values

description: Python list_comprehension to get multiple values


code: next(array for array in [Di, Dj, Dk] if CONDITION)

rawDescription: Python - Uniquely determining which text file an element originated from


code:
# Get reversed cumprod of b and pad with `1` at the end
b_rev_cumprod = b[::-1].cumprod()[::-1]
B = np.hstack((b_rev_cumprod,1))

# Get K
K = a*b

# Append with 0 at the start, corresponding starting d
K_ext = np.hstack((0,K))

# Perform elementwsie multiplication and cumsum and scale down for final c
sums = (B*K_ext).cumsum()
c = sums[1:]/b_rev_cumprod

rawDescription: Cumulative addition/multiplication in NumPy


code: [(x,y,x*y) for x in range(1,5) for y in range(1,5)]

rawDescription: Comprehensions in Python and Javascript are only very basic?


code:
for i in range(20):
    print_square(i)

rawDescription: Check statement for a loop only once

description: Check statement for a loop only once


rawDescription: Take laplacian of unevenly sampled data in python


code:
def __setitem__(self, key, value, PREV=0, NEXT=1, dict_setitem=dict.__setitem__):
    'od.__setitem__(i, y) <==> od[i]=y'
    # Setting a new item creates a new link at the end of the linked list,
    # and the inherited dictionary is updated with the new key/value pair.
    if key not in self:
        root = self.__root
        last = root[PREV]
        last[NEXT] = root[PREV] = self.__map[key] = [last, root, key]
    dict_setitem(self, key, value)

rawDescription: Why does overriding __contains__ break OrderedDict.keys?


rawDescription: Select a specific column in a DF and a random column (python3, pandas)


code:
from bs4 import BeautifulSoup
from pprint import pprint

result = {}
soup = BeautifulSoup(page)
divs = soup.find_all("div", {"class":"info"})
for div in divs:
    name = div.find("a")["id"]
    table = div.find_next("table", {"class":"properties"})
    rows = table.find_all("tr", {"class":None})
    rowd = {}
    for row in rows:
        cells = row.find_all("td")
        rowd[cells[0].text] = cells[1].text
    result[name] = rowd
pprint (result)

rawDescription: How to create structured array out of unstructured HTML using python

description: Create structured array out of unstructured HTML using python


code:
import sys
import re

for line in sys.stdin:
    line = line.strip()
    portions = re.split(r'\t+', line)
    status = portions[-1]
    if status.islower():
        whatever_you_want_to_write = status + ',' + portions #whatever
        sys.stdout.write(whatever_you_want_to_write)

rawDescription: MapReduce programming to filter a large input file


code: df != df.shift()

rawDescription: Drop Duplicate in market data

description: Drop Duplicate in market data


code: value = data[closest_match]

rawDescription: Finding a string in a list and returning a secondary value with python


code:
import click

@click.command(name='my-cmd', context_settings=dict(
    ignore_unknown_options=True,
    allow_extra_args=True,
))
@click.option('--option1')
@click.option('--option2')
@click.pass_context
def cli(ctx, option1, option2):
    click.echo({ctx.args[i][2:]: ctx.args[i+1] for i in xrange(0, len(ctx.args), 2)})

rawDescription: Add unspecified options to cli command using python-click


rawDescription: Inverse cumsum for numpy

description: Inverse cumsum for numpy


rawDescription: Are class variables in the scope of instance methods or class methods?


code:
dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
        dicts[i] = values[i]
print(dicts)

rawDescription: populating a dictionary using for loops (python)

description: Populating a dictionary using for loops (python)


code:
@pytest.fixture(scope="session", params=["one", "two", "three"])
def myfixture():
    pytest.param = request.param
    # ...

rawDescription: Skip test depending on parameter in py.test


code:
with open(infilename, 'r') as infile, open(outfilename, 'w') as outfile:
    for line in infile:
        value = mydict.get(line.strip())
        if value is not None:
            outfile.write(value + '\n')

rawDescription: Reading a text file and matching it to a dictionary key in python


code: class User: ...

rawDescription: How do I call a property setter from __init__

description: Call a property setter from __init__


code:
import pandas as pd

# some example data
qry = pd.DataFrame.from_dict({"Keyword": ["NewWordsWithFriends",
                                          "com.fingerarts.sudoku"],
                              "Game": ["Words With Friends",
                                       "Sudoku by FingerArts"]})

df = pd.DataFrame.from_dict({"user-agent" : ["NewWordsWithFriendsFree/2.3 CFNetwork/672.1.15 Darwin/14.0.0",
                                             "iPhone3,1; iPhone OS 7.1.2; com.fingerarts.sudoku2; 143441-1,24"]})

keywords = qry.Keyword.tolist()
games = qry.Game.tolist()

def select(x):
    for key, game in zip(keywords, games):
        if key in x:
            return game

df["GameName"] = df["user-agent"].apply(select)

rawDescription: Python Pandas: Lookup table by searching for substring


code:
import os
def fixpath(path):
    path = os.path.normpath(os.path.expanduser(path))
    if path.startswith("\\"): return "C:" + path
    return path

rawDescription: Using absolute unix paths in windows with python


code: (OrderedDict(row) for i, row in df.iterrows())

rawDescription: How to turn pandas dataframe row into ordereddict fast

description: Turn pandas dataframe row into ordereddict fast


code:
A = [2,3,1,4,5,2,4]
B = [4,2,3,6,2,5,1]
[i for sublist in [[a, b] if a < b else [b, a] for a, b in zip(A, B)] for i in sublist]

rawDescription: Make one list from two list applying constraint


code: print("The value is {}".format(d["key{}".format(x)]))

rawDescription: Printing a formatted dictionary key

description: Printing a formatted dictionary key


code: rows = cur.fetchall()

rawDescription: graph from weighted edge list from a database

description: Graph from weighted edge list from a database


rawDescription: Making a raw dictionary sane

description: Making a raw dictionary sane


code:
k.press_key(k.shift_key)
k.press_key(k.control_key)
k.type_string("u03a3")
k.release_key(k.shift_key)
k.release_key(k.control_key)

rawDescription: Save text cursor position in the currently focused application/control, then restore it and paste text


code: dummy = indices - 1

rawDescription: np.where() not returning expected indices in numpy python

description: Np.where() not returning expected indices in numpy python


code:
string_with_color = '#00ff00'  # gathered somehow

color = QtGui.QColor(0, 0, 0)
color.setNamedColor(string_with_color)

rawDescription: Qt - Format QColor to be used in Style Sheet?


code:
p = ctypes.cast("foo", ctypes.POINTER(ctypes.c_char))
void_p = ctypes.cast(p, ctypes.c_voidp).value+1
p = ctypes.cast(void_p, ctypes.POINTER(ctypes.c_char))
p.contents

rawDescription: Python: how to increment a ctypes POINTER instance


rawDescription: How to sort a Series or DataFrame by a given index order?

description: Sort a Series or DataFrame by a given index order


code:
{'pups': ['pusp', 'upsp', 'upps', 'upsp', 'uspp'],
'cups': ['cusp', 'cpus', 'cpsu', 'csup', 'cspu']}

rawDescription: Python: Create Dictionary From List with [0] = Key and [1:]= Values


code: l2_sum[key] = l2_sum.get(key, 0) + num

rawDescription: Eliminate dups and sum corresponding terms in lists


rawDescription: Numpy indexing multidimensional arrays with array and slice


code:
#!/usr/bin/python
import json
import cgi
import cgitb
import sys
reload(sys)
sys.setdefaultencoding('utf8')
form = cgi.FieldStorage()
cityRu = form.getvalue('city')
print ("Content-type: text/html")
print ("")
with open('json/cities.json') as jf:
    cities = json.load(jf)
cities_with_ru = filter(lambda x: 'ru' in x['name_translations'], cities)
for rs in cities_with_ru:
    print (rs['name_translations']['en']+' - '+rs['name_translations']['ru'])

rawDescription: enumeration values in json

description: Enumeration values in json


code: f.extend(os.path.splitext(name)[0] for name in filenames)

rawDescription: remove extension in list python

description: Remove extension in list python


code:
def windows(a, w, _as_strided=stride_tricks.as_strided):
    windows_shape = tuple(sa - sw + 1 for sa, sw in zip(a.shape, w))
    windows_shape += w
    windows_strides = a.strides + a.strides
    return _as_strided(a, windows_shape, windows_strides)

def rotation_matrix1(section, _windows=windows):
    rot_filters = windows(section.reshape(5, 5), (3, 3)).reshape(9, 9)
    return rot_filters[rot_filters.std(1).argmin(),:].mean()

rawDescription: Optimizing implementation of a rotating mask in numpy/scipy


rawDescription: Index of columns where rows match criterion Python Pandas


rawDescription: Calculate string values dynamically

description: Calculate string values dynamically


code:
class BlogPostList(ListAPIView):

    def get_queryset(self):
        user = self.request.user
        return BlogPost.objects.prefetch_related(
            Prefetch(
                'likes',
                queryset=BlogPostLikes.objects.filter(user=user) \
                    .select_related('user'),
                to_attr='likes_by_request_user'
            )
        )

rawDescription: Django (django-rest-framework) looking for a best practice to find out wether request.user exists in blog.likes


code:
from operator import itemgetter
import numpy as np

_, modes_sorted = zip(*sorted(zip(amplitudes, modes.T), key=itemgetter(0)))
modes_sorted = np.array(modes_sorted)

rawDescription: Sort a 1D array and a 2D array(by column) simultaneously


rawDescription: Get element inside current element using xpath


code:
def get_choice_by_name(name, choices, case_sensitive=False):
    try:
        if name is None:
            return ''
        elif name and not case_sensitive:
            return next(k for k, n in choices
                        if n.lower() == name.lower())
        else:
            return next(k for k, n in choices if n == name)
    except StopIteration:
        raise ValueError(
            "Invalid choice: {}, not found in {}".format(name, choices)
        )

class DenormalizedChoiceField(TypedChoiceField):

    def clean(self, value):
        if not value:
            return self.empty_value
        try:
            value = get_choice_by_name(value, self.choices)
        except ValueError as e:
            raise ValidationError(str(e))

        value = super(DenormalizedChoiceField, self).clean(value)
        return value

rawDescription: Importing Denormalized data into django models via modelforms


code: ss = 'hello string [processing] in python.'

rawDescription: Search patern to include square brackets


code:
for choice in self.choices:
    if len(choice) == 2:
        choice.append(None)
    yield tuple( [el for el in choice] + [selected] )

rawDescription: Loop with 3 or 2 items to unpack in Python


code:
X_test[:2]
y_test[:2]
[bunch.target_names[idx] for idx in y_test[:2]]

rawDescription: Load Custom Dataset (which is like 20 news group set) in Scikit for Classification of text documents


code:
QShortcut(Qt.Key_Enter, self.Begin, self.Begin.animateClick)
QShortcut(Qt.Key_Return, self.Begin, self.Begin.animateClick)

rawDescription: QT Designer how to assign 2 hotkeys to a QPushButton (python3)


code:
from numpy.core.umath_tests import inner1d

out = inner1d(arr[:, :, None, None], arr)

rawDescription: Iterate over all pairwise combinations of numpy array columns


code:
import csv
import pprint

s = '''\
0000001,0,-94.8,28
0000001,6,-95.4,28
0000002,7,-97.6,29
'''.splitlines()

event_map = {'0000001': '123456', '0000002': '789012'}

groupdict = {}
for row in csv.reader(s):
    source_id = row[0]
    event_id = event_map[source_id]
    data = row[1:]
    groupdict.setdefault(event_id, []).append(data)
pprint.pprint(groupdict)

rawDescription: Append a list to the value for matching key values


code:
def consumer_view(request):
    response = requests.get('http://your-url.com/your-endpoint')
    # do what you need to do here

rawDescription: Consuming Django Rest Api in the same project


code:
import time
import sys

print('Fishing', end='')
sys.stdout.flush()
for i in range(5):
    time.sleep(1)
    print('.', end='', flush=True)  # another way

rawDescription: Strange print behavior with time.sleep in python


rawDescription: How to conver this list/tuple in the following list in Python?

description: Conver this list/tuple in the following list in Python


rawDescription: Scrape arraytodatatable with python

description: Scrape arraytodatatable with python


code:
x = [1, 2, 3]
count(*(float(y) for y in x), **{'three': x.pop()})

rawDescription: Evaluation order of positional and keyword arguments


code:
import ast
# construct a string literal, with the 'u' prefix
s2_literal = u'u"%s"' % s2
s2_literal
print(ast.literal_eval(s2_literal))

# also works with single-quotes string literals
s2_literal2 = u"u'%s'" % s2
s2_literal2

print(ast.literal_eval(s2_literal2))

rawDescription: how to convert unicode string on unicode format with python?

description: Convert unicode string on unicode format with python


code:
import cv2
import PIL.Image
import PIL.ImageTk
import Tkinter as tk

def update_image(image_label, cv_capture):
    cv_image = cv_capture.read()[1]
    cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
    pil_image = PIL.Image.fromarray(cv_image)
    tk_image = PIL.ImageTk.PhotoImage(image=pil_image)
    image_label.configure(image=tk_image)
    image_label._image_cache = tk_image  # avoid garbage collection
    root.update()

def update_all(root, image_label, cv_capture):
    if root.quit_flag:
        root.destroy()  # this avoids the update event being in limbo
    else:
        update_image(image_label, cv_capture)
        root.after(10, func=lambda: update_all(root, image_label, cv_capture))

if __name__ == '__main__':
    cv_capture = cv2.VideoCapture()
    cv_capture.open(0)  # have to use whatever your camera id actually is
    root = tk.Tk()
    setattr(root, 'quit_flag', False)
    def set_quit_flag():
        root.quit_flag = True
    root.protocol('WM_DELETE_WINDOW', set_quit_flag)  # avoid errors on exit
    image_label = tk.Label(master=root)  # the video will go here
    image_label.pack()
    root.after(0, func=lambda: update_all(root, image_label, cv_capture))
    root.mainloop()

rawDescription: Tkinter display other windows

description: Tkinter display other windows


code:
def format_rows(rows, gap):
    split_rows = [row.split(',') for row in rows]
    # Splits each row up, by comma
    column_lengths = [max(col_len) for col_len in zip(*[map(len, row) for row in split_rows])]
    # Finds the maximum size of each column

    output = []
    for row in split_rows:
        col_lengths = zip(row, column_lengths)
        output.append(''.join(col.ljust(col_length + gap, ' ') for (col, col_length) in col_lengths))
    return '\n'.join(output)

rawDescription: python yahoo finance format

description: Python yahoo finance format


code:
a = 3
b = [3]
def change_a(something):
    something = 4
def change_b(something):
    something[0] = 4
change_a(a)
change_b(b)
print(a,b) # prints "3 4"

rawDescription: Why is there no insert() method for strings in Python?


rawDescription: Unicode extraction

description: Unicode extraction


code:
class Event(models.Model):
    content_type      = models.ForeignKey(ContentType)
    object_id         = models.PositiveIntegerField()
    content_object    = generic.GenericForeignKey('content_type', 'object_id')

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

class EventMixin(object):
     @property
     def get_event(self):
         ctype = ContentType.objects.get_for_model(self.__class__)
         try:
             event = Event.objects.get(content_type__pk = ctype.id, object_id=self.id)
         except:
            return None
         return event

class Action1(EventMixin, models.Model):
    # Don't need to mess up the models fields (make sure the mixing it placed before models.Model)
    ...

rawDescription: Generic one-to-one relation in Django

description: Generic one-to-one relation in Django


code:
first=[row[0] for row in data]
rownum1=[row[1] for row in data]
rownum2=[row[2] for row in data]

rawDescription: Find and display rows with approximately close entries


code:
kolkata_timetuple = kolkata_datetime.timetuple()
print(kolkata_timetuple)
# time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=5, tm_min=30, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

rawDescription: How to add two offset in python?

description: Add two offset in python


code:
def getAnswer():
    while True:
        a = input()
        try:
            return int(a)
        except ValueError:
            print('Numbers only please...')

rawDescription: Python <function functionName at 0x00000000>


code:
import tkinter as TK     # TK is a convenient, easy to type alias to use for tkinter.
gui = TK.Tk()
gui.geometry("500x500")   # don't forget the quotes

rawDescription: Tkinter importing without *?

description: Tkinter importing without *


code:
class LoginForm(SafeForm):
   email=TextField(__("E-Mail"),validators=[Required()])
   password=PasswordField(__("Password"),validators=[Required()])
   submit=SubmitField(__("Login"))

   def __init__(self,*k,**kk):
      self._user=None #for internal user storing
      super(LoginForm,self).__init__(*k,**kk)

   def validate(self):
       self._user=User.query.filter(User.email==self.email.data).first()
       return super(LoginForm,self).validate()

   def validate_email(self,field):
       if self._user is None:
           raise ValidationError(_("E-Mail not recognized"))

   def validate_password(self,field):
       if self._user is None:
           raise ValidationError() #just to be sure
       if not self._user.validate_password(self.password.data): #passcheck embedded into user model
           raise ValidationError(_("Password incorrect"))

rawDescription: Invalid Login logic in Flask Python

description: Invalid Login logic in Flask Python


rawDescription: Split dictionary key and list of values from dict


code:
m = Mock(spec=actual_fu)
m('foo', bar='baz')

m.assert_called_once_with(foo='foo', bar='baz')
m.assert_called_once_with('foo', bar='baz')
m.assert_called_once_with(bar='baz', foo='foo')
m.assert_called_once_with('foo', 'baz')

rawDescription: check unittest.mock call arguments agnostically w.r.t. whether they have been passed as positional arguments or keyword arguments

description: Check unittest.mock call arguments agnostically w.r.t. whether they have been passed as positional arguments or keyword arguments


code:
import hashlib
myhash = hashlib.sha1("Fox".encode('utf-8'))
myhash.digest()
myhash.hexdigest()

rawDescription: Checking SHA1 on a String

description: Checking SHA1 on a String


code:
a = [1,2,3]
b = "foo"
d = []
d.extend(a)
d.append(b)
d

rawDescription: appending dictionaries to a list

description: Appending dictionaries to a list


code:
results = [item['green'] for item in D['b']]
# ['second', 'fourth']

rawDescription: multiple iteration through python dictionary

description: Multiple iteration through python dictionary


code:
class ListOptions(object):
    pass

class Options(object):
    @classmethod
    def list(cls):
        return ListOptions

    @classmethod
    def __setattr__(cls, name, value):
        if instance(value, list):
            value = [] + value
        else:
            value = [ value ]
        object.__setattr__(cls, name, value[-1])
        setattr(ListOptions, name, value)

setattr(Options, 'opt', Option('opt', None))

rawDescription: How to return the native object value when not accessed as a list

description: Return the native object value when not accessed as a list


rawDescription: How to test membership of sequence in python list?

description: Test membership of sequence in python list


rawDescription: How to manually create a sparse matrix in Python

description: Manually create a sparse matrix in Python


code:
d = {"male": 0, "female": 1}
pd.read_csv(file.csv, converters={2: d.get})

rawDescription: categorical variables with pandas

description: Categorical variables with pandas


code: range(3, 6)

rawDescription: Getting a list of the range of 2 pandas columns


code:
def data(self,index,role):
    if not index.isValid():
        return(None)
    elif role == QtCore.Qt.CheckStateRole:
        return("")
    elif role != QtCore.Qt.DisplayRole:
        return(None)
    else:
        return(self.data[index.row()][index.column()])

rawDescription: How to hide checkboxes in a QTableView using python?

description: Hide checkboxes in a QTableView using python


code:
sp_mat.getnnz(axis=0)
#  array([1, 1, 2, 1, 1])

rawDescription: Check Density of a Scipy Sparse Matrix

description: Check Density of a Scipy Sparse Matrix


code:
rng = [d for d in rng
       if d.weekday() < 5
       and d.hour >= 7
       and d.hour < 18
       and (False if d.hour == 17 and d.minute > 30
            else True)
      ]

rawDescription: Pandas create an intraday DateTimeIndex between 2 times each day excluding weekends and holidays


rawDescription: Python regular expressions not recognizing \number


rawDescription: Is there any way to map on arrays, and return an array in Python?


rawDescription: numpy genfromtxt issues in Python3

description: Numpy genfromtxt issues in Python3


code:
import re

regexp = re.compile(r'Max Tsai-Wu.*?([0-9.-]+)')
result = []
with open('input.txt') as f:
    for line in f:
        match = regexp.match(line)
        if match:
            result.append(match.group(1))

rawDescription: Python: Finding values after searching for a string in a text files


code:
with open('myfile.csv','wb') as myfile:
    wrtr = csv.writer(myfile, delimiter=',', quotechar='"')
    for row in rows:
        wrtr.writerow([row.field1,row.field2,row.field3])
        myfile.flush() # whenever you want

rawDescription: CSVWriter not saving data to file - WHY?

description: CSVWriter not saving data to file - WHY


code:
l1=['a','b','c', 'd']
l2= ['a','b','d','f']
for (i,wor) in enumerate(l1):
    if wor in l2:
        l1[i]= 33
    else:
        del l1[i]
    print(i, len(l1))

rawDescription: Python Replace elements in a list that are also in another list, and delete others


code: dates - pd.Timestamp('1970-01-01')

rawDescription: Creating column with difference in two rows in pandas


code:
class MyArticleAdminForm(forms.ModelForm):
    class Meta:
        model = Article
    def clean_name(self):
        return self.cleaned_data["name"].upper()

rawDescription: Changing case (upper/lower) on adding data through Django admin site


rawDescription: Split one level of an multi index into columns


code: Result=system("'MKVMerge' -o 'NewVideo' CommandLine 'MKVVideo'")

rawDescription: mkvtoolnix bulk remove audio tracks

description: Mkvtoolnix bulk remove audio tracks


code:
from django.db import models
from django.db import transaction

class MyModel(models.Model):
    # model definition

    def save(self, *args, **kwargs):
        transaction.set_autocommit(False)
        try:
            super(MyModel, self).save(*args, **kwargs)
            foo() # do_other_things
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()
        finally:
            transaction.set_autocommit(True)

rawDescription: Django models: managing transactions when commit_manually is deprecated


code:
from itertools import product
matches = [(t,p) for t,p in product(targets,prefixes) if t.startswith(p)]
print(matches)

rawDescription: checking if any element in a list starts with any of a number of prefixes in Python?

description: Checking if any element in a list starts with any of a number of prefixes in Python


code:
da = np.insert(da, 0,0)
da = np.append(da, len(a))
np.diff(da)

rawDescription: Measure distance between objects in picture with python


code:
lis=[['a', 10, 20], ['b', 10, 20], ['a', 20, 100]]
lis.sort(key=itemgetter(0)) #sort the list first
lis
[[k]+map(sum,zip(*[x[1:] for x in g])) for k,g in groupby(lis,key=itemgetter(0))]

rawDescription: combining list elements in a list

description: Combining list elements in a list


code:
def f(a, b, c):
    print("{} {} {}".format(a, b, c))

def main():
    iterable = [1, 2, 3, 4, 5]
    pool = multiprocessing.Pool()
    a = "hi"
    b = "there"
    func = partial(f, a, b)
    pool.map(func, iterable)
    pool.close()
    pool.join()

if __name__ == "__main__":
    main()

rawDescription: Passing multiple parameters to pool.map() function in Python


code:
oscar_prot = None

def get_B_instance(b_instance):
    global oscar_prot
    oscar_prot = b_instance

d = Deferred()
d.addCallback(get_B_instance)

protocol.ClientCreator(reactor, OA, SN, PASS, deferred=d, icq=icqMode).connectTCP(*hostport)

rawDescription: Sending ICQ messages from outside event handlers in Twisted, Oscar


code:
from uuid import uuid4
from datetime import datetime

class cached_descriptor(object):
    def __init__(self, func, timeout):
        self.__doc__ = getattr(func, '__doc__')
        self.func = func
        self.uuid = str(uuid.uuid4())
        self.timeout = timeout

    def __get__(self, obj, cls):
        if obj is None:
            return self
        if not hasattr(obj, '_cache'):
            obj._cache = {}
        if self.uuid not in obj._cache:
            obj._cache[self.uuid] = []
        data = obj._cache[self.uuid]
        now = datetime.now()
        if not data or (now - data[1]).total_seconds() > self.timeout:
            obj._cache[self.uuid] = (self.func(obj), now)
        return obj._cache[self.uuid][0]

class cached_property(object):
    def __init__(self, timeout):
        self.timeout = timeout

    def __call__(self, func):
        return cached_descriptor(func, self.timeout)

rawDescription: How can I cache API data in a class attribute?

description: Cache API data in a class attribute


code:
class AddressMixin(object):
    @declared_attr
    def street(cls):
        return Column(Text, ...)

class CustomerAddress(Base, AddressMixin):
    __tablename__ = 'customer_addresses'
    id = ...

rawDescription: sqlalchemy - multiple files - relationships

description: Sqlalchemy - multiple files - relationships


code:
def num_points(arr, axis):
    try:
        return arr.shape[axis]
    except IndexError:
        return 1

rawDescription: Check number of columns numpy array that returns 1 if is a 1-dimensional array


code:
import os
import lxml.etree as ET

# SET CURRENT DIRECTORY
cd = os.path.dirname(os.path.abspath(__file__))

# LOAD IN XML AND XSL FILES
dom = ET.parse(os.path.join(cd, 'Original.xml'))
xslt = ET.parse(os.path.join(cd, 'XSLT_Script.xsl'))

# TRANSFORM
transform = ET.XSLT(xslt)
newdom = transform(dom)

# OUTPUT FINAL XML
tree_out = ET.tostring(newdom, encoding='UTF-8', pretty_print=True, xml_declaration=True)

xmlfile = open(os.path.join(cd, 'output.xml'),'wb')
xmlfile.write(tree_out)
xmlfile.close()

rawDescription: how to add xml child node with namespace in python?

description: Add xml child node with namespace in python


code:
hdfreset = hdf.reset_index()
hdfreset.columns = ['a', 'b', 'occurrence']
hdfpivot=hdfreset.pivot('a', 'b')

rawDescription: Create Contour Plot from Pandas Groupby Dataframe


code:
import dis
def del_by_pop(mylist):
    mylist.pop(-1)

def del_by_del(mylist):
    del mylist[-1]

rawDescription: Remove all trailing zeroes in Python list


code:
for element in soup_original_2.body:
    soup_original_1.body.append(element)

rawDescription: How to concatenate two html file bodies with BeautifulSoup?

description: Concatenate two html file bodies with BeautifulSoup


rawDescription: Convert array of dictionaries into 2 dimensional array with potentially non-matching fieldnames


code: yield dict1[item1], dict2[item2]

rawDescription: Help using *args in tuple matching Python function


rawDescription: how does the python min function works

description: How does the python min function works


code:
translation = {'Apfel': 'Apple', 'Erdbeere' : 'Strawberry'}
fruit = 'Apfel'
translation[fruit]
fruit = 'Erdbeere'
translation[fruit]

rawDescription: Conditional renaming of strings in Python


code:
def wrapped_apicall(color=None, size=None):
    if color is None and size is None:
        return apicall()
    # At least one argument is not None, so...
    if size is None:
        # color is not None
        return apicall(color)
    if color is None:
        # size is not None
        return apicall(size)
    # Neither argument is None
    return apicall(color, size)

rawDescription: Python -- Only pass arguments if the variable exists


code:
import csv

with open('output.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, dialect='excel')
    spamwriter.writerow(header)
    for row in data:
        spamwriter.writerow(row)

rawDescription: Looping through a list of hosts and commands in Paramiko and store the result in excel with column headers


code: print(gradeScores(grader(testOne, testTwo, testThree, finalExam))) #will replace with values

rawDescription: Calculate final letter grade in Python given 4 test scores


code:
class Foo:
    def __init__(self):
        self.elements = [3, 4, 5]

    def __getitem__(self, index):
        return self.elements[index]

rawDescription: Access class variables with __repr__()

description: Access class variables with __repr__()


code: t.mark_set(INSERT, '2.3')

rawDescription: Setting the position of the insert character in the tkinter text widget


code:
from xlsxwriter.workbook import Workbook

# Create an new Excel file and add a worksheet.
workbook = Workbook('wrap_text2.xlsx')
worksheet = workbook.add_worksheet()

# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)

# Add a cell format with text wrap on.
cell_format = workbook.add_format({'text_wrap': True})

# Write a wrapped string to a cell.
worksheet.write('A1', "Line 1\nLine 2\nLine 3", cell_format)

workbook.close()

rawDescription: Writing multi-line strings into cells using openpyxl


code:
days = 'Mon Tue Wed Thu Fri Sat Sun'.split()
days_1 = {d: n for n, d in enumerate(days)}
def weekdays_between(s, e):
    s, e = days_1[s], days_1[e]
    return [days[n % 7] for n in range(s, e + (1 if e > s else 8))]

weekdays_between('Wed', 'Fri')
weekdays_between('Sat', 'Tue')

rawDescription: How can I get all days between two days?

description: Get all days between two days


code:
class Child(Person):
    def __init__(self, age):
        Person.__init__(self, age=age)

    gets_drink = dec(Person.gets_drink.__func__)

rawDescription: How would one decorate an inherited method in the child class?


code:
def __iter__(self):
    for i in range(self.natoms):
        yield self[i + 1]

rawDescription: Define a iterable class supporting two or more simultaneous iterating


code:
class MyStr(str):
    def change(self): # 's' argument is replaced by 'self'
        result=""
        for index,item in enumerate(self): # Use 'self' here instead of 's'
            if(index%2 !=0): result=result+item
        return(result)

rawDescription: How to add my own method to the built-in str type?

description: Add my own method to the built-in str type


rawDescription: extract a str contained between 2 str

description: Extract a str contained between 2 str


code:
import heapq
import json

data = json.loads(json_string)
limited = {k: data[k] for k in heapq.nsmallest(data, 10, key=int)}

rawDescription: Load part of a json in python

description: Load part of a json in python


rawDescription: Iterate list of numbers

description: Iterate list of numbers


code:
from io import StringIO
import pandas

datacsv = StringIO("""\
XY UV  BC   Val
y  u    c    11
y  u    b    22
y  v    c    33
y  v    b    44
x  u    c    111
x  u    b    222
x  v    c    333
x  v    b    444
""")
df = pandas.read_csv(datacsv, sep='\s+')
df.set_index(['XY', 'UV', 'BC']).unstack(level='BC')

rawDescription: Pandas dataframe - transform column values into individual columns


rawDescription: Mock same method with different return value called twice in a function in python


code:
final = {}
for id, (x, n) in dict2.items():
    final.setdefault(dict1[x], {})[id] = n

rawDescription: Reconstruct dictionary in python

description: Reconstruct dictionary in python


code:
import re

ls=[]

with open('data.csv') as f:
    for line in f:
        ls.append(line)

for w in ls:
    if "saleAmount" in w and int(re.findall('\d+',w)[0]) < 1000:
        print(w)
        for i in range(1,4):
            print(ls[ls.index(w)+i])

rawDescription: parse a file for a line with specific text, then logic to determine next steps

description: Parse a file for a line with specific text, then logic to determine next steps


code:
root_str = etree.tostring(root_el, encoding=unicode)
root_len_chars = len(root_str)

rawDescription: Convert XML to string to find length

description: Convert XML to string to find length


rawDescription: how to iterate through the list, fetching each possible pair of values?

description: Iterate through the list, fetching each possible pair of values


code:
lister_sum = sum(int(i) for i in a )
return lister_sum % 10 == 0 or lister_sum == 0

rawDescription: Python efficiency query

description: Python efficiency query


rawDescription: ordering by a field in a foreign key alphabetically

description: Ordering by a field in a foreign key alphabetically


code:
from functools import wraps
from mock import Mock
def decor(f):
    @wraps(f)
    def wrapper(*args, **kwds):
        return f(*args, **kwds)
    return wrapper

mock_func = Mock()
decor(mock_func)
mock_func.__name__ = 'foo'
decor(mock_func)

rawDescription: python mock: @wraps(f) problems

description: Python mock: @wraps(f) problems


code:
c = 10
d = 10
id(c) == id(d)
c is d

rawDescription: References and copies in python

description: References and copies in python