code:
import ctypes
from ctypes import wintypes

kernel32 = ctypes.WinDLL('kernel32.dll', use_last_error=True)
winspool = ctypes.WinDLL('winspool.drv', use_last_error=True)

# define LPHANDLE, PDWORD, and PWORD for Python 2
if not hasattr(wintypes, 'LPHANDLE'):
    setattr(wintypes, 'LPHANDLE', ctypes.POINTER(wintypes.HANDLE))
if not hasattr(wintypes, 'PDWORD'):
    setattr(wintypes, 'PDWORD', ctypes.POINTER(wintypes.DWORD))
if not hasattr(wintypes, 'PWORD'):
    setattr(wintypes, 'PWORD', ctypes.POINTER(wintypes.WORD))

INFINITE = -1
WAIT_OBJECT_0 = 0x00000000
WAIT_TIMEOUT  = 0x00000102
WAIT_FAILED   = 0xFFFFFFFF
INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value

PRINTER_CHANGE_ADD_PRINTER               = 0x00000001
PRINTER_CHANGE_SET_PRINTER               = 0x00000002
PRINTER_CHANGE_DELETE_PRINTER            = 0x00000004
PRINTER_CHANGE_FAILED_CONNECTION_PRINTER = 0x00000008
PRINTER_CHANGE_PRINTER                   = 0x000000FF

PRINTER_CHANGE_ADD_JOB                   = 0x00000100
PRINTER_CHANGE_SET_JOB                   = 0x00000200
PRINTER_CHANGE_DELETE_JOB                = 0x00000400
PRINTER_CHANGE_WRITE_JOB                 = 0x00000800
PRINTER_CHANGE_JOB                       = 0x0000FF00

PRINTER_CHANGE_ADD_FORM                  = 0x00010000
PRINTER_CHANGE_SET_FORM                  = 0x00020000
PRINTER_CHANGE_DELETE_FORM               = 0x00040000
PRINTER_CHANGE_FORM                      = 0x00070000

PRINTER_CHANGE_ADD_PORT                  = 0x00100000
PRINTER_CHANGE_CONFIGURE_PORT            = 0x00200000
PRINTER_CHANGE_DELETE_PORT               = 0x00400000
PRINTER_CHANGE_PORT                      = 0x00700000

PRINTER_CHANGE_ADD_PRINT_PROCESSOR       = 0x01000000
PRINTER_CHANGE_DELETE_PRINT_PROCESSOR    = 0x04000000
PRINTER_CHANGE_PRINT_PROCESSOR           = 0x07000000
PRINTER_CHANGE_SERVER                    = 0x08000000 # NT 6.1+

PRINTER_CHANGE_ADD_PRINTER_DRIVER        = 0x10000000
PRINTER_CHANGE_SET_PRINTER_DRIVER        = 0x20000000
PRINTER_CHANGE_DELETE_PRINTER_DRIVER     = 0x40000000
PRINTER_CHANGE_PRINTER_DRIVER            = 0x70000000

PRINTER_CHANGE_ALL                       = 0x7F77FFFF
PRINTER_CHANGE_TIMEOUT                   = 0x80000000

PRINTER_NOTIFY_CATEGORY_ALL = 0x00
PRINTER_NOTIFY_CATEGORY_3D  = 0x01

PRINTER_NOTIFY_TYPE = 0x00
JOB_NOTIFY_TYPE     = 0x01

PRINTER_NOTIFY_FIELD_SERVER_NAME            = 0x00 # not supported
PRINTER_NOTIFY_FIELD_PRINTER_NAME           = 0x01
PRINTER_NOTIFY_FIELD_SHARE_NAME             = 0x02
PRINTER_NOTIFY_FIELD_PORT_NAME              = 0x03
PRINTER_NOTIFY_FIELD_DRIVER_NAME            = 0x04
PRINTER_NOTIFY_FIELD_COMMENT                = 0x05
PRINTER_NOTIFY_FIELD_LOCATION               = 0x06
PRINTER_NOTIFY_FIELD_DEVMODE                = 0x07
PRINTER_NOTIFY_FIELD_SEPFILE                = 0x08
PRINTER_NOTIFY_FIELD_PRINT_PROCESSOR        = 0x09
PRINTER_NOTIFY_FIELD_PARAMETERS             = 0x0A
PRINTER_NOTIFY_FIELD_DATATYPE               = 0x0B
PRINTER_NOTIFY_FIELD_SECURITY_DESCRIPTOR    = 0x0C
PRINTER_NOTIFY_FIELD_ATTRIBUTES             = 0x0D
PRINTER_NOTIFY_FIELD_PRIORITY               = 0x0E
PRINTER_NOTIFY_FIELD_DEFAULT_PRIORITY       = 0x0F
PRINTER_NOTIFY_FIELD_START_TIME             = 0x10
PRINTER_NOTIFY_FIELD_UNTIL_TIME             = 0x11
PRINTER_NOTIFY_FIELD_STATUS                 = 0x12
PRINTER_NOTIFY_FIELD_STATUS_STRING          = 0x13 # not supported
PRINTER_NOTIFY_FIELD_CJOBS                  = 0x14
PRINTER_NOTIFY_FIELD_AVERAGE_PPM            = 0x15
PRINTER_NOTIFY_FIELD_TOTAL_PAGES            = 0x16 # not supported
PRINTER_NOTIFY_FIELD_PAGES_PRINTED          = 0x17 # not supported
PRINTER_NOTIFY_FIELD_TOTAL_BYTES            = 0x18 # not supported
PRINTER_NOTIFY_FIELD_BYTES_PRINTED          = 0x19 # not supported
PRINTER_NOTIFY_FIELD_OBJECT_GUID            = 0x1A
PRINTER_NOTIFY_FIELD_FRIENDLY_NAME          = 0x1B # NT 6.0+
PRINTER_NOTIFY_FIELD_BRANCH_OFFICE_PRINTING = 0x1C # NT 6.2+

JOB_NOTIFY_FIELD_PRINTER_NAME        = 0x00
JOB_NOTIFY_FIELD_MACHINE_NAME        = 0x01
JOB_NOTIFY_FIELD_PORT_NAME           = 0x02
JOB_NOTIFY_FIELD_USER_NAME           = 0x03
JOB_NOTIFY_FIELD_NOTIFY_NAME         = 0x04
JOB_NOTIFY_FIELD_DATATYPE            = 0x05
JOB_NOTIFY_FIELD_PRINT_PROCESSOR     = 0x06
JOB_NOTIFY_FIELD_PARAMETERS          = 0x07
JOB_NOTIFY_FIELD_DRIVER_NAME         = 0x08
JOB_NOTIFY_FIELD_DEVMODE             = 0x09
JOB_NOTIFY_FIELD_STATUS              = 0x0A
JOB_NOTIFY_FIELD_STATUS_STRING       = 0x0B
JOB_NOTIFY_FIELD_SECURITY_DESCRIPTOR = 0x0C # not supported
JOB_NOTIFY_FIELD_DOCUMENT            = 0x0D
JOB_NOTIFY_FIELD_PRIORITY            = 0x0E
JOB_NOTIFY_FIELD_POSITION            = 0x0F
JOB_NOTIFY_FIELD_SUBMITTED           = 0x10
JOB_NOTIFY_FIELD_START_TIME          = 0x11
JOB_NOTIFY_FIELD_UNTIL_TIME          = 0x12
JOB_NOTIFY_FIELD_TIME                = 0x13
JOB_NOTIFY_FIELD_TOTAL_PAGES         = 0x14
JOB_NOTIFY_FIELD_PAGES_PRINTED       = 0x15
JOB_NOTIFY_FIELD_TOTAL_BYTES         = 0x16
JOB_NOTIFY_FIELD_BYTES_PRINTED       = 0x17
JOB_NOTIFY_FIELD_REMOTE_JOB_ID       = 0x18

PRINTER_NOTIFY_OPTIONS_REFRESH = 0x01
PRINTER_NOTIFY_INFO_DISCARDED  = 0x01

JOB_STATUS_PAUSED            = 0x00000001
JOB_STATUS_ERROR             = 0x00000002
JOB_STATUS_DELETING          = 0x00000004
JOB_STATUS_SPOOLING          = 0x00000008
JOB_STATUS_PRINTING          = 0x00000010
JOB_STATUS_OFFLINE           = 0x00000020
JOB_STATUS_PAPEROUT          = 0x00000040
JOB_STATUS_PRINTED           = 0x00000080
JOB_STATUS_DELETED           = 0x00000100
JOB_STATUS_BLOCKED_DEVQ      = 0x00000200
JOB_STATUS_USER_INTERVENTION = 0x00000400
JOB_STATUS_RESTART           = 0x00000800
JOB_STATUS_COMPLETE          = 0x00001000
JOB_STATUS_RETAINED          = 0x00002000
JOB_STATUS_RENDERING_LOCALLY = 0x00004000
JOB_STATUS_ALL               = 0x00007FFF

JOB_STATUS_STRING = {
    JOB_STATUS_PAUSED:   'PAUSED',
    JOB_STATUS_ERROR:    'ERROR',
    JOB_STATUS_DELETING: 'DELETING',
    JOB_STATUS_SPOOLING: 'SPOOLING',
    JOB_STATUS_PRINTING: 'PRINTING',
    JOB_STATUS_OFFLINE:  'OFFLINE',
    JOB_STATUS_PAPEROUT: 'PAPEROUT',
    JOB_STATUS_PRINTED:  'PRINTED',
    JOB_STATUS_DELETED:  'DELETED',
    JOB_STATUS_BLOCKED_DEVQ: 'BLOCKED_DEVQ',
    JOB_STATUS_USER_INTERVENTION: 'USER_INTERVENTION',
    JOB_STATUS_RESTART:  'RESTART',
    JOB_STATUS_COMPLETE: 'COMPLETE',
    JOB_STATUS_RETAINED: 'RETAINED',
    JOB_STATUS_RENDERING_LOCALLY: 'RENDERING_LOCALLY'}

class SYSTEMTIME(ctypes.Structure):
    _fields_ = (('wYear',         wintypes.WORD),
                ('wMonth',        wintypes.WORD),
                ('wDayOfWeek',    wintypes.WORD),
                ('wDay',          wintypes.WORD),
                ('wHour',         wintypes.WORD),
                ('wMinute',       wintypes.WORD),
                ('wSecond',       wintypes.WORD),
                ('wMilliseconds', wintypes.WORD))
    @property
    def as_datetime(self):
        from datetime import datetime
        return datetime(self.wYear, self.wMonth, self.wDay,
                        self.wHour, self.wMinute, self.wSecond,
                        self.wMilliseconds * 1000)

class PRINTER_NOTIFY_OPTIONS_TYPE(ctypes.Structure):
    _fields_ = (('Type',      wintypes.WORD),
                ('Reserved0', wintypes.WORD),
                ('Reserved1', wintypes.DWORD),
                ('Reserved2', wintypes.DWORD),
                ('Count',     wintypes.DWORD),
                ('_pFields',  wintypes.PWORD))
    def __init__(self, Type=JOB_NOTIFY_TYPE, pFields=None):
        super(PRINTER_NOTIFY_OPTIONS_TYPE, self).__init__(Type)
        if pFields is not None:
            self.pFields = pFields
    @property
    def pFields(self):
        ptr_t = ctypes.POINTER(wintypes.WORD * self.Count)
        return ptr_t(self._pFields.contents)[0]
    @pFields.setter
    def pFields(self, pFields):
        self.Count = len(pFields)
        self._pFields = pFields

PPRINTER_NOTIFY_OPTIONS_TYPE = ctypes.POINTER(PRINTER_NOTIFY_OPTIONS_TYPE)

class PRINTER_NOTIFY_OPTIONS(ctypes.Structure):
    _fields_ = (('Version', wintypes.DWORD),
                ('Flags',   wintypes.DWORD),
                ('Count',   wintypes.DWORD),
                ('_pTypes', PPRINTER_NOTIFY_OPTIONS_TYPE))
    def __init__(self, Flags=0, pTypes=None):
        super(PRINTER_NOTIFY_OPTIONS, self).__init__(2, Flags)
        if pTypes is not None:
            self.pTypes = pTypes
    @property
    def pTypes(self):
        ptr_t = ctypes.POINTER(PRINTER_NOTIFY_OPTIONS_TYPE * self.Count)
        return ptr_t(self._pTypes.contents)[0]
    @pTypes.setter
    def pTypes(self, types):
        if isinstance(types, PRINTER_NOTIFY_OPTIONS_TYPE):
            self.Count = 1
            self._pTypes = ctypes.pointer(types)
        else:
            self.Count = len(types)
            self._pTypes = types

PPRINTER_NOTIFY_OPTIONS = ctypes.POINTER(PRINTER_NOTIFY_OPTIONS)

class PRINTER_NOTIFY_INFO_DATA(ctypes.Structure):
    class _NOTIFY_DATA(ctypes.Union):
        class  _DATA(ctypes.Structure):
            _fields_ = (('cbBuf', wintypes.DWORD),
                        ('pBuf',  wintypes.LPVOID))
        _fields_ = (('adwData', wintypes.DWORD * 2),
                    ('Data',    _DATA))
    _fields_ = (('Type',        wintypes.WORD),
                ('Field',       wintypes.WORD),
                ('Reserved',    wintypes.DWORD),
                ('Id',          wintypes.DWORD),
                ('_NotifyData', _NOTIFY_DATA))
    @property
    def _data_as_string(self):
        if self._NotifyData.Data.pBuf:
            return ctypes.c_wchar_p(self._NotifyData.Data.pBuf).value
        return u""
    @property
    def _data_as_datetime(self):
        if self._NotifyData.Data.pBuf:
            t = SYSTEMTIME.from_address(self._NotifyData.Data.pBuf)
        else:
            t = SYSTEMTIME()
        return t.as_datetime
    @property
    def NotifyData(self):
        if self.Type == JOB_NOTIFY_TYPE:
            if self.Field == JOB_NOTIFY_FIELD_PRINTER_NAME:
                return 'job_printer_name', self._data_as_string
            if self.Field == JOB_NOTIFY_FIELD_MACHINE_NAME:
                return 'job_machine_name', self._data_as_string
            if self.Field == JOB_NOTIFY_FIELD_USER_NAME:
                return 'job_user_name', self._data_as_string
            elif self.Field == JOB_NOTIFY_FIELD_STATUS:
                return 'job_status', self._NotifyData.adwData[0]
            elif self.Field == JOB_NOTIFY_FIELD_DOCUMENT:
                return 'job_document', self._data_as_string
            elif self.Field == JOB_NOTIFY_FIELD_PRIORITY:
                return 'job_priority', self._NotifyData.adwData[0]
            elif self.Field == JOB_NOTIFY_FIELD_POSITION:
                return 'job_position', self._NotifyData.adwData[0]
            elif self.Field == JOB_NOTIFY_FIELD_SUBMITTED:
                return 'job_submitted', self._data_as_datetime
            elif self.Field == JOB_NOTIFY_FIELD_PAGES_PRINTED:
                return 'job_pages_printed', self._NotifyData.adwData[0]
            elif self.Field == JOB_NOTIFY_FIELD_BYTES_PRINTED:
                return 'job_bytes_printed', self._NotifyData.adwData[0]
        # else return a copy of NotifyData
        data = self._NOTIFY_DATA.from_buffer_copy(self._NotifyData)
        if data.Data.pBuf:
            buf_t = ctypes.c_char * data.Data.cbBuf
            buf_src = buf_t.from_address(data.Data.pBuf)
            buf_cpy = buf_t.from_buffer_copy(buf_src)
            buf_ptr = ctypes.c_void_p(ctypes.addressof(buf_cpy))
            data.Data.pBuf = buf_ptr
        return (self.Type, self.Field), data

class PRINTER_NOTIFY_INFO(ctypes.Structure):
    _fields_ = (('Version', wintypes.DWORD),
                ('Flags',   wintypes.DWORD),
                ('Count',   wintypes.DWORD),
                ('_aData',  PRINTER_NOTIFY_INFO_DATA * 1))
    @property
    def aData(self):
        ptr_t = ctypes.POINTER(PRINTER_NOTIFY_INFO_DATA * self.Count)
        return ptr_t(self._aData[0])[0]

PPRINTER_NOTIFY_INFO = ctypes.POINTER(PRINTER_NOTIFY_INFO)
PPPRINTER_NOTIFY_INFO = ctypes.POINTER(PPRINTER_NOTIFY_INFO)

class PPRINTER_NOTIFY_INFO_GC(PPRINTER_NOTIFY_INFO):
    """PRINTER_NOTIFY_INFO * that Windows deallocates"""
    _type_ = PRINTER_NOTIFY_INFO
    _freed = False
    def __del__(self,
                FreePrinterNotifyInfo=winspool.FreePrinterNotifyInfo):
        if self and not self._freed:
            FreePrinterNotifyInfo(self)
            self._freed = True

def check_bool(result, func, args):
    if not result:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

def check_ihv(result, func, args):
    if result == INVALID_HANDLE_VALUE:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

def check_idv(result, func, args):
    if result == WAIT_FAILED:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

winspool.OpenPrinterW.errcheck = check_bool
winspool.OpenPrinterW.argtypes = (
    wintypes.LPWSTR,   # _In_  pPrinterName
    wintypes.LPHANDLE, # _Out_ phPrinter
    wintypes.LPVOID)   # _In_  pDefault

winspool.ClosePrinter.errcheck = check_bool
winspool.ClosePrinter.argtypes = (
    wintypes.HANDLE,) # _In_ hPrinter

winspool.FindFirstPrinterChangeNotification.errcheck = check_ihv
winspool.FindFirstPrinterChangeNotification.restype = wintypes.HANDLE
winspool.FindFirstPrinterChangeNotification.argtypes = (
    wintypes.HANDLE, # _In_ hPrinter
    wintypes.DWORD,  #      fdwFilter
    wintypes.DWORD,  #      fdwOptions
    PPRINTER_NOTIFY_OPTIONS) # _In_opt_ pPrinterNotifyOptions

winspool.FindNextPrinterChangeNotification.errcheck = check_bool
winspool.FindNextPrinterChangeNotification.argtypes = (
    wintypes.HANDLE, # _In_      hChange
    wintypes.PDWORD, # _Out_opt_ pdwChange
    PPRINTER_NOTIFY_OPTIONS, # _In_opt_  pPrinterNotifyOptions
    PPPRINTER_NOTIFY_INFO)   # _Out_opt_ ppPrinterNotifyInfo

winspool.FindClosePrinterChangeNotification.errcheck = check_bool
winspool.FindClosePrinterChangeNotification.argtypes = (
    wintypes.HANDLE,) # _In_ hChange

winspool.FreePrinterNotifyInfo.errcheck = check_bool
winspool.FreePrinterNotifyInfo.argtypes = (
    PPRINTER_NOTIFY_INFO,) # _In_ pPrinterNotifyInfo

kernel32.WaitForSingleObject.errcheck = check_idv
kernel32.WaitForSingleObject.restype = wintypes.DWORD
kernel32.WaitForSingleObject.argtypes = (
    wintypes.HANDLE, # _In_ hHandle
    wintypes.DWORD)  # _In_ dwMilliseconds

def wait_for_print_job(filter=PRINTER_CHANGE_ADD_JOB,
                       timeout=INFINITE,
                       printer_name=None):
    if timeout != INFINITE:
        timeout = int(timeout * 1000)
    hPrinter = wintypes.HANDLE()
    dwChange = wintypes.DWORD()
    winspool.OpenPrinterW(printer_name, ctypes.byref(hPrinter), None)
    try:
        hChange = winspool.FindFirstPrinterChangeNotification(
                    hPrinter, filter, 0, None)
        try:
            if (kernel32.WaitForSingleObject(hChange, timeout) !=
                WAIT_OBJECT_0): return
            winspool.FindNextPrinterChangeNotification(
                hChange, ctypes.byref(dwChange), None, None)
            return dwChange.value
        finally:
            winspool.FindClosePrinterChangeNotification(hChange)
    finally:
        winspool.ClosePrinter(hPrinter)

DEFAULT_FIELDS = (
    JOB_NOTIFY_FIELD_PRINTER_NAME,
    JOB_NOTIFY_FIELD_STATUS,
    JOB_NOTIFY_FIELD_DOCUMENT,
    JOB_NOTIFY_FIELD_PRIORITY,
    JOB_NOTIFY_FIELD_POSITION,
    JOB_NOTIFY_FIELD_SUBMITTED)

def wait_for_print_job_info(fields=DEFAULT_FIELDS,
                            timeout=INFINITE,
                            printer_name=None):
    if timeout != INFINITE:
        timeout = int(timeout * 1000)
    hPrinter = wintypes.HANDLE()
    fields = (wintypes.WORD * len(fields))(*fields)
    opt = PRINTER_NOTIFY_OPTIONS(
            pTypes=PRINTER_NOTIFY_OPTIONS_TYPE(
                    Type=JOB_NOTIFY_TYPE, pFields=fields))
    pinfo = PPRINTER_NOTIFY_INFO_GC() # note: GC subclass
    result = []
    winspool.OpenPrinterW(printer_name, ctypes.byref(hPrinter), None)
    try:
        hChange = winspool.FindFirstPrinterChangeNotification(
                    hPrinter, 0, 0, ctypes.byref(opt))
        try:
            if (kernel32.WaitForSingleObject(hChange, timeout) !=
                WAIT_OBJECT_0): return result
            winspool.FindNextPrinterChangeNotification(
                hChange, None, None, ctypes.byref(pinfo))
            for data in pinfo[0].aData:
                if data.Type != JOB_NOTIFY_TYPE:
                    continue
                nd = (data.Id,) + data.NotifyData
                result.append(nd)
            return result
        finally:
            winspool.FindClosePrinterChangeNotification(hChange)
    finally:
        winspool.ClosePrinter(hPrinter)

def job_status_string(status, nfmt='%#010x'):
    if status == 0:
        return nfmt % 0
    strings = []
    for state, string in JOB_STATUS_STRING.items():
        if status & state:
            strings.append(string)
            status &= ~state
            if not status:
                break
    if status:
        strings.append(nfmt % status)
    return ','.join(strings)

rawDescription: How to catch printer event in python

description: Catch printer event in python


code:
from collections import OrderedDict

[i for i in OrderedDict.fromkeys(b) for _ in range(min(b.count(i), a.count(i)))]

rawDescription: How do I target a particular element in two lists separately? How do I pick an arbitrary number of an element occurring many times in a list?

description: Target a particular element in two lists separately? How do I pick an arbitrary number of an element occurring many times in a list


code:
import copy
# make your initialization
initial_variable = copy.copy(variable)

rawDescription: How to restart a program?

description: Restart a program


rawDescription: Unicode Characters in Twitter (Python)

description: Unicode Characters in Twitter (Python)


code:
class test(object):
    __slots__ = ['a', 'next']

x = test()
x.next = x
x.a = 42

rawDescription: C struct python equivalent

description: C struct python equivalent


code: u'Eixample, an inner suburb of Barcelona with distinctive architecture'

rawDescription: duckduckgo API not returning results

description: Duckduckgo API not returning results


code: random.sample(word_drills, 3)

rawDescription: Pull random keys from dictionary in Python that are not equal to one another


code:
from typing import get_type_hints

def strict_types(function):
    def type_checker(*args, **kwargs):
        hints = get_type_hints(function)

        all_args = kwargs.copy()
        all_args.update(dict(zip(function.__code__.co_varnames, args)))

        for argument, argument_type in ((i, type(j)) for i, j in all_args.items()):
            if argument in hints:
                if not issubclass(argument_type, hints[argument]):
                    raise TypeError('Type of {} is {} and not {}'.format(argument, argument_type, hints[argument]))

        result = function(*args, **kwargs)

        if 'return' in hints:
            if type(result) != hints['return']:
                raise TypeError('Type of result is {} and not {}'.format(type(result), hints['return']))

        return result

    return type_checker

rawDescription: python 3.5 type hints: can i check if function arguments match type hints?

description: Python 3.5 type hints: can i check if function arguments match type hints


code:
for name, score in top_10_pairs:
    print('{} {}'.format(name, score))

rawDescription: parsing a file so as to get the top 10 players.

description: Parsing a file so as to get the top 10 players.


code: df.loc[df.ID == 103, ['FirstName', 'LastName']] = 'Matt', 'Jones'

rawDescription: Python PANDAS, change one value based on another value


rawDescription: Polygon or free-form shape drawing with OpenCV Python


code:
def search_file(directory = None, file = None):
    assert os.path.isdir(directory)
    for cur_path, directories, files in os.walk(directory):
        if file in files:
            return os.path.join(directory, cur_path, file)
    return None

rawDescription: Do I understand os.walk right?

description: Do I understand os.walk right


code: (f(x) + sin(x)).atoms(Function)

rawDescription: Sympy: Get functions from expression

description: Sympy: Get functions from expression


code:
def find_words_and_remove(words, strings):
    return [" ".join(word for word in string.split() if word not in words) for string in strings]

rawDescription: Erasing list of phrases from list of texts in python


code: logger = logging.getLogger(__name__)

rawDescription: Why does logging seem to require a handler in each module in order to print to console?


code: len(passes['Messi'])

rawDescription: Python Data Structure Selection

description: Python Data Structure Selection


code:
import dateutil

df = DataFrame ({
    "schedule" :
    Series ([
        "2012-12-31",
        "2013-01-01",
        "2013-09-27",
        "2014-04-06"
    ]).apply(dateutil.parser.parse)
})
df["year"] = df["schedule"].apply (lambda x : x.year if x.month < 9 else x.year + 1)
df

rawDescription: Pandas: Extracting just the Calendar Year from Datetime column


rawDescription: In Pandas How to sort one level of a multi-index based on the values of a column, while maintaining the grouping of the other level


code:
import lxml.etree as ET
import io

content='''\
<?xml version="1.0" encoding="UTF-8"?>
<locales>
<api-url>url</api-url>
<locale>
    <market>AE</market>
    <languages>
        <language>ar</language>
    </languages>
</locale>
<locale>
    <market>AM</market>
    <languages>
        <language>hy</language>
        <language>ru</language>
    </languages>
</locale>
</locales>
'''
inputXml=ET.parse(io.BytesIO(content))

for locale in inputXml.xpath('//locale'):
    market = locale.xpath('market/text()')[0]
    for lang in locale.xpath('languages/language/text()'):
        print('{m}_{l}'.format(m=market,l=lang))

rawDescription: Concatenate values in a list (XML,Python)


code: from pandas_datareader import data as web

rawDescription: Pandas DataFrame not working as intended


code:
for d in mylist:
    for k in d.keys():
        sum_dict[k] += d[k]

rawDescription: Sum of values in list of dictionaries

description: Sum of values in list of dictionaries


code: ways[i]+=ways[i-coin]

rawDescription: Understanding change-making algorithm

description: Understanding change-making algorithm


code: first3 = numpy.dstack(firstmatrices)

rawDescription: Merging a list of numpy arrays into one array (fast)


code:
import bisect
def rank3(x,y,z, ascending=True):
    if x <= y:
        ret = [x, y]
    else:
        ret = [y, x]
    pz = bisect.bisect(ret, z)
    ret.insert(pz, z)
    if not ascending:
        ret = ret[::-1] # or use ret.reverse()
    return tuple(ret)

rawDescription: How to put numbers in ascending, return them in a tuple, and add another argument.(Python)

description: Put numbers in ascending, return them in a tuple, and add another argument.(Python)


code:
obj = unique_ranked_collection()
isinstance(obj, non_unique_ranked_collection)

rawDescription: Forcing compatibility of inherited types (Python)


code:
import textwrap

List = [
    ["A1", "Some text that you want to write to a file, aligned in\n a column."],
    ["A2", "And this is a shorter text."]]

indention = 30
max_line_length = 30

file=open("tmp.txt", 'w')
for i in range(len(List)):

    out = List[i][0].ljust(indention, ' ')
    cur_indent = 0
    for line in List[i][1].split('\n'):
        for short_line in textwrap.wrap(line, max_line_length):
            out += ' '* cur_indent + short_line.lstrip() + "\n"
            cur_indent = indention

    file.write(out)

rawDescription: How to align columns when printing on a file in Python

description: Align columns when printing on a file in Python


code:
import uuid
suffix = str(uuid.uuid4()).replace('-','') # remove '-' so we have a valid identifier
a_name = "a_" + suffix
c_name = "c_" + suffix
mec.scatter(a_name, b)
mec.execute("%s = fun(%s)" % (c_name, a_name))
d = mec.gather(c_name)

rawDescription: Synchronization issue in IPython parallel computing


code: from django.db import models

rawDescription: How to move a model between two Django apps (Django 1.7)

description: Move a model between two Django apps (Django 1.7)


code:
def foo():
    funcstr=(
        'def func(x, {p}):\n'
        '    return x * 2*a + 4*b - 5*c'
        )

rawDescription: Dynamically define a function

description: Dynamically define a function


code:
def split(row):
    ret = some_computation(row, split.previous)
    split.previous = row
    return ret
split.previous = None

rawDescription: Python dictionary merge values and delete previous


code:
def dict_freeze(d):
    # This is the trivial one-line function
    # It assumes the values are of immutable types, i.e. no lists.
    # It unpacks dict items, sorts and converts to tuple
    # sorting isn't strictly necessary, but dictionaries don't preserve order
    #   thus we could end up with the following:
    #   d = {'a': 1, 'b': 2} could get frozen as either of the following
    #   (('a', 1), ('b', 2)) != (('b', 2), ('a', 1))
    return tuple(sorted(d.items()))

frozen_d = dict_freeze(d)
print(frozen_d)
# prints
(('blue', (2, 4)), ('red', (1,)), ('yellow', (1, 3)))

rawDescription: Make an object immutable

description: Make an object immutable


code:
from numpy import arange, sin
t = arange(5)
t
y = sin(t)
y

rawDescription: Numpy Arrays: Slice y-values array based on threshold, then slice the x-values array correspondingly


rawDescription: Clear cookies from Requests Python

description: Clear cookies from Requests Python


code:
generatedClass = superClassCreator()
globals()[generatedClass.__name__] = generatedClass
del generatedClass

rawDescription: python how to register dynamic class in module

description: Python how to register dynamic class in module


code:
from django.contrib import admin
from models import *

def delete_selected(modeladmin, request, queryset):
    for element in queryset:
        element.delete()
delete_selected.short_description = "Delete selected elements"

class FileAdmin(admin.ModelAdmin):
    model = File
    actions = [delete_selected]

    list_display = ('title', 'file_type')

admin.site.register(File, FileAdmin)

rawDescription: Removing a file from the server once the entry has been removed


code:
import pygame,random
from pygame.locals import *

xmax = 1000    #width of window
ymax = 600     #height of window

class Particle():
    def __init__(self, startx, starty, col):
        self.x = startx
        self.y = random.randint(0, starty)
        self.col = col
        self.sx = startx
        self.sy = starty

    def move(self):
        if self.y < 0:
            self.x=self.sx
            self.y=self.sy

        else:
            self.y-=1

        self.x+=random.randint(-2, 2)

def main():
    pygame.init()
    screen = pygame.display.set_mode((xmax,ymax))
    white = (255, 255, 255)
    black = (0,0,0)
    grey = (128,128,128)

    clock=pygame.time.Clock()

    particles = []
    for part in range(300):
        if part % 2 > 0: col = black
        else: col = grey
        particles.append( Particle(515, 500, col) )

    exitflag = False
    while not exitflag:
        for event in pygame.event.get():
            if event.type == QUIT:
                exitflag = True
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    exitflag = True

        screen.fill(white)
        for p in particles:
            p.move()
            pygame.draw.circle(screen, p.col, (p.x, p.y), 2)

        pygame.display.flip()
        clock.tick(50)
    pygame.quit()

if __name__ == "__main__":
    main()

rawDescription: Pygame particle effects

description: Pygame particle effects


code:
def nearest_neighbors(x, y) :
    x, y = map(np.asarray, (x, y))
    y = y.copy()
    y_idx = np.arange(len(y))
    nearest_neighbor = np.empty((len(x),), dtype=np.intp)
    for j, xj in enumerate(x) :
        idx = np.argmin(np.abs(y - xj))
        nearest_neighbor[j] = y_idx[idx]
        y = np.delete(y, idx)
        y_idx = np.delete(y_idx, idx)

    return nearest_neighbor

rawDescription: finding nearest items across two lists/arrays in Python

description: Finding nearest items across two lists/arrays in Python


code:
from itertools import chain
example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['', 'gg']]
'' in chain.from_iterable(example_list)

rawDescription: Best way to check if an item is present in a list of lists?

description: Check if an item is present in a list of lists


code:
tf = tempfile.NamedTemporaryFile(prefix="zz")
tf.name

rawDescription: Best way to generate random file names in Python

description: Generate random file names in Python


code: [u'py:attribute', u'std:label', u'py:method', u'py:function', u'py:class']

rawDescription: How to properly write coss-references to external documentation with intersphinx?

description: Properly write coss-references to external documentation with intersphinx


rawDescription: How to view the instance variables of a class

description: View the instance variables of a class


rawDescription: python numpy array slicing

description: Python numpy array slicing


code:
def getWordForm(phone_num):
    words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
             'eight', 'nine']
    result = ''
    for ch in phone_num:
        if ch.isnumeric():
            result += words[int(ch)] + ' '
        else:
            result += ch + ' '
    return result[:-1]

rawDescription: Python - changing a 10 digit phone # to words with a list #Simplicity


code: answer = Questions()

rawDescription: Tkinter Math Quiz

description: Tkinter Math Quiz


code:
class push_to_advance(object):
    def __init__(self):
        self.fig = plt.figure()
        self.ax = self.fig.gca()
        self.bound_keys = []
        self.bound_cid = {}

    def add_step_through(self, gen, key):
        key = key[0] # make a single char
        if key in self.bound_keys:
            raise RuntimeError("key %s already bound"%key)
        first_data = gen.next()
        self.ax.plot(first_data)
        self.fig.canvas.draw()
        self.bound_keys.append(key)
        def ontype(event):
            if event.key == key:
                try:
                    self.ax.plot(gen.next())
                    self.fig.canvas.draw()
                except StopIteration:
                    self.fig.canvas.mpl_disconnect(self.bound_cid[key])
                    del self.bound_cid[key]
                    self.bound_keys.remove(key)

        self.bound_cid[key] = self.fig.canvas.mpl_connect('key_press_event', ontype)

rawDescription: Using events with matplotlib in a for loop


code:
import numpy as np
x = np.random.random(10)
y = np.random.random(10)
zip(x,y)
data = np.array( zip(x,y), dtype=[('x',float),('y',float)])
data['x']
data['y']
data[0]

rawDescription: Is there a standard way to store XY data in python?


code:
def classname(self):
    # can't access attributes that start with _  in a template
    return self.__class__.__name__

rawDescription: django-model-utils, inheritance and templates

description: Django-model-utils, inheritance and templates


code:
D = DATA({'temperature': 102, 'appVersion': '1.0.4'})
D

rawDescription: python 2.7 defining a class that will show their attributes if called with no arguments

description: Python 2.7 defining a class that will show their attributes if called with no arguments


code:
def myExample(**kwargs):
    if kwargs.get("width") and kwargs.get("w"):
        cmds.error("same flag used two times")
    else:
        myWidth = kwargs.get("width") or kwargs.get("w") or "nothing"
    print(myWidth)

myExample(width=200)

rawDescription: Aliasing in the names of function arguments (double naming)


rawDescription: Django. i18N reverse url Issue

description: Django. i18N reverse url Issue


code:
import re
from collections import defaultdict

files = ['s1.txt', 'ai1.txt', 's2.txt', 'ai3.txt']

def get_key(fname):
   return int(re.findall(r'\d+', fname)[0])

d = defaultdict(list)
for f in files:
   d[get_key(f)].append(f)

out = [d[k] for k in sorted(d.keys())]
print(out)

rawDescription: Sorting files in a list

description: Sorting files in a list


rawDescription: Can I get first derivative for kernel density estimation in python?

description: Get first derivative for kernel density estimation in python


code: longer_words_count = sum(1 for word in sentence.split() if len(word) >= 4)

rawDescription: Count each list element with min 4 chars


rawDescription: Print everything right of ":" at the same width


code:
class PointProperty(object):
    def __init__(self, x, y):
        ''' x and y are the names of the coordinate attributes '''
        self.x = x
        self.y = y

    def __set__(self, instance, value):
        assert type(value) == Point
        setattr(instance, self.x, value.x)
        setattr(instance, self.y, value.y)

    def __get__(self, instance, owner):
        if instance is not None:
            return Point(x=getattr(instance, self.x),
                         y=getattr(instance, self.y))
        else: # called on the Class
            return PointColumnProxy(getattr(owner, self.x),
                                    getattr(owner, self.y))

rawDescription: storing list/tuples in sqlite database with sqlalchemy

description: Storing list/tuples in sqlite database with sqlalchemy


code:
B.my_attr = 'bar'
B.my_attr
A.my_attr

rawDescription: python - class instance variable inherence and class variable inherence

description: Python - class instance variable inherence and class variable inherence


code:
class Reversable(object):
    def __init__(self, seq):
        self.seq = seq
    def __len__(self):
        return len(self.seq)
    def __getitem__(self, item):
        return self.seq[item]
    def __reversed__(self):
        for elem in 'Reversing: ' + self.seq[::-1]:
            yield elem

r = Reversable('Foo bar baz!')
list(r)
list(reversed(r))

rawDescription: Python __reverse__ magic method

description: Python __reverse__ magic method


code:
holiday_tuple = (datetime.date(2015, 3, 1), 'some description')
print("{:%d/%m} {}".format(*holiday_tuple))

rawDescription: Using .format() with tuples instead of dictionaries


rawDescription: How to define a mathematical function in SymPy?

description: Define a mathematical function in SymPy


code: known(edits1(word)) or known_edits2(word) or [word]

rawDescription: Norvig's spell checker, how he implements the conditional probability?


code:
import logging

MYVAR = 'Jabberwocky'

class ContextFilter(logging.Filter):
    """
    This is a filter which injects contextual information into the log.
    """
    def filter(self, record):
        record.MYVAR = MYVAR
        return True

FORMAT = '%(MYVAR)s %(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT, datefmt='%d/%m/%Y %H:%M:%S')

logger = logging.getLogger(__name__)
logger.addFilter(ContextFilter())

logger.warning("'Twas brillig, and the slithy toves")

rawDescription: How to input variables in logger formatter?

description: Input variables in logger formatter


rawDescription: Printing Binary in Python

description: Printing Binary in Python


code:
import numpy as np
diff = df['Open'].diff()
conditions = [diff > 0, diff < 0]
choices = [1, 0]
df['increasing'] = np.select(conditions, choices, default=2)

rawDescription: New colum in pandas, based on another colums last value


code:
old_stdout = sys.stdout
sys.stdout = open("log.txt","w") # now calling print will write to this logfile
results = []
T1, T2 = time.time(), time.time()
while T2 - T1 < 1 * 60 * 60:
    results.append( func() )
    T2 = time.time()
    old_stdout.write("%0.2f%% Complete\n"%(100.0*(T2-T2)/(1.0*60*60)))

rawDescription: Dynamic Output of time progression

description: Dynamic Output of time progression


code:
def rstrip_chars(s, chars):
    return s[:-len(chars)] if s.endswith(chars) else s

s = rstrip_chars(s, '000000')

rawDescription: how to trim n characters of string in python?

description: Trim n characters of string in python


code:
from types import MethodType

def foo(instance):
    # this function will receive the instance as first argument
    # similar to a bound method
    pass

instance.foo = MethodType(foo, instance, instance.__class__)

rawDescription: Adding a method to a class within a class


code:
cum_defaults = cum_defaults.reindex(index=range(min(cum_defaults.index),
                                                max(cum_defaults.index) + 1),
                                    method='ffill')

rawDescription: Create a time series from data

description: Create a time series from data


rawDescription: Beautiful Soup HTML Extraction

description: Beautiful Soup HTML Extraction


code: df.loc[update_idx, 'new_col'] = new_value

rawDescription: Vectorized update to pandas DataFrame?

description: Vectorized update to pandas DataFrame


rawDescription: 2D Histogram out of array data set

description: 2D Histogram out of array data set


code:
myapp/models.py
from django.db import models

class A(models.Model):
    export_date = models.DateField()

    def __unicode__(self):
        return "date: {0}".format(self.export_date)

class B(models.Model):
    name = models.CharField(max_length=255)
    color = models.CharField(max_length=255)
    weight = models.CharField(max_length=255)
    a = models.ForeignKey(A)

    def __unicode__(self):
        return "name: {0}, color: {1}, weight: {2}".format(self.name,
                                                           self.color,
                                                           self.weight)

class C(models.Model):
    taste = models.CharField(max_length=255)
    smell = models.CharField(max_length=255)
    a = models.ForeignKey(A)

    def __unicode__(self):
        return "taste: {0}, smell: {1}".format(self.taste, self.smell)

rawDescription: Joining multiple tables for a single report in Django


code:
def freq_threshold(n):
    return [(char, tally[char]) for char in tally if tally[char] > n]

rawDescription: What is my function missing? (python)

description: What is my function missing? (python)


code:
import scrapy
from furiousme.items import FuriousmeItem

class FuriousSpider(scrapy.Spider):
    name = "furious"

    def __init__(self, domain, start_url, thelist_id):
        self.allowed_domains = [domain]
        self.start_urls = [start_url]
        self.thelist_id = thelist_id  # this receives the argument

    def parse(self, response):
        for href in response.css("a::attr('href')"):
            url = response.urljoin(href.extract())
            yield scrapy.Request(url, callback=self.parse_dir_contents)

    def parse_dir_contents(self, response):
        for sel in response.xpath("//body//a"):
            item = FuriousmeItem()
            item['emails'] = response.xpath("//a[starts-with(@href, 'mailto')]/text()").extract()
            item['entity_id'] = self.thelist_id # this stores the argument
            yield item

rawDescription: Scrapy Passing Arguments and Writing to MySQL


rawDescription: Pointfree function combination in Python


code:
file_output = []
with open(valid_pfile, 'r') as f:
    for line in f.readlines()[1:]: # ignoring the first line which is header
       file_output.append([v.split() for v in line.split(',')])

rawDescription: Iterate through a file and process it

description: Iterate through a file and process it


code:
from selenium import webdriver
import time

chromedriver = "./chromedriver"
browser = webdriver.Chrome(executable_path = chromedriver)

browser.get('http://anubiann00b.github.io/FocusTest/')

while True:
    browser.execute_script("window.onfocus()")
    time.sleep(1)
    browser.execute_script("window.onblur()")
    time.sleep(1)

rawDescription: Feign focus in Selenium chrome browser

description: Feign focus in Selenium chrome browser


code:
headers = table.find('tr', class_="yfnc_modtitle1").find_all('th')
revenue = table.tr.td.table.tr.next_sibling.td.next_siblings

with open('/home/kwal0203/Desktop/Apple.csv', 'a') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow([value.get_text(strip=True).encode("utf-8") for value in headers])
    writer.writerow([value.get_text(strip=True).encode("utf-8") for value in revenue])

rawDescription: How to write output of web scrape to column instead of rows in Beautiful Soup

description: Write output of web scrape to column instead of rows in Beautiful Soup


code:
import imp
packages = imp.load_source('packages', '/path/to/packages.py')

rawDescription: Python -- import a module from a directory that's not a package


code:
import numpy as np
np.random.seed(1)

# Each array with have 5 random points
x, y, z = np.random.random((3, 5))

# A is going to look like:
#  |1  x1  x1^2  y1  y1^2|
#  |1  x2  x2^2  y2  y2^2|
#  |1  x3  x3^2  y3  y3^2|
#  |1  x4  x4^2  y4  y4^2|
#  |1  x5  x5^2  y5  y5^2|
A = np.column_stack([np.ones(len(x)), x, x**2, y, y**2])

# And "B" will just be our "z" array
B = z

# Now we can solve the system of equations Ax = B
a, b, c, d, e = np.linalg.solve(A, B)

rawDescription: Fit data to curve using polyfit with multiple variables in python using numpy polyfit


code:
def addTags(functionHere):
    def wrapper(firstValue, secondValue):
        return "NumberTag" + functionHere(firstValue, secondValue) + "NumberTagOver"
    return wrapper

rawDescription: Decorators in Python

description: Decorators in Python


code: [xs for xs in a if not any(math.isnan(x) for x in xs)]

rawDescription: How to delete [NaN] from a list of lists?

description: Delete [NaN] from a list of lists


rawDescription: python count list item occurences and put result in list

description: Python count list item occurences and put result in list


code:
my_instance = MyModel(**my_dict)
#add any customization for the new instance here
my_instance.save()

rawDescription: How do I "pickle" instances of Django models in a database into sample python code I can use to load sample data?


code:
#!/usr/bin/env python

from distutils.core import setup

setup(name='myapp',
      version='1.0',
      description='This is a cool webapp by Syrahn.',
      author='Syrahn',
      requires=['googleappengine','nosetests',], #etc
     )

rawDescription: GAE on linux CI server

description: GAE on linux CI server


code:
diff_grid = [''.join(i) for i in zip(*grid[::-1])]
diff_grid

rawDescription: I want to format my list differently

description: I want to format my list differently


code:
import re
test = "WEB-INF/library/JARFILE-45.33.jar:/properties/somefile.property"
sub = r"WEB-INF/library/JARFILE-[a-zA-Z0-9]+\.[a-zA-Z0-9]+\.jar:/properties/somefile\.property"
print(re.match(sub, test))

rawDescription: Python : To list files if my keyword contains using regular expression


code:
import csv

in_1_name = "/home/julien/input.csv"
in_2_name = "/home/julien/excel/output.csv"
out_name = "/home/julien/excel/merged.csv"

with open(in_1_name) as in_1, open(in_2_name) as in_2, open(out_name, 'w') as out:
    reader1 = csv.reader(in_1, delimiter=";")
    reader2 = csv.reader(in_2, delimiter=";")
    writer = csv.writer(out, delimiter=";")
    for row1, row2 in zip(reader1, reader2):
        if row1[0] and row2[0]:
            writer.writerow([row1[0], row2[0]])

rawDescription: Add a column from a csv to another csv

description: Add a column from a csv to another csv


code:
result = []
row2 = []
while curr_row < numOfRows:
   curr_row += 1
   row2 = []
   row = worksheet.row(curr_row)
   for value2 in re.findall(r"'(.*?)'", str(row)):
        row2.append(value2)
   result.append(row2)
return result

rawDescription: return Set of lists from out of function: python

description: Return Set of lists from out of function: python


rawDescription: Create column relative to other values in same column (time since last transaction) Pandas


code:
found = False
for i, student in enumerate(name_list):
    if student.name == del_name:
        found = i
if found != False:
    del name_list[found]
    print("Deleted...")
else:
    print("Could not find name %s" % (del_name,))

rawDescription: deleting a name from a list input by user and averaging a class score

description: Deleting a name from a list input by user and averaging a class score


code:
lst = [1,100,10]
sorted(lst) #returns sorted list
lst #is still the same
lst.sort() #returns nothing
lst #has updated

rawDescription: making a string into a list within a list comprehension

description: Making a string into a list within a list comprehension


code: im = ax.pcolor(data, cmap=cm.gray, edgecolors='white', linewidths=1)

rawDescription: Matplotlib grayscale heatmap with visually distinct "NA" squares fields


code:
howManyX = int(raw_input('Input number of x-values for this graph: '))

x_col_nums = [1] * 6
for i in range(howManyX):
    x_col_nums[i] = int(raw_input("Input column number for x%d-value: " % (i + 1)))

rawDescription: Condensing Large Unpythony if statement

description: Condensing Large Unpythony if statement


code:
import os, fnmatch

def find_files(directory, pattern):
    for root, dirs, files in os.walk(directory):
        for basename in files:
            if fnmatch.fnmatch(basename, pattern):
                filename = os.path.join(root, basename)

                yield filename

rawDescription: Moving into a directory without knowing its name


code:
from collections import namedtuple

Transaction = namedtuple("Transaction", ["account", "amount"])

rawDescription: Objects With No Behavior

description: Objects With No Behavior


code:
a = np.arange(25).reshape((5,5))
a
rows = b = np.array([0,4,2,3,3])
cols = np.arange(len(b))
[a[b[i], i] for i in range(5)]
a[rows, cols]

rawDescription: Using fancy indexing to get one value from each column of a numpy matrix


code:
y = 10
for i in range(0,10):
    for j in range(0, i):
        print(y + j, end=' ')
    print('')
    y += i

rawDescription: Creating a number list with nested For loops in Python


code:
res = df.pop("A").str.get_dummies()  # Note: pop removes column A from df
res.columns = res.columns.map(lambda x: "A_" + x)
res
res.join(df)

rawDescription: How to make a binary decomposition of pandas.Series column

description: Make a binary decomposition of pandas.Series column


code: X - np.dot( A, B )

rawDescription: NumPy Matrix Multiplication Efficiency for Matrix With Known Structure


code:
import pandas as pd
import pandas_datareader.data as web
import datetime
import numpy as np

currentTime = datetime.datetime.now().date()
df = web.DataReader('goog','yahoo', start='2016-5-1',end='2016-5-15')

ma_3 = pd.rolling_mean(df, window=3)

print(ma_3)

rawDescription: Rolling mean, returning nan in dataframe pandas python


code:
first = data[0]
for i, val in enumerate(data[1:]):
    if val < first:
        data[i] += 1
        break
else:
    data[0] += 1

rawDescription: Python 3.4.1 Find different keep the same


code:
with open('your.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile)
    # write your header first
    for obj in YourModel.objects.all():
        row = ""
        for field in fields:
             row += getattr(obj, field.name) + ","
        writer.writerow(row)

rawDescription: Exporting items from a model to CSV Django / Python


code:
fig, ax = plt.subplots()

l1, = ax.plot(x,y, 'k', label='l1')
leg1 = plt.legend([l1],['l1'])

l2, = ax.plot(x,y, 'k', label='l2')
leg2 = plt.legend([l2],['l2'])

ax.add_artist(leg1)

print(ax.get_children())

rawDescription: How to get all legends from a plot?

description: Get all legends from a plot


code:
with capture_stdout_unicode() as out:
    api_call_that_prints()

logger.info(out.getvalue())

rawDescription: UnicodeEncodeError when printing from Django


code:
while True:
    n = int(input('How many trials?')) # raw_input for Python 2.x
    simul(n)

rawDescription: Simulate several rounds of rock, paper and scissors


code:
s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")

rawDescription: Are there other ways to format strings other then comma, percent, plus sign?


rawDescription: reassigning row/list in a 2d list in python

description: Reassigning row/list in a 2d list in python


code:
class B():
    def __init__(self, c, a):
        self.c = c
        self.a = a
    def getA(self):
        return self.a

class A():
    def __init__(self, d):
        self.b = B(d, self)

a = A(d)

rawDescription: how to get the object from its attribute in python?

description: Get the object from its attribute in python


rawDescription: Storing and analysing experimental data in efficient way (SQL, PYTHON)


code:
ax.set_ylim3d(-1, 31)
ax.set_xlim3d(-1, 21)

rawDescription: Removing axes margins in 3D plot

description: Removing axes margins in 3D plot


code:
from my_app.models import MyModel

mms = MyModel.objects.all()

rawDescription: What is a "Manager" in django?

description: What is a "Manager" in django


code:
class MyCustomForm(forms.Form):
    records= forms.ModelMultipleChoiceField(queryset=Record.objects.all, widget=forms.CheckboxSelectMultiple)

rawDescription: How do I create / access dynamic form fields in Django from within a View?

description: Create / access dynamic form fields in Django from within a View


code:
from django.shortcuts import render
from templated_email import send_templated_mail

@login_required
def verFactura(request, id_factura):
    fact = Factura.objects.get(pk = id_factura)
    cliente = Cliente.objects.get(factura = fact)
    template = 'verfacturas.html'
    iva = fact.importe_sin_iva * 0.21
    total = fact.importe_sin_iva + iva

    extra_context = dict()
    extra_context['fact'] = fact
    extra_context['cliente'] = cliente
    extra_context['iva'] = iva
    extra_context['total'] = total

    # Send the email
    send_templated_mail(template_name='receipt',
                        from_email='robot@server.com',
                        recipient_list=[request.user.email],
                        context=extra_context)

    return render(request, template, extra_context)

rawDescription: Send_email in django with data from a view as an HTML page


code: ax2.plot(ax.get_xticks(),df[['sales_gr','net_pft_gr']].values, linestyle='-', marker='o', linewidth=2.0)

rawDescription: How to align the bar and line in matplotlib two y-axes chart?

description: Align the bar and line in matplotlib two y-axes chart


code: srted  = sorted(list1) # creates a new list

rawDescription: How to sort a list from user input?

description: Sort a list from user input


rawDescription: Don't want show all items of a model object in django


rawDescription: How to get a padded slice of a multidimensional array?

description: Get a padded slice of a multidimensional array


code:
import itertools
l =  [2, 2, 3, 4, 6, 9, 14, 22, 35, 56, 90]
s = set()
for i in range(len(l)):
    for comb in itertools.combinations(l, i+1):
        s.add(sum(list(comb)))
sorted(s)

rawDescription: How can I count up by one by using or adding various numbers in a list?

description: Count up by one by using or adding various numbers in a list


rawDescription: Elegant way to slice a list with a condition


code:
g = sns.FacetGrid(tips, col="sex", row="smoker", sharex=False)

def ordered_barplot(data, **kws):
    x_order = data.day.value_counts().order().index[-2:]
    sns.barplot(data.day, x_order=x_order)

g.map_dataframe(ordered_barplot)

rawDescription: seaborn FacetGrid , ranked barplot separated on row and col

description: Seaborn FacetGrid , ranked barplot separated on row and col


code: os.write(out, 'xxxx')

rawDescription: python interprocess querying/control

description: Python interprocess querying/control


code:
class A(metaclass=B if use_metaclass else type):
    pass

rawDescription: Using a metaclass depending on configuration


code: re.findall(r'<.+?>', text)

rawDescription: How to eliminate html tags?

description: Eliminate html tags


code:
print(file.read())
file.seek(0, os.SEEK_SET)
for line in file:
    ...

rawDescription: Why is the command line file not getting the lines?


code: self.v = IntVar()

rawDescription: how to connect to mysql database from gui made in python

description: Connect to mysql database from gui made in python


code:
def dict_of_max(d):
    return {k:max(v) for k, v in d.items()}

rawDescription: How do you sort a list which is inside a dictionary?

description: Sort a list which is inside a dictionary


code:
for path in filepath:
  dirname, filename = os.path.split(path)
  print(filename[0:-19])
  var1 = filename
  var2 = filename[0:-25]

rawDescription: Looking to assign print output (string) to a variable


code:
def process_requests(q):
    while True:
        request = q.get()
        # do your magic with 'request'
        ...

rawDescription: Gevent async server with blocking requests


code:
delta = maximum - minimum
factor = 10**math.ceil(math.log(delta,10))  # smallest power of 10 greater than delta
normalised_delta = delta / factor           # 0.1 <= normalised_delta < 1
if normalised_delta/5 >= 0.1:
  step_size = 0.1
elif normalised_delta/5 >= 0.05:
  step_size = 0.05
elif normalised_delta/20 <= 0.01:
  step_size = 0.01
step_size = step_size * factor

rawDescription: Ticking function grapher

description: Ticking function grapher


code:
marker = ";!$%^&;"
[r.replace(marker[1:-1],'') for r in PATTERN.split("aaa;;aaa;'b;;b'".replace(';;', marker))[1::2]]

rawDescription: How to split but ignore separators in quoted strings, in python?

description: Split but ignore separators in quoted strings, in python


rawDescription: What's the Pythonic way to implement "diamond inheritance"?


code:
import os
import sys
import warnings
import time
import socket
import re
import urllib2
import types
import SocketServer
import threading
import tempfile
import zipfile
import pickle
import glob #for directory scanning
import abc #abstract base class
import colorsys
import logging
import pygame as pg
import scipy.ndimage as ndimage
import scipy.stats.stats as sss  #for auto white balance
import scipy.cluster.vq as scv
import scipy.linalg as nla  # for linear algebra / least squares
import math # math... who does that
import copy # for deep copy
import numpy as np
import scipy.spatial.distance as spsd
import scipy.cluster.vq as cluster #for kmeans
import pygame as pg
import platform
import copy
import types
import time

from numpy import linspace
from scipy.interpolate import UnivariateSpline
from warnings import warn
from copy import copy
from math import *
from pkg_resources import load_entry_point
from SimpleHTTPServer import SimpleHTTPRequestHandler
from types import IntType, LongType, FloatType, InstanceType
from cStringIO import StringIO
from numpy import int32
from numpy import uint8
from EXIF import *
from pygame import gfxdraw
from pickle import *

rawDescription: SimpleCV Code Completion with Eclipse

description: SimpleCV Code Completion with Eclipse


code:
eli = enumerate(li)
i = eli.next()
i[0]
i[1]

list(enumerate(li))

rawDescription: scatter plot python with several y values

description: Scatter plot python with several y values


code:
reader = csv.csvreader(csvfile)
converters = [datetime, float, int, float]
result = np.array([[conv(col) for col, conv in zip(row, converters)]
    for row in reader])
# BTW, column headings are in reader.fieldnames at this point.

rawDescription: Reading CSV files in numpy where delimiter is ","


code:
from django.core.cache import cache
from django.db.models.signals import post_save
from myapp.models import MyModel

def kill_object_cache(sender, **kwargs):
    cache.delete('some_key')

post_save.connect(kill_object_cache, sender=MyModel)
post_delete.connect(kill_object_cache, sender=MyModel)

rawDescription: Models in database speed vs static dictionaries speed


code: assert np.all(rdd.first()[1] == np.arange(100))

rawDescription: repartition a dense matrix in pyspark

description: Repartition a dense matrix in pyspark


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

# Define a graph
G = nx.Graph()
G.add_edges_from([(1,2,{'weight':10, 'val':0.1}),
                  (1,4,{'weight':30, 'val':0.3}),
                  (2,3,{'weight':50, 'val':0.5}),
                  (2,4,{'weight':60, 'val':0.6}),
                  (3,4,{'weight':80, 'val':0.8})])
# generate positions for the nodes
pos = nx.spring_layout(G, weight=None)

# create the dictionary with the formatted labels
edge_labels = {i[0:2]:'${}'.format(i[2]['weight']) for i in G.edges(data=True)}

# create some longer node labels
node_labels = {n:"this is node {}".format(n) for n in range(1,5)}

# draw the graph
nx.draw_networkx(G, pos=pos, with_labels=False)

# draw the custom node labels
shifted_pos = {k:[v[0],v[1]+.04] for k,v in pos.iteritems()}
node_label_handles = nx.draw_networkx_labels(G, pos=shifted_pos,
        labels=node_labels)

# add a white bounding box behind the node labels
[label.set_bbox(dict(facecolor='white', edgecolor='none')) for label in
        node_label_handles.values()]

# add the custom egde labels
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)

plt.show()

rawDescription: Making networkx plot where edges only display edited numeric value, not field name


code:
with open('your_file', 'rb') as f:
    data = f.read()
print(len(data))

rawDescription: Reading file stops at halfway

description: Reading file stops at halfway


code: copy_of_A = A[:]

rawDescription: Python list help

description: Python list help


code:
field_qualifier = Group(LBRACK + OneOrMore(word) + RBRACK)
search_term = Group(Group(OneOrMore(word) | quotedString)('search_text') +
                          Optional(field_qualifier)('field'))
expr = Forward()
atom = search_term | (LPAREN + expr + RPAREN)
or_term = Group(atom + ZeroOrMore(or_op + atom))
and_term = Group(or_term + ZeroOrMore(and_op + or_term))
expr << and_term

rawDescription: pyparsing one query format to another one

description: Pyparsing one query format to another one


code:
import re
import sys

INPUT_VALIDATOR = re.compile("^[0-9]+$")

input_str = input("Please type a natural number to add up: ")

if INPUT_VALIDATOR.match(input_str) is None:
    print ("Your input was not a natural number (a positive whole number greater or equal to zero)!")
    print ("This displeases me, goodbye puny human.")
    sys.exit(1)

total = 0
for digit_str in input_str:
    print(digit_str)
    total += int(digit_str)
print("+")
print("___")
print(total)

rawDescription: Python: How to use a Variable Integer to Call a Specific Part of a String


rawDescription: Python: how to extend pairwise to triwise?


code:
# Synchronous way:
download(url1)  # takes 5 sec.
download(url2)  # takes 5 sec.
# Total time: 10 sec.

# Asynchronous way:
await asyncio.gather(
    download(url1),  # takes 5 sec.
    download(url2)   # takes 5 sec.
)
# Total time: only 5 sec. (+ little overhead for using asyncio)

rawDescription: When to use and when not to use Python 3.5 `await` ?


rawDescription: python tuple is immutable - so why can I add elements to it

description: Python tuple is immutable - so why can I add elements to it


code:
groups = df.groupby(df.date.dt.year).groups
# {2012: [0, 1], 2013: [2], 2014: [3], 2015: [4, 5]}
sorted_groups = [value for (key, value) in sorted(groups.items())]
# [[0, 1], [2], [3], [4, 5]]

cv = [(sorted_groups[i] + sorted_groups[i+1], sorted_groups[i+2])
      for i in range(len(sorted_groups)-2)]

rawDescription: scikit-learn cross validation custom splits for time series data

description: Scikit-learn cross validation custom splits for time series data


rawDescription: Converting tuple to integer

description: Converting tuple to integer


code: result = extractors[quantity](alist)

rawDescription: Code smell - if/else construct

description: Code smell - if/else construct


code: ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'AAA', 'AABERG', 'AACHEN', 'AAKER', 'AALSETH', 'AAMODT', 'AANCOR', 'AARDEMA']

rawDescription: Python: A good regular expression for text parsing in this example


code:
# This works but still puts a black dot for the nan point
carr = np.array([[0.0,0,0,1],[0,0,1,1],[0,1,0,1]]) # RGBA color array
carr[1] = np.repeat(np.nan,4)

pts = np.array([[1,2],[1,3],[2,2]]).T
plt.scatter(pts[0],pts[1],c=carr,s=500)

rawDescription: Exclude points from plotting by color definition?


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.clock import Clock

class Root(GridLayout):

    string = ''

    def animate_text(self):
        Clock.schedule_interval(self.update_label, 0.1)

    def update_label(self, dt):
        self.string += '>'
        self.ids.my_label.text = self.string

        if len(self.string) > 20:
            Clock.unschedule(self.update_label)
            self.string = ''
            self.ids.my_label.text = 'DONE'

class Test(App):
    pass

Test().run()

rawDescription: Kivy Update Label Texture

description: Kivy Update Label Texture


code:
import pandas as pd
df = pd.DataFrame(
    {'Name': ['name1', 'name2', 'name3', 'name4', 'name5'],
     'String': ['EXAN', 'EXAN_', 'EXAMPL', 'EXAMPLE', 'TEST'],
     'Value': [100.1, 200.2, 300.3, 400.4, 500.5]})
df['Value2'] = np.where(df['String'].str.contains(r'M'), df['Value']+50, np.nan)
df = df.reset_index(drop=False)
df = pd.lreshape(df, {'Value': ['Value', 'Value2']})
df = df.sort_values(by='index')
df = df.drop('index', axis=1)

rawDescription: Python: Adding a row when row iteration in dataframe find letter in string of a column


code:
#!/usr/bin/env python
import bjsonrpc
from SRPSocket import SRPSocket
import SocketServer
from bjsonrpc.handlers import BaseHandler
import time

class handler(BaseHandler):
    def time(self):
        return time.time()

class SecureServer(SRPSocket.SRPHost):
    def auth_socket(self, socket):
        server = bjsonrpc.server.Server(socket, handler_factory=handler)
        server.serve()

s = SocketServer.ForkingTCPServer(('', 1337), SecureServer)
s.serve_forever()

rawDescription: How to add authentication to a (Python) twisted xmlrpc server

description: Add authentication to a (Python) twisted xmlrpc server


rawDescription: Django Open / Edit record instead of Creating new


code:
reader = []
with mgf.read(mgf_file) as temp_read:
    for thing in temp_read:
        reader.append(thing)

rawDescription: Copying dicts from csv to a new dict-python


rawDescription: Subsetting a 2D numpy array

description: Subsetting a 2D numpy array


code: np.allclose(result_data, result_alt)

rawDescription: Optimizing or replacing array iteration with python loop by numpy functionality


code:
from collections import deque
def find_after_name(users, name):
    users2 = deque(users)
    users2.rotate(-1)
    for user1, user2 in zip(users1, users2):
        if user1.name == name:
            return user2

rawDescription: Find object from list that has attribute equal to some value and also get the next object after


rawDescription: 3D array multiplication

description: 3D array multiplication


code:
import nose
nose.run()

rawDescription: How to run all tests in a python file from a python script?

description: Run all tests in a python file from a python script


rawDescription: python counting frequency of elements

description: Python counting frequency of elements


rawDescription: making multiple pandas data frames using a loop or list comprehension

description: Making multiple pandas data frames using a loop or list comprehension


rawDescription: Regular expressions matching words which contain the pattern but also the pattern plus something else


code:
from collections import OrderedDict
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
    }
d_ascending = OrderedDict(sorted(d.items(), key=lambda kv: kv[1]['key3']))
d_descending = OrderedDict(sorted(d.items(),
                                  key=lambda kv: kv[1]['key3'], reverse=True))

rawDescription: python dictionary sorting in descending order based on values

description: Python dictionary sorting in descending order based on values


code:
Vendas.objects.create(item_price='5.0', purchase_count=1)
Vendas.objects.create(item_price='15.0', purchase_count=5)
Vendas.objects.extra(select={
    'price': 'sum(item_price * purchase_count)'
}).values_list('price', flat=True)[0]

rawDescription: Arithimetic operation before aggregation


code:
import mmap
mmap.PAGESIZE
mmap.ALLOCATIONGRANULARITY

rawDescription: Extract specific bytes from a binary file in Python


code:
import web

web.config.debug = False  # turns off the reloader

class subappcls:
    def GET(self):
        return "This will also be shown fine"

sub_mappings = (
    "/subpath", subappcls
)

#subclass web app
subwebapp = web.application(sub_mappings, globals())

#mapped class
class mapped_cls:
    def GET(self):
        return "this mapped sub app will not be found"

#Here I add mappings:
subwebapp.add_mapping("/mapped_sub_path", mapped_cls)

class appcls:
    def GET(self):
        return "main app"

main_mappings = (
    "/subapp", subwebapp,
    "/app", appcls,
)

mainwebapp = web.application(main_mappings, globals())

class indexcls:
    def GET(self):
        return "this will be shown just fine"

mainwebapp.add_mapping("/another", indexcls)

if __name__ == "__main__":
    mainwebapp.run()
else:
    application = mainwebapp.wsgifunc()

rawDescription: Unable to add mapping to sub application in WebPy


code: trann = models.ForeignKey(Transaction, related_name="doclinks")

rawDescription: Django: Creating editable default values for model instance based on foreignkey existance


code:
from datetime import datetime
datetime.strptime('2012-02-10' , '%Y-%m-%d')
_.isoweekday()

rawDescription: Convert string into Date type on Python

description: Convert string into Date type on Python


code:
do_not_select = (1, 2, 3)
cursor.execute("""SELECT * FROM table_a
                    WHERE id NOT IN {}""".format(do_not_select))
data.cursor.fetchall()

rawDescription: Python MySQL executemany in WHERE clause


code:
u = np.unique(arr)
indices = np.searchsorted(u, arr.flat)

rawDescription: How to find most frequent values in numpy ndarray?

description: Find most frequent values in numpy ndarray


code: files = [x for x in os.listdir('.') if os.path.isfile(x)]

rawDescription: How can I isolate part of a string in a list of strings and sort the list with it? (in Python)

description: Isolate part of a string in a list of strings and sort the list with it? (in Python)


code: [i for i, y_element in enumerate(set_y) if y_element in set_x]

rawDescription: Looking for an elegant way of finding the intersection between two lists of words' tuples in different orders


code:
from __future__ import print_function

import atexit
from os import path
from json import dumps, loads

def read_counter():
    return loads(open("counter.json", "r").read()) + 1 if path.exists("counter.json") else 0

def write_counter():
    with open("counter.json", "w") as f:
        f.write(dumps(counter))

counter = read_counter()
atexit.register(write_counter)

def main():
    print("I have been run {} times".format(counter))

if __name__ == "__main__":
    main()

rawDescription: how can i count how many time program has been executed in python

description: Count how many time program has been executed in python


code:
ax.set_xticklabels([r"$\left[ \begin{array}{cc} 0 & 1 \\ 1 & 0 \end{array}\right]$",
                    r"$\left[ \begin{array}{cc} 0 & 1 \\ 5 & 0 \end{array}\right]$",
                    r"$\left[ \begin{array}{cc} 0 & 1 \\ 10 & 0 \end{array}\right]$",
                    r"$\left[ \begin{array}{cc} 0 & 1 \\ 30 & 0 \end{array}\right]$",
                    r"$\left[ \begin{array}{cc} 0 & 1 \\ 50 & 0 \end{array}\right]$",
                    r"$\left[ \begin{array}{cc} 0 & 1 \\ 100 & 0 \end{array}\right]$"])

rawDescription: Add matrix in X-axis using matplotlib

description: Add matrix in X-axis using matplotlib


code:
import time
import zmq

ctx = zmq.Context.instance()
s = ctx.socket(zmq.PULL)
url = 'tcp://127.0.0.1:5555'
s.bind(url)

rawDescription: PyZMQ one-way communication

description: PyZMQ one-way communication


code:
dict(res[0] for res in parse_ns_headers(cookies))
from pprint import pprint
pprint(_)

rawDescription: passing in cookie python requests

description: Passing in cookie python requests


code:
dic = {'a':1, 'b':2}
dic['keys'] = dic.keys()
return render_to_response('your_template.html', dic)

rawDescription: Django templates: get the list of passed objects and variable


code:
import pandas as pd
import numpy as np

x = np.linspace(0, 1, 21)
y = np.random.rand(21)
s = pd.Series(y, index=x)

ax = s.plot(kind='bar', figsize=(10, 3))
ax.figure.tight_layout()

rawDescription: How can I set the x-axis tick locations for a bar plot created from a pandas DataFrame?

description: Set the x-axis tick locations for a bar plot created from a pandas DataFrame


rawDescription: In Django, how do I filter based on all entities in a many-to-many relation instead of any?


code: s = set(lst)

rawDescription: How to construct a set out of list items?

description: Construct a set out of list items


code:
'foo' in 'seafood'  # True
'foo' in 'flooded'  # False

rawDescription: Python 3: How Do I Restrict Words From An input() Containing "foo" or "bar"?


rawDescription: Python Tkinter - Find image file path from PhotoImage


code:
def whereclose(a, b, rtol=1e-05, atol=1e-08):
    return np.where(isclose(a, b, rtol, atol))

idx = whereclose(a, b, 0, atol)[0][0]

rawDescription: Find float in ndarray

description: Find float in ndarray


rawDescription: Get sums of pairs of elements in a numpy array


rawDescription: Accurate color blending in Matplotlib-Venn


code:
with open(path) as f:
    lines = [line.strip() for line in f if line]

rawDescription: Retrieve text blocks from file

description: Retrieve text blocks from file


code:
def process_index(k):
    return tuple(k.split("|"))

rawDescription: Coverting Index into MultiIndex (hierachical index) in Pandas


code:
import json
json.dumps({'foo': 'bar'})
json.loads(_)

rawDescription: How do I serialize a Python dictionary into a string, and then back to a dictionary?

description: Serialize a Python dictionary into a string, and then back to a dictionary


rawDescription: Python: Questions about math and negative power


code:
def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

rawDescription: Permutations of list of lists

description: Permutations of list of lists


code:
def traverse(root, callback):
    """
        Peform callback on all nodes in depth-first order
        e.g. traverse(root, lambda x:print(x))
    """
    yield root, callback(root)
    for child in root.children:
        traverse(child)

def getAllDescendents(title):
    queryNode = titlesToNodes[title]  #what you call 'tree'
    for node,blah in traverse(queryNode, lambda x:None):
        yield node

rawDescription: Python - Tree traversal question

description: Python - Tree traversal question


rawDescription: python - filter function for nested loop and if condition

description: Python - filter function for nested loop and if condition


code:
if classchoice == "A":
    write_flag = True
    with fileinput.input("classa.txt", inplace=1) as f:
        for line in f:
            line = line.rstrip()
            words = line.split()
            if name == words[0]:
                line = line + " " + str(score)
                write_flag = False
            print(line)
        #This is if `name` was never found, meaning we have to add the name to the file with the score.
    if write_flag:
        with open("classa.txt",'a') as f:
            f.write("{} {}\n".format(name,score))

rawDescription: Python: Storing data in a text file and appending particular/individual lines


code:
def taskchain(*args, **kwargs):
    output = kwargs.get('output', PIPE)
    error_output = kwargs.get('error_output', STDOUT)
    lastprocess = None

    for index, argset in enumerate(args):
        islastprocess = index == len(args) - 1

        process = Popen(argset, stdout=output if islastprocess else PIPE,
                stdin=None if lastprocess is None else lastprocess.stdout,
                stderr=error_output)

        if lastprocess is not None:
            lastprocess.stdout.close()

        lastprocess = process

    if output == PIPE:
        return lastprocess.communicate()
    else:
        lastprocess.wait()

rawDescription: Solving process chaining in Python

description: Solving process chaining in Python


code:
df.columns = df.columns.str.split(":", 1).str[1]
df

rawDescription: Strip all characters from column header before a :


code: queryset = Order.objects.values('id', 'user_id', 'details__product_type')

rawDescription: Django query in One to Many relationship


code:
urlpatterns += patterns('',
    url(r'^profile/(?P\d+)/$', ' ...', name='profile'),
)

rawDescription: Django HttpResponseRedirect with int parameter


code:
import time

transdata =  get_http('https://coinbase.com/api/v1/transfers').read()
f1 = open('{}_DUMP.txt'.format(int(time.time())), 'w+')
f1.write( transdata )

rawDescription: How to timestamp output text files

description: Timestamp output text files


code:
class Vertex(object):
    def __init__(self,key):
        self.id = key
        self.connectedTo = {}

class Graph(object):
    def __init__(self, vertexclass=Vertex):
        self.vertList = {}
        self.numVertices = 0
        self.vertexclass = vertexclass

    def addVertex(self,key):
        self.numVertices += 1
        newVert = self.vertexclass(key)
        self.vertList[key] = newVert
        return newVert

    def getVertex(self,k):
        if k in self.vertList:
            return self.vertList[k]
        else:
            return None

rawDescription: How do I use a new extended class instead of the original in another loaded class

description: Use a new extended class instead of the original in another loaded class


rawDescription: Issue with transposing a data set using pandas


code:
partner = {

    'name': 'Fabien Pinckaers',
    'lang': 'fr_FR',
    'address': [(0,0,{
        'type': 'default',
        'street': 'Chaussée de Namur 40',
        'zip': '1367',
        'city': 'Grand-Rosière',
        'phone': '+3281813700',
        'fax': '+3281733501',
    })]
}

rawDescription: 1 sock.execute transaction with 2 data structures


code:
def tpl_print(name, origin, idn):
    return "\nname: {0}\norigin: {1}\nidn: {2}".format(name, origin, idn)

print(tpl_print("horse", "Europe", "001"))

rawDescription: Python: Template for printing out select values


code:
zebra = 'Yout caretak taking care of something'
words = nltk.word_tokenize(zebra)
words

rawDescription: Python Converting output into sentence

description: Python Converting output into sentence


code:
# in file myapp/views.py

from registration.backends.simple.views import RegistrationView
from .forms import MyRegistrationForm

class MyRegistrationView(RegistrationView):

    form_class = MyRegistrationForm

    def register(self, request, form):

        user = super(MyRegistrationView, self).register(request, form)
        user.birth_date = form.cleaned_data["birth_date"]
        user.photo = form.cleaned_data["photo"]

        user.save()

        return user

rawDescription: Custom User's and implementations with forms


code: df.groupby(level=0).apply(lambda df: replace_first_x(df, 2, 9999))

rawDescription: How to Update Value in First N Rows by Group in a Multi-Index Pandas Dataframe?


rawDescription: pandas reading dates from csv in yy-mm-dd format

description: Pandas reading dates from csv in yy-mm-dd format


code:
tag_dict = {'001':['apple','orange'], '002':['banana','strawberry','peach']}
df = pd.DataFrame.from_dict(tag_dict, orient='index').stack()
df.reset_index(level=0)

rawDescription: dict to dataframe with value in list

description: Dict to dataframe with value in list


code:
d = Detail()
d
print(d)

rawDescription: How to print an object in Python

description: Print an object in Python


code:
from sqlalchemy.orm import aliased
utm1 = aliased(UserTypeMapper)
utm2 = aliased(UserTypeMapper)

rawDescription: SQLAlchemy mapping joined tables' columns to one object


code:
for i in xrange(n_pts):
    r = float(i)/float(n_pts)*r_max

rawDescription: Integrate using SciPy with variable integrand members and put into meshgrid


code:
jlist = []  # make jlist a globally accessible variable

def write_to_file(string):
    jdata = json.loads(string)
    jlist.append(jdata)
    with open("Data.json", "w") as outfile:
        json.dump(jlist,outfile, indent=4)

rawDescription: unexpected formatting when dumping to json

description: Unexpected formatting when dumping to json


code:
pairs = [("sumstring1","abc.txt"), ("sumstring2","def.txt"),
         ("sumstring1","ghi.txt"), ("sumstring2","jkl.txt")]
dups = collections.defaultdict(set)
for checksum, name in pairs:
    dups[checksum].add(name)
dups

rawDescription: In a list of tuples, return tuple[1] if tuple[0] is a duplicate of another tuple[0] in the list


code:
counter_a = Counter()
counter_b = Counter()

for _ in range(3):
    counter_a.increment()
for _ in range(1000000):
    counter_b.increment()

assert counter_a.count == 3
assert counter_b.count == 1000000

rawDescription: Why do we use classes in Python?

description: Why do we use classes in Python


code:
# test file
def test_input():
    s = raw_input()
    assert s.strip() == "Pass"

rawDescription: nose test freezing at raw_input

description: Nose test freezing at raw_input


code:
a = []
temp = a
temp.extend(['foo', 'bar'])
a
temp is a

rawDescription: Iteratively add elements to a list

description: Iteratively add elements to a list


code:
def cutoff(string, pattern):
    idx = string.find(pattern)
    return string[:idx if idx != -1 else len(string)]

cutoff(s, "23")
cutoff(s, "asdfdsafdsa")

rawDescription: Slice a string after a certain phrase?

description: Slice a string after a certain phrase


code: scoreatpercentile(x, [lo, hi])

rawDescription: Interval containing specified percent of values


code:
posible_match = np.where(np.logical_and(*[lookup[..., i] == tplsum[i] for i in range(D)]))
for y, x in zip(*posible_match):
    if np.all(im[y+1:y+h+1, x+1:x+w+1] == tpl):
        return (y+1, x+1)

rawDescription: Determine if an image exists within a larger image, and if so, find it, using Python


code:
import importlib

module = importlib.import_module('uid_2014-10-13')

rawDescription: Is it able to import from a module named uid_2014-10-13.py?


code: found_keys = [k for k in h5file if re.match(r'/some/[pattern]+', k)]

rawDescription: How to feed a regular expression to a method that requires a string?

description: Feed a regular expression to a method that requires a string


code:
import random
random.shuffle(questions,random.random) #shuffle list in place
d = {}
for (q,v) in questions:
   d[v] = raw_input(q)
   #more stuff like hide(str)

rawDescription: Python- Simple random selector

description: Python- Simple random selector


code:
print("Hello", end='')
a = "This is a test"
print(a)
#HelloThis is a test

rawDescription: Print without a newline between two strings


code:
for name, records in groupby(SeqIO.parse(some_genbank, 'gb'), lambda record:record.annotations['source']):
    with open(name + ".faa", "w+") as outf:
        for record in records:
            write_all_record(outf, record)

rawDescription: Opening and closing files in a loop

description: Opening and closing files in a loop


code: # vim: set filetype=python :

rawDescription: vim creating alias for frequently used command

description: Vim creating alias for frequently used command


code: urls = raw_input("Enter yer urls! ")

rawDescription: Dynamic Python Variables

description: Dynamic Python Variables


rawDescription: Implementing a model for "teams" in django


code: mng.frame.SetPosition(*args, **kwargs)

rawDescription: matplotlib window layout questions

description: Matplotlib window layout questions


rawDescription: Build an array by averaging n consecutive numbers in an array


code:
self.my_color = "red"
...
self.canvas.create_rectangle(..., fill=my_color)

rawDescription: Is there a way to have a "default color" with a canvas in Tkinter?


code:
class MyClass(object):
   def __init__(self, Matrix):
      self._Matrix=Matrix
   def set_Matrix(self,Matrix):
      self._Matrix=Matrix
   def get_Matrix(self):
      return self._Matrix
   def get_nonzero(self):
      return len(_Matrix[nonzero(_Matrix)])

rawDescription: Custom Class - Change attribute in array


code:
to_remove = set()
# still iterate over it as a list, since we need that to be able to slice it
# if you replace it with a set at the outset, you can always listify it
# by doing `list(lst_as_set)`
for index,f1 in enumerate(lst):
    if f1 in to_remove:
        continue
    # parens in slicing aren't required, but add clarity
    for f2 in lst[(index+1):]:
        if f2 in to_remove:
            continue
        # no need to check for f1 == f2, since that's now impossible
        if f1.intersect(f2):
            if f1.score >= f2.score:
                to_remove.add(f2)
            else:
                to_remove.add(f1)

# yep, we can turn the set into a list more or less trivially
# (usually, duplicate elements make things complicated)
keep = set(lst)
# set difference can be done with the minus sign:
# https://docs.python.org/2/library/stdtypes.html#set
keep = keep - to_remove

rawDescription: Python 2.7 delete items form list while looping


code:
for pair in format:
    however_many = len(pair[0])
    argues.append((args[positional_index:positional_index+however_many], {k: kwargs[k] for k in pair[1]}))
    positional_index += however_many

rawDescription: Getting respective *args, **kwargs from collection of functions, then filling in the irregular 2d structure with provided 1d arguments


code:
names=['buyer{i:0>3d}'.format(i=i) for i in range(1,6)]
maxValuations=range(100,75,-5)
endowments=range(500,250,-50)
for name, maxValuation, endowment in zip(names,maxValuations,endowments):
    mgr.register_actor(
        Buyer(name=name, maxValuation=maxValuation, endowment=endowment),name)

rawDescription: How to dynamically update values to arguments in Python loop?

description: Dynamically update values to arguments in Python loop


code:
from django.core.serializers import serialize
from django.db.models.query import QuerySet
from django.utils import simplejson
from django.utils.safestring import mark_safe
from django.template import Library

register = Library()

def jsonify(object):
    if isinstance(object, QuerySet):
        return mark_safe(serialize('json', object))
    return mark_safe(simplejson.dumps(object))

register.filter('jsonify', jsonify)
jsonify.is_safe = True

rawDescription: Django Template - Convert a Python list into a JavaScript object


rawDescription: arrange values in a python 2D array

description: Arrange values in a python 2D array


rawDescription: Can't get simple loop working right

description: Can't get simple loop working right


code:
import smtplib
mailer = smtplib.SMTP()
mailer.connect()
mailer.sendmail(from_, to, msg.as_string())
mailer.close()

rawDescription: How to send email with pdf attachment in Python?

description: Send email with pdf attachment in Python


code:
import os
null = open(os.devnull, 'w')
twill.set_output(null)
html = show() # writing to /dev/null or nul
null.close()

rawDescription: Using show() with twill spams the console with HTML


code:
import urllib, urllib2, cookielib, re

zendesk_subdomain = 'mysub'
zendesk_username = '...'
zendesk_password = '...'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
resp = opener.open('http://%s.zendesk.com/access/unauthenticated' % (zendesk_subdomain))
s = resp.read()
data = dict()
data['authenticity_token'] = re.findall('<input name="authenticity_token" type="hidden" value="([^"]+)"', s)[0]
data['return_to'] = 'http://%s.zendesk.com/login' % zendesk_subdomain
data['user[email]'] = zendesk_username
data['user[password]'] = zendesk_password
data['commit'] = 'Log in'
data['remember_me'] = '1'

opener.open('https://localch.zendesk.com/access/login', urllib.urlencode(data))

rawDescription: Scrapy: Do form login and then work with that session


code:
rest_content = """
I should be an h1
=================

I should be an h2
-----------------
foo

I should also be an h2
----------------------
foo
"""

from docutils.core import publish_parts
parts = publish_parts(rest_content, writer_name="html",
        settings_overrides={'doctitle_xform':False})
html_snippet = parts['html_body']

print(html_snippet)

rawDescription: reStructuredText not respecting subheadings

description: ReStructuredText not respecting subheadings


rawDescription: How to sort a list based on dictionary values?

description: Sort a list based on dictionary values


code:
import datetime
import time

user_reg_time = datetime.datetime.strptime("20091129060140", "%Y%M%d%H%m%S")
epochs_time = time.mktime(user_time_reg.timetuple())

rawDescription: Python: Convert Varbinary type timestamp to unix time stamp


code:
class player:
    def __init__(self, x=0, y=0):
       self.x = x
       self.y = y

    def up(self):
        self.y += 1

    def down(self):
        self.y -= 1

    def left(self):
        self.x -= 1

    def right(self):
        self.x += 1

    def move(self, direction):
        # call the appropriate method that corresponds to given direction
        getattr(self, direction)()

rawDescription: Storing code in a list or dictionary?

description: Storing code in a list or dictionary


code: url = '%syear_%s/month_%s/day_%s/%s/' % (BASE, year, month, day, game_id)

rawDescription: basic python module design question

description: Basic python module design question


rawDescription: Combining first elements of nested lists and summing the second elements


code:
for i in range(10):
    # create dict
    df.append( created_dict )

rawDescription: Python : append/merge dicts to pandas in a pythonic way


code:
results = OneOrMore(Group(section)).parseString(source)
results.pprint()

rawDescription: Parsing text file in python using pyparsing


rawDescription: remove asterisk symbol inside diamond shape

description: Remove asterisk symbol inside diamond shape


code:
KEYROWS = {
    'normal': [
       '1234567890+',
       'qwertyuiop',
       "asdfghjkl",
       '<zxcvbnm,.-',
    ],
    'caps': [
       '!"#$%&/()=?',
       'QWERTYUIOP',
       'ASDFGHJKL*',
       '>ZXCVBNM;:_',
    ],
}

def RenderKeys(self, keyset):
    rows = self.KEYROWS[keyset]
    for row,keys in enumerate(rows):
        for col, key in enumerate(keys):
            btn = Button(self.Level, text=key, command=lambda key=key:self.AppendKey(key), font=("Helvetica", 16), width=3, height=2)
            btn.grid(row=row + 2, column=col)

def AppendKey(self, value):
    self.InputFiled.insert(END, value)

rawDescription: Looping buttons, forgets the button value


code:
from redis import Redis
from rq_scheduler import Scheduler
from datetime import timedelta

from after_hours import after_6_hours

def create_game():
    print('Game created')

    scheduler = Scheduler(connection=Redis()) # Get a scheduler for the "default" queue
    scheduler.enqueue_in(timedelta(hours=6), after_6_hours) #schedules the job to run 6 hours later.

rawDescription: How to schedule a single-time event in Django in Heroku?

description: Schedule a single-time event in Django in Heroku


rawDescription: Converting two lists into a matrix

description: Converting two lists into a matrix


rawDescription: Python: updating a large dictionary using another large dictionary


code: outfile.close() # <- add parens

rawDescription: file.write only performed upon exit of an interactive python session?

description: File.write only performed upon exit of an interactive python session


code:
class A:
    pass

rawDescription: Is it necessary to include __init__ as the first function everytime in a class in Python?


rawDescription: To split strings using Python

description: To split strings using Python


code: df.groupby(['x1', 'x2']).agg({'x3': {'my_sum':np.sum, 'my_mean':np.mean}}).T.reset_index(level=0, drop=True).T.reset_index()

rawDescription: A better way to aggregate data and keep table structure and column names with Pandas


code:
from sys import version
import subprocess

class Popen(subprocess.Popen):
    def __init__(self, *args, **kwds):
        subprocess.Popen.__init__(self, *args, **kwds)
        self.args = args[0]

if version[0] < 3 or (version[0]==3 and version[1] < 3): # pre 3.3
    subprocess.Popen = Popen

rawDescription: Python: how to get command run with subprocess Popen


code:
clf = DecisionTreeClassifier()
clf.fit(X, y)

rawDescription: decision trees from features of multiple datatypes

description: Decision trees from features of multiple datatypes


code:
class PureMap:
    def __init__(self, function, sequence):
        self._f = function
        self._sequence = sequence

    def __iter__(self):
        return map(self._f, self._sequence)
    def __getitem__(self, i):
        return self._f(self._sequence[i])
    # etc.

rawDescription: Lazy evaluation of map

description: Lazy evaluation of map


rawDescription: Python: convert a dot separated hex values to string?


code:
from json import JSONDecoder
from functools import partial

def json_parse(fileobj, decoder=JSONDecoder(), buffersize=2048):
    buffer = ''
    for chunk in iter(partial(fileobj.read, buffersize), ''):
         buffer += chunk
         while buffer:
             try:
                 result, index = decoder.raw_decode(buffer)
                 yield result
                 buffer = buffer[index:]
             except ValueError:
                 # Not enough data to decode, read more
                 break

rawDescription: How do I use the 'json' module to read in one JSON object at a time?

description: Use the 'json' module to read in one JSON object at a time


code: p_names = (p.name for p in Position.objects.all())

rawDescription: Django: ForeignKey to_field and db_column doesn't seem to work


code: images.transpose()  # or images.T

rawDescription: reshape an array of images

description: Reshape an array of images


code:
computed_field = fields.Char(compute='comp', inverse='inv', store=True)
boolean_field = fields.Boolean()

@api.one
def comp(self):
    ...

@api.one
def inv(self):
    ...

rawDescription: How to make a field computed only if some condition is fulfilled in Odoo 8?

description: Make a field computed only if some condition is fulfilled in Odoo 8


rawDescription: Different append of n item to list and [0]*n in python?


rawDescription: Dot notation string manipulation

description: Dot notation string manipulation


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

G=nx.star_graph(3)
L=nx.line_graph(G)
nx.draw(G, node_size=500)
plt.show()

rawDescription: networkx edge-to-node node-to-edge representation

description: Networkx edge-to-node node-to-edge representation


code:
import scipy.linalg.blas as FB
vx = FB.dgemm(alpha=1.0, a=A.T, b=A.T, trans_b=True)

rawDescription: Is there an "enhanced" numpy/scipy dot method?


code:
from MyProject import settings
import django
django.setup()

rawDescription: how to run a custom script in parallel with django

description: Run a custom script in parallel with django


rawDescription: Accessing hierarchical columns in pandas after groupby


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:
class UserAdmin(admin.ModelAdmin):

    list_display = ('income', ...)

    def income(self, obj):
        return obj.income

    def get_queryset(self, request):
       queryset = super(UserAdmin, self).get_queryset(request)
       # you logic here to `annotate`the queryset with income
       return queryset

rawDescription: Django admin list display optimize queryset


code:
for data, machine in results:
  print("The data is %d from machine %d." % (data, machine))

rawDescription: Tag extra information to differentiate numbers in a list


code: df.index = df.index.map(lambda x: 'row%s' % x)

rawDescription: Pandas dataframe - how to assign index?

description: Pandas dataframe - how to assign index


code: [typeB for typeB in typeBlist if typeB.typeA == typeA]

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


code:
for node in tree.in_order():
    whatever(node.some_other_attribute)

rawDescription: Python in order traversal to a flat list


code: sorted(L, key=itemgetter(1))

rawDescription: merging n sorted lists of tuples in python

description: Merging n sorted lists of tuples in python


code:
from bisect import bisect_left
def commonElements(a1, a2):
   L = []
   a2.sort() #sort a2 to be able to use binary search in the internal loop thus changing the complexity from O(n^2) to O(n*log(n)) (assuming n and m are rather equal).
   a2_len = len(a2)
   for el in a1:
       i = bisect_left(a2, el)
       if i != a2_len and a2[i] == el:
           L.append(x)
   # L.sort() #uncomment this line if the list in sorted order is needed (not just ordered as the first lits; it's possible to sort a1 in the very beginning of the function, but that would be slower on the average since L is smaller on the average than a1 or a2 (since L is their intersection).
   return tuple(L)

rawDescription: How do I find every element that is in both of two other lists?

description: Find every element that is in both of two other lists


code:
W(d)
W(d)
W(d)
W(d)

rawDescription: Python Dictionary, make range associated with its values and return them


code:
df2 = df.set_index(['by_currency', 'by_portfolio']).stack().unstack(0)
df2.columns.name = None
df2.index = df2.index.swaplevel(0,1)
df2 = df2.sort_index()
df2

rawDescription: Multiindex on DataFrames and sum in Pandas


code:
if data==b"":
    break

rawDescription: reading binary data and retrieving per condition : working fine in Python 2.6.x but not in Python 3.2

description: Reading binary data and retrieving per condition : working fine in Python 2.6.x but not in Python 3.2


rawDescription: Remove items from list if they are within a given range


code: a + b

rawDescription: class in python with method acting on self. inheritance

description: Class in python with method acting on self. inheritance


code:
def modseq(n, p):
    r = 0
    for i in range(n):
        r = (r + p) % n
        yield r

rawDescription: Time based rotation

description: Time based rotation


code:
import csv

with open('data.txt', 'rb') as inf:
     data = list(csv.reader(inf, skipinitialspace=True))
     data = [i for i in data if i] ## add to deal w/ blank lines in data file

rawDescription: Reading from a file directly into a 2D list python


code:
alpha_dict = {"A": ("Apple", 14.5), "B": ("Banana", 23.4)}

user_input = "A"

alpha_dict[user_input]
Out[8]: ('Apple', 14.5)

rawDescription: Comparing user input with tuple value

description: Comparing user input with tuple value


code: string += str(getbingint) + ":" + str("%.2f") % (getsmallint*1.225) + ","

rawDescription: Python basic maths

description: Python basic maths


code:
income_brackets = [(0, 25000), (25000, 50000)]
source = {'grant': [], 'funding': []}

#Hard to understand one-liner
#source = {key: [median(df.query('income > {} and income < {}'.format(lower, upper))[key]) for lower, upper in income_brackets] for key in source}

#Easy to understand three-liner
for lower, upper in income_brackets:
    for key in source:
        source[key].append(median(df.query('income > {} and income < {}'.format(lower, upper))[key]))

rawDescription: Creating variables using loops or lists. Dynamic Loops are bad?


code:
import pandas as pd
import numpy as np

np.random.seed(1)
s = pd.Series(np.random.randint(0,20,20))

categories, edges = pd.qcut(s, 5, retbins=True)
df = pd.DataFrame({'original':s,
                   'bin_max': edges[1:][categories.labels]},
                  columns = ['original', 'bin_max'])
print(df)

rawDescription: How to return max value of quantile cut range instead of quantile label

description: Return max value of quantile cut range instead of quantile label


rawDescription: Extracting polygon given coordinates from an image using OpenCV


code: bins_arange = numpy.arange(xmin, xmax + 1, binsize)

rawDescription: Weighted mean in numpy/python

description: Weighted mean in numpy/python


code: d[attrib_a, attrib_b] = t

rawDescription: Python creating dictionary key from a list of items


code:
list_of_strings = ['foo', 'ba', 'a']
''.join([format(el, '>4') for el in list_of_strings])

rawDescription: Is there is way to justify substrings while performing join operation


code:
format_timedelta(timedelta(days=2, hours=10, minutes=20, seconds=3))
format_timedelta(timedelta(hours=10, minutes=20, seconds=3))

rawDescription: How can I display timedelta in hours:min:sec?

description: Display timedelta in hours:min:sec


code: import config

rawDescription: Python pattern for sharing configuration throughout application


code:
ts.ix[ts.index.indexer_between_time(datetime.time(18), datetime.time(9),
                                    include_start=False, include_end=False)]

rawDescription: Pandas Drop Rows Outside of Time Range

description: Pandas Drop Rows Outside of Time Range


code:
x = { 1: "a", 2: "b", 3: "c" }
y = { 1: "A", 2: "B", 3: "C" }
{key: x.get(key, "") + y.get(key, "") for key in set.intersection(set(x.keys()), set(y.keys()))}

rawDescription: Merge values of a dictionary by key based on custom function


rawDescription: Python sql query insert data in columns

description: Python sql query insert data in columns


code:
class Qnode:
    # initialization method
    def __init__(self,guess):
        self.nodetype = kGuess
        self.desc = guess
        nodes.append(self)

rawDescription: Saving dict with nested class instances in Python 2.7


code:
with io.open('d.txt', 'r', encoding='utf-8') as doc:
   ...

rawDescription: How to find all capital and lower case occurrences of unicode character using regex and re.sub in Python?

description: Find all capital and lower case occurrences of unicode character using regex and re.sub in Python


rawDescription: compare elements of two lists

description: Compare elements of two lists


code:
signal = thub(sig, 2) # T-Hub is a T (tee) auto-copy
filt1(signal) * line(dur, 0, 1) + filt2(signal) * line(dur, 1, 0)

rawDescription: Applying time-variant filter in Python

description: Applying time-variant filter in Python