code:
m = re.search('^(?P<description>.*?)(Arguments:(?P<arguments>.*?))?(Returns:(?P<returns>.*))?$', s, re.DOTALL)
m.groupdict()['description']
m.groupdict()['arguments']
m.groupdict()['returns']

rawDescription: regex: string with optional parts

description: Regex: string with optional parts


code:
from multiprocessing import Process

class P(Process):
    def __init__(self):
        super(P, self).__init__()
    def run(self):
        print('hello')

p = P()
p.start()
p.join()

rawDescription: Using Python's multiprocessing.Process class


code:
paired = zip(List2,List3,List1)
rev_sorted = sorted(paired,reverse=True,key=lambda x: x[1])  #"minor" sort first
paired_sorted = sorted(rev_sorted,key=lambda x:x[0])         #"major" sort last
l2,l3,l1 = zip(*paired_sorted)

rawDescription: Sort List in Python by two other lists

description: Sort List in Python by two other lists


code:
import itertools
for f,b in itertools.izip(foo,bar):
    print(f,b)
for f,b in itertools.izip_longest(foo,bar):
    print(f,b)

rawDescription: How can I iterate through two lists in parallel in Python?

description: Iterate through two lists in parallel in Python


code:
mat = [['V', 'A', 'T'], ['D', 'I', 'S'], ['O', 'I', 'M'], ['F', 'U', 'A']]
rows = len(mat)
cols = len(mat[0])
diags = [[mat[sum_-k][k]
          for k in range(sum_ + 1)
          if (sum_ - k) < rows and k < cols]
         for sum_ in range(rows + cols - 1)]
print(diags)

rawDescription: Diagonals in a non-square matrix - python


code:
import sys
import subprocess as sp
import cPickle

BEGIN = 'pickle_begin'

def send_and_exit(x):
    sys.stdout.write(BEGIN + cPickle.dumps(x))
    sys.stdout.flush()
    sys.exit(0)

def execute_and_receive(filename):
    p = sp.Popen(["python", filename], stdout=sp.PIPE)
    (out, err) = p.communicate()
    return cPickle.loads(out[out.find(BEGIN) + len(BEGIN):])

rawDescription: How to Get Variable from another .py

description: Get Variable from another .py


code:
# Note that login_required needs to come before app.route
# Because decorators are applied from closest to furthest
# and we don't want to route and then check login status

@app.route("/")
@login_required
def home():
    # For bonus points we *could* store the user
    # in a thread-local so we don't have to hit
    # the database again (and we get rid of *this* boilerplate too).
    user = database.get(request.cookies['YourSessionCookie'])
    return render_template('welcome.html', user=user)

@app.route("/do-that")
@login_required
def do_that():
    user = database.get(request.cookies['YourSessionCookie'])
    return render_template('welcome.html', user=user)

rawDescription: Python Flask: keeping track of user sessions? How to get Session Cookie ID?


code: vars()[rate] = 'k' + str(i)

rawDescription: Iteration over variable names in python?

description: Iteration over variable names in python


code:
template = etree.fromstring('
 A template
', etree.HTMLParser(remove_comments=True))
etree.tostring(template)

rawDescription: Parsing html partial templates using lxml


code:
a = np.random.standard_normal(size=(2,5))
a
i = np.array([[0,1,2,4,3],[0,1,2,3,4]])
a[np.arange(a.shape[0])[:,np.newaxis],i]

rawDescription: Numpy: Sorting a multidimensional array by a multidimensional array


code: minutes, seconds = divmod(mytime.total_seconds(), 60)

rawDescription: subtraction date - how to get result in minutes

description: Subtraction date - how to get result in minutes


code:
zip(datarelmax_0[0], datarelmax_0[1])
zip(datarelmax_1[0], datarelmax_1[1])

rawDescription: How to create a numpy array from two lists of tuples, but only when the tuples are the same

description: Create a numpy array from two lists of tuples, but only when the tuples are the same


code:
class ChartData(object):
    def check_valve_data():
        data = {'serial numbers': [], 'mass': [],
                 'pressure drop': [], 'cracking pressure': [], 'reseat pressure': []}

        valves = CheckValve.objects.all()

        for unit in valves:
            data['serial numbers'].append(unit.serial_number)
            data['mass'].append(unit.mass)
            data['cracking pressure'].append(unit.cracking_pressure)
            data['pressure drop'].append(unit.pressure_drop)
            data['reseat pressure'].append(unit.reseat_pressure)

        return data

rawDescription: Passing Django Database Queryset to Highcharts via JSON


code:
def pairs(df, k1,k2, a, b):
    check = df.loc[(df[k1] == a) & (df[k2] == b)]
    return None if check.empty else check.index[0]

rawDescription: Is there a way to 'search' in a pandas DataFrame for 2 specific numbers in columns and return the index if it exists?


code:
class InhalationAnesthesia(Anesthesia):
    __tablename__ = 'inhalation_anesthesias'
    __mapper_args__ = {'polymorphic_identity': 'inhalation'}
    id = Column(Integer, ForeignKey('anesthesias.id'), primary_key=True)
    # ...
    # specific fields definition
    # ...

class TwoStepInjectionAnesthesia(Anesthesia):
    __tablename__ = 'twostep_injection_anesthesias'
    __mapper_args__ = {'polymorphic_identity': 'twostep_injection'}
    id = Column(Integer, ForeignKey('anesthesias.id'), primary_key=True)
    # ...
    # specific fields definition
    # ...

rawDescription: multiple/split class associations in sqlalchemy

description: Multiple/split class associations in sqlalchemy


code:
class DequeLL:

    def __init__(self):
        self.head = None
        self.last = None
        self.length = 0

    def __str__(self): # Refactored for clarity
        width = (max(len(node.data) for node in self.allNodes())
                    if self.head else 0) # width to avoid ambiguity with self.length
        s = ['\u2510{}\u250c'.format(' '*width)]
        for node in self.allNodes():
            s.append('\u2502{:<{}}\u2502'.format(node.data, width))
        s.append('\u2514{}\u2518'.format('\u2500'*width))
        return '\n'.join(s)

    def addFrontDLL(self, item):
        temp = Node(str(item))
        temp.setNext(self.head)
        self.head = temp
        if self.last is None: # if adding to an empty deque, set the last node, too
            self.last = temp
        self.length += 1
        print(self) # refactored the pretty-printing into __str__ for clarity

    def addRearDLL(self, item):
        node = Node(str(item))
        node.next = None
        if self.length == 0:
            self.head = self.last = node
        else:
            last = self.last
            last.next = node
            self.last = node
        self.length = self.length + 1
        print(self)

    def allNodes(self):
        node = self.head
        while node is not None:
            yield node
            node = node.next

rawDescription: Python: Linklist deque addfront & addrear


code:
a
m,n = a.shape
a

rawDescription: numpy matrix, setting 0 to values by sorting each row

description: Numpy matrix, setting 0 to values by sorting each row


code:
class FooAdmin(admin.ModelAdmin):
    ...

    list_display = ['name', 'my_action_link', ...]

    def get_urls(self):
        urls = super(FooAdmin, self).get_urls()
        my_urls = patterns('',
            (r'^my_custom_action/(?P<pk>\d+)/$', self.my_view)
        )
        return my_urls + urls

    @permission_required('foo.can_change')
    def my_view(self, request):
        obj = get_object_or_404(Foo, pk=pk)
        obj.do_something()
        # Redirect back to the change list. Or something else?
        # You could add some modelform to this view. :)

rawDescription: Customizing django admin site - in row buttons


code:
import numpy as np
def DFT_matrix(N):
    i, j = np.meshgrid(np.arange(N), np.arange(N))
    omega = np.exp( - 2 * pi * 1J / N )
    W = np.power( omega, i * j ) / sqrt(N)
    return W

rawDescription: DFT matrix in python

description: DFT matrix in python


code:
#!/usr/bin/python2

import pandas as pd
import numpy as np
import sys

# Make an example data frame.
df = pd.DataFrame(np.random.randint(100, size=(5,5)),
                  columns=['a', 'b', 'c', 'd', 'e'])

header = '\n'.join(
    # I like to make sure the header lines are at least utf8-encoded.
    [unicode(line, 'utf8') for line in
        [ '1001',
        'Daedalus, Stephen',
        'Dublin, Ireland',
        'Keys',
        'MINOS',
        '1,1',
        '1904,06,16,1922,02,02',
        'time_since_8am', # Ends up being the header name for the index.
        ]
    ]
)

with open(sys.argv[1], 'w') as ict:
    # Write the header lines, including the index variable for
    # the last one if you're letting Pandas produce that for you.
    # (see above).
    for line in header:
        ict.write(line)

    # Just write the data frame to the file object instead of
    # to a filename. Pandas will do the right thing and realize
    # it's already been opened.
    df.to_csv(ict)

rawDescription: Writing multiple header lines in pandas.DataFrame.to_csv


code:
st='3 eaxmple1.jpg example22.jpg 4'
re.findall(r'(?:\D|^)(\d)(?:\D|$)', st)

rawDescription: Repeated Number in Python Regular expression


code:
from lxml import html
s='[<span class="street-address">\n            510 E Airline Way\n           </span>]'
h = html.document_fromstring(s)
h.cssselect('span')[0].text.strip()

rawDescription: Python beautifulsoup trying to remove html tags 'span'


code: RetVal = Shell("<full path to python.exe> " & "<full path to your python script>")

rawDescription: How to call python script on excel vba?

description: Call python script on excel vba


rawDescription: Re-reading file when cycling over a file object in Python


code:
df = pd.DataFrame({'Date': pd.Series([datetime(2014, 8, 12),
                                      datetime(2014, 8, 13),
                                      datetime(2014, 8, 14),
                                      datetime(2014, 8, 15),
                                      datetime(2014, 8, 16)]),
                   'TotalData': pd.Series([500, 600, 750, 150, 300])
                   })
df['PrevTotalData'] = df['TotalData'].shift(1)
df.loc[0, 'PrevTotalData'] = 0

# Assuming here that the amount of data day after reboot is always less then
# the total amount of data in previous day
rebooted = df['PrevTotalData'] > df['TotalData']
df['DataBeforeLastReboot'] = 0
df.ix[rebooted, 'DataBeforeLastReboot'] = df['PrevTotalData']
df['DataBeforeLastReboot'] = df['DataBeforeLastReboot'].cumsum()
df['TotalDataFixed'] = df['TotalData'] + df['DataBeforeLastReboot']

print(df)

rawDescription: Correcting cumulatives in Pandas

description: Correcting cumulatives in Pandas


code:
import numpy as np

data = {
    'boxes': np.array([[x1, y1], [x2, y2]]),
    'height': np.array([h1, h2]),
    'general_parameter': np.array([par1, par2])
}

rawDescription: Recommended way to represent my data with numpy


rawDescription: Unique class instances in Python3

description: Unique class instances in Python3


code: [(k, [x[1] for x in g]) for k, g in itertools.groupby(items, lambda x: x[0])]

rawDescription: Combine list of lists with similar values in python


code:
ax = plt.gca()
ax.set(xticks=[1, 2.5, 4], xticklabels=["a", "b", "c"])

rawDescription: How to label certain x values

description: Label certain x values


code:
import ipaddress
ipaddress.ip_address('192.0.43.10') in ipaddress.ip_network('192.0.0.0/16')

rawDescription: Python - ip <-> subnet match?

description: Python - ip <-> subnet match


code:
parser = argparse.ArgumentParser(usage='custom usage')
sp = parser.add_subparsers(dest='cmd')
sp.required = True
spp = sp.add_parser('cmd1')
act_g = spp.add_argument('-g')
act_wid = spp.add_argument('--wid')
act_w1 = spp.add_argument('--w1')
act_w2 = spp.add_argument('--w2')

@spp.crosstest # decorator to register this function with spp
def test1(spp, seen_actions, *args):
    # seen_actions - list of actions that were seen by parser
    if 1==len({act_w1, act_w2}.intersection(seen_actions)):
        # error if only one of these was seen
        parser.error('-w1 and -w2 always appear together')
@spp.crosstest
def test2(spp, seen_actions, *args):
    # required mutually exclusive wid and (w1,w2 group)
    if act_wid in seen_actions:
        if act_w1 in seen_actions or act_w2 in seen_actions:
            parser.error('-wid and (-w1 -w2) are mutually exclusive')
    elif act_w1 not in seen_actions:
        parser.error('wid or (w1 and w2) required')
@spp.crosstest
def test3(spp, seen_actions, *args):
    # is this the simplest logical way of expressing this?
    if act_g not in seen_actions and act_wid in seen_actions:
        parser.error('not g, so not wid')
args = parser.parse_args()

rawDescription: Python argparse: Complex Argument Parsing Scenario


code: "{}{}".format(subdomain + '.' if subdomain else '', fullDomain)

rawDescription: Conditionally parsing a string

description: Conditionally parsing a string


code:
from itertools import chain, izip
new_mac_tags = list(chain.from_iterable(izip(mac_tags, mac_tags)))

rawDescription: adding each member of an array again, right after itself

description: Adding each member of an array again, right after itself


code:
sorted_points = sorted(points)
new_xs = [point[0] for point in sorted_points]
new_ys = [point[1] for point in sorted_points]
new_xs
new_ys

rawDescription: Python: sort a list and change another one consequently


code: topiclist = [topic for (topic, tlist) in dictionary.iteritems() if word in tlist]

rawDescription: Find which dictionaries from a list contain word


rawDescription: How do I create aggregates by a column in pandas?

description: Create aggregates by a column in pandas


code:
def sample_view(request, *args, **kwargs):
    from datetime import date
    current_date = date.today()
    current_day = int(current_date.day) # force a cast to an int, just to be explicit
    return render_to_response("template", {'day_of_the_month': current_day })

rawDescription: get particular date in django template Django

description: Get particular date in django template Django


code:
def createfile():
    var = """#!/bin/sh
             echo ${test}
          """
    script_txt = ""

    for line in var:
        script_txt += line.lstrip(" ")

    return script_txt

v = createfile()

rawDescription: store formatted text in variable python

description: Store formatted text in variable python


code:
def rec_fac(n):
    if n == 1:
        return n
    else:
        return eval('n*rec_fac(n-1)')

rawDescription: How can I make a "Recursive Factorial" without using multiplication?

description: Make a "Recursive Factorial" without using multiplication


code:
def sliceImage(I, a, b, *arg, **kws):
    from scipy import linspace, asarray
    from scipy.ndimage import map_coordinates
    from scipy.linalg import norm
    dst = norm(asarray(b) - a) + 1
    return map_coordinates(I, [linspace(strt, end, dst)
                               for strt, end in zip(a, b)],
                           *arg, **kws)

rawDescription: Arbitrary image slice with python/numpy

description: Arbitrary image slice with python/numpy


code:
class Meta(type): pass
class Foo(object): pass
issubclass(Meta, type)
issubclass(Foo, type)

rawDescription: Determine if a class in python is a metaclass


code:
from collections import Counter
tokensI = Counter(value for value in contentsI.split()
                        if value not in [ 'unwanted1', 'unwanted2' ])
tokensO = Counter(value for value in contentsO.split()
                        if value not in [ 'unwanted1', 'unwanted2' ])

rawDescription: How to compare two files that have the same unsorted (and additional unimportant) content?

description: Compare two files that have the same unsorted (and additional unimportant) content


rawDescription: Comparing 3 lists in Python

description: Comparing 3 lists in Python


code: b = wx.BitmapButton(pane, -1, wx.Bitmap('buttons/my_beautiful_button.png'))

rawDescription: How to add an outline border to a widget?

description: Add an outline border to a widget


code: return sparse_mat, session_id

rawDescription: returning different datatypes from a function in python

description: Returning different datatypes from a function in python


code:
table_rows = []
for something in something_else:
    table_rows += ['\n', GetRow()]
sTable = ''.join(table_rows)

rawDescription: Why is variable1 += variable2 much faster than variable1 = variable1 + variable2?


code:
@gets_arg_from(the_list)
def print_func(word):
     return word

rawDescription: Decorator which conditionally activates another decorator?


code:
import numpy as np
import pylab as plt

N = 2000
total_bins = 10

# Sample data
X = np.random.random(size=N)*10
Y = X**2 + np.random.random(size=N)*X*10

bins = np.linspace(X.min(),X.max(), total_bins)
delta = bins[1]-bins[0]
idx  = np.digitize(X,bins)
running_median = [np.median(Y[idx==k]) for k in range(total_bins)]

plt.scatter(X,Y,color='k',alpha=.2,s=2)
plt.plot(bins-delta/2,running_median,'r--',lw=4,alpha=.8)
plt.axis('tight')
plt.show()

rawDescription: Running median of y-values over a range of x


code:
def merge(*iterators):
    """Merges a collection of iterators, returning a single iterator that yields
    the elements of the original iterators in non-decreasing order.  Each of
    the original iterators is assumed to yield its elements in non-decreasing
    order."""

    done = object()
    n = [next(it, done) for it in iterators]

    while any(v is not done for v in n):
        v, i = min((v, i) for (i, v) in enumerate(n) if v is not done)
        yield v
        n[i] = next(iterators[i], done)

rawDescription: how to use python iterators elegently

description: Use python iterators elegently


code:
translation_map = str.maketrans({"-": None})
to_compare = to_compare.translate(translation_map)

rawDescription: making difflib's SequenceMatcher ignore "junk" characters

description: Making difflib's SequenceMatcher ignore "junk" characters


code: (all, those, variables) = unpack('>6B9H2BH3I2HIH2B10H4I', data)

rawDescription: Unpacking data structure with Python

description: Unpacking data structure with Python


code: min(x for sublist in lst for x in sublist)

rawDescription: How to pick the smallest value in a list when an iterative process is applied to the list

description: Pick the smallest value in a list when an iterative process is applied to the list


rawDescription: random.sample and "selection order"

description: Random.sample and "selection order"


code: fout = [sys + " Weekly Summary.csv"]

rawDescription: Python 2.7.2. How to append specific lines from multiple files into one file.


code:
with open('data/myCSVfile.csv', 'w') as f:
    for line in newResult:
        f.write(newResult + '\n')

rawDescription: write a CSV file with Python after scraping text from website

description: Write a CSV file with Python after scraping text from website


code:
import numpy as np
data = np.arange(1, 7)
groups = np.array([0,0,1,2,2,1])

unique_groups = np.unique(groups)
sums = []
for group in unique_groups:
    sums.append(data[groups == group].sum())

rawDescription: Sum array by number in numpy

description: Sum array by number in numpy


code: return value1, value2     #returns a tuple

rawDescription: Python 3, Passing data from one function to another


code:
from testfixtures import log_capture

@log_capture()
def test_function(l):
    logger = logging.getLogger()
    logger.info('a message')
    logger.error('an error')

    l.check(
        ('root', 'INFO', 'a message'),
        ('root', 'ERROR', 'an error'),
        )

rawDescription: Writing a unit test for Python logger formatted output


rawDescription: Check string for multiple occurrence of character in Python


rawDescription: Dictionary __gt__ and __lt__ implementation


rawDescription: how to receive regex from command line in python

description: Receive regex from command line in python


code:
_yellow = _green = _red = lambda msg: msg
yellow, green, red = _yellow, _green, _red
if sys.stdout.isatty():
    try:
        from colors import yellow, green, red
    except ImportError:
        pass

rawDescription: Import ansicolor python functions and use them only terminal


code: part0, _, part2 = str.partition(' ')

rawDescription: How to pick certain elements of x-tuple returned by a function?

description: Pick certain elements of x-tuple returned by a function


rawDescription: What actually happens when broadcasting a NumPy array


code:
import lxml.html
data = """blah blah
bow bow
buh buh
"""
doc = lxml.html.document_fromstring(data)
for col in doc.cssselect('td'):
    style = col.attrib['style']
    if style=='padding: 20px':
        print(col.text.strip())

rawDescription: Finding inline style with lxml.cssselector


rawDescription: Spotfire IronPython script: Delete a data-table


code:
import invRegex
import inverse_regex
print(repr(''.join(invRegex.invert('.'))))
print(repr(''.join(inverse_regex.ipermute('.'))))

rawDescription: Generate random string from regex character set


rawDescription: modifying iterator in for loop in python

description: Modifying iterator in for loop in python


code:
class MyClass(MyNamedTuple):
    ...

rawDescription: Can a class inherit the properies of a namedtuple?


code:
class ConcurrentThingy:
    def __init__ (self):
        self.lock = Lock () # or RLock () if you want it to be reentrant

    def concurrentlyAccessedMethod (self, *args, **kwargs):
        with self.lock: doMeanStuff ()

rawDescription: Python Dictionaries and Threading Concurreny


rawDescription: adjusting floats to maintain high precision

description: Adjusting floats to maintain high precision


rawDescription: Convert DataFrame column type from string to datetime


code:
{x: freq for x,freq in dic.items() if freq > 1}
{x: freq for x,freq in dic.most_common(3)}

rawDescription: Selecting items in a dictionary using python


code:
z = pd.ewma(x, com=a/(1.0-a), adjust=False)
print(z)

rawDescription: Pandas EWMA not working as expected

description: Pandas EWMA not working as expected


code:
cp0 = r*np.cos(phi[i])
sp0 = r*np.sin(phi[i])

rawDescription: Rounding the edges of a cylinder in matplotlib poly3D


code:
with open(csvfile, "w") as csvfile:
    link_writer = csv.writer(csvfile)
    for row in Products:
        cells = row.find_all('td')
        data = {
            'description' : cells[0].get_text(),
            'price' : cells[1].get_text()
        }
       # write what you need

rawDescription: Exporting Beautiful Soup table scrape results to CSV


code:
frag = oneOf("yes no")
flowTcp = ("in_port" + LBRACE + in_port("in_port") + RBRACE + COMMA +
            "eth" + LBRACE +
                "src" + EQUAL + macAddress("src") + COMMA +
                "dst" + EQUAL + macAddress("dst") +
                RBRACE + COMMA +
            Optional("eth_type" + LBRACE + eth_type("eth_type") + RBRACE + COMMA) +
            Optional("arp" + LBRACE +
                "sip" + EQUAL + ipAddress("sip") + COMMA +
                "tip" + EQUAL + ipAddress("tip") + COMMA +
                "op" + EQUAL + op("op") + COMMA +
                "sha" + EQUAL + macAddress("sha") + COMMA +
                "tha" + EQUAL + macAddress("tha") +
                RBRACE + COMMA) +
            Optional("ipv4" + LBRACE +
                "src" + EQUAL + ipAddress("src") + COMMA +
                "dst" + EQUAL + ipAddress("dst") + COMMA +
                "proto" + EQUAL + proto("proto") + COMMA +
                "tos" + EQUAL + tos("tos") + COMMA +
                "ttl" + EQUAL + ttl("ttl") + COMMA +
                "frag" + EQUAL + frag("frag") +
                RBRACE + COMMA) +
            Optional("tcp" + LBRACE +
                "src" + EQUAL + src("srcPkt") + COMMA +
                "dst" + EQUAL + dst("dstPkt") +
                RBRACE) +
            "packets" + COLON + packets("packets"))

rawDescription: extract data from ovs dump-flow using pyparsing

description: Extract data from ovs dump-flow using pyparsing


code:
import numpy as np

def pagerank(M, d, v_quadratic_error):
    count = 0
    N = M.shape[1]
    while True:
        v = np.random.rand(N, 1)
        if (v != 0).all(): break
    v = v / np.linalg.norm(v)
    R = d * M + ((1 - d) / N * np.ones((N, N)))
    while True:
        last_v = v
        v = np.dot(R, v)
        count += 1
        print('iteration # {}: {}'.format(count, np.isfinite(v)))
        if np.linalg.norm(v - last_v, 2) <= v_quadratic_error: break
    return v

M = np.array(np.mat('0 0 0 0 1 ; 0.5 0 0 0 0 ; 0.5 0 0 0 0 ; 0 1 0.5 0 0 ; 0 0 0.5 1 0'))
print(pagerank(M, 0.80, 0.001))

rawDescription: PageRank python implementation, algorithm


code:
pdb.runeval("[myfunc(x) for x in range(3)]", globals(), locals())
# or with ... some_module.globals())

rawDescription: Trace an arbitrary Python command issued in PDB?


code:
import matplotlib.pyplot as plt
plt.show()

rawDescription: Repeat pandas dataframe over time

description: Repeat pandas dataframe over time


code:
import wx

class GUI(wx.Frame):
    def __init__(self, parent, id, title):
        screenWidth = 500
        screenHeight = 400
        screenSize = (screenWidth,screenHeight)
        wx.Frame.__init__(self, None, id, title, size=screenSize)
        self.Bind(wx.EVT_CLOSE, self.closeWindow)  #Bind the EVT_CLOSE event to closeWindow()

    def closeWindow(self, event):
        self.Destroy() #This will close the app window.

if __name__=='__main__':
    app = wx.App(False)
    frame = GUI(parent=None, id=-1, title="Problem Demo-PSS")
    frame.Show()
    app.MainLoop()

rawDescription: Exit button doesn´t work - wxpython

description: Exit button doesn´t work - wxpython


code: list_func = [f1, f2, f3]

rawDescription: Python doubts about calling func and Syntax


code:
from pyspark.mllib.linalg import VectorUDT
from pyspark.sql.types import StructType, StructField

schema = StructType([StructField("features", VectorUDT(), True)])
row = Row("features")
result.map(lambda x: row(DenseVector(x))).toDF(schema)

rawDescription: Encode and assemble multiple features in PySpark


code:
from itertools import permutations
from numpy import sqrt

def permuts(S,N):
    def factorize(N):
        return [ (i, N//i) for i in xrange(1,int(sqrt(N))) if N%i == 0 ]

    factors = factorize(N)
    for i,j in factors:
        for p in permutations(str(i)+str(j)):
            if ' '.join(map(str, p)) == S:
                return j,i

rawDescription: FInd Possible Permutations of Given Numbers whose Multiplication Gives the Required Number


code: ['EPCOR LXO EPCOR', 'S MSKA EPCOR', 'NA JPP']

rawDescription: Can using a dictionary on standard letters work in the same or similar way using a text file?


code:
parse_string = ("http://www.google.pl/search?q=%s&restofurl" %
               '%2C'.join(tag.strip() for tag in tags_list))
parse_string

rawDescription: Parsing a list into a url string

description: Parsing a list into a url string


code:
Local._get_collection().aggregate([
    # Match the documents that have the required user
    { "$match": {
         "points.user": user
    }},

    # Filter the array in place
    { "$project": {
        "token": 1,
        "points": {
            "$setDifference": [
                {
                    "$map": {
                       "input": "$points",
                       "as": "el",
                       "in": {
                           "$cond": [
                               { "$eq": [ "$$el.user", user ] },
                               "$$el",
                               false
                           ]
                       }
                    }
                },
                [false]
            ]
        }
     }}
])

rawDescription: get filtered embeded elements from all class on mongoengine

description: Get filtered embeded elements from all class on mongoengine


code:
x = lambda: 'x()'
y = lambda: 'y()'
mydecorator = lambda f: lambda *arg, **kwarg: f(*arg, **kwarg) + ' decorated!'
targets = {id(x): mydecorator(x)}
def mapper(obj):
    if id(obj) in targets:
        return targets[id(obj)]
    else:
        return obj
@hijack(mapper)
def f():
    return (x(), y())
f()

rawDescription: How to apply a decorator to subroutines in python

description: Apply a decorator to subroutines in python


code: mn = arr.mean(0).mean(0)

rawDescription: Sum of colorvalues of an image

description: Sum of colorvalues of an image


rawDescription: Numpy: efficient way to generate combinations from given ranges


code:
a='value1, value2, value3(a, b, c)'
split=a.split(', ')
result=[]
for ent in split:
    if ent.find('(', 0, len(ent))!=-1:
        temp=''
        for ent2 in split[split.index(ent):]:
            if ent2.find('(', 0, len(ent))!=-1:
                temp=temp+ent2
            else:
                temp=temp+','+ent2
                split.remove(ent2)
            #May need a check whether ) has not been reached yet, in which case don't add the items.
        result.append(temp)
    else:
        result.append(ent)

rawDescription: Python nested comma in csv

description: Python nested comma in csv


code:
try:
  random.sample(range(1, 2), 3)
except ValueError:
  print('Sample size exceeded population size.')

rawDescription: Python, Generate 'n' unique random numbers within a range


rawDescription: loop trough a python list of tuples and change a value

description: Loop trough a python list of tuples and change a value


code:
from heapq import merge

def keyfunc(s):
    return int(s.split()[1])

with open('file1') as fd1, open('file2') as fd2:
    for line in merge(fd1, fd2, key=keyfunc):
        print(line)

rawDescription: merge two files sorted numerically by an integer in each line without reading into memory and without sorting

description: Merge two files sorted numerically by an integer in each line without reading into memory and without sorting


rawDescription: Python libraries to calculate human readable filesize from bytes?


rawDescription: Random Trees in OpenCV from python

description: Random Trees in OpenCV from python


code:
import datetime
sastime = 1716470000
epoch = datetime.datetime(1960, 1, 1)
print(epoch + datetime.timedelta(seconds=sastime))

rawDescription: Convert SAS numeric to python datetime

description: Convert SAS numeric to python datetime


code: list(list(parsed_sent) for parsed_sent in parser.raw_parse_sents(sent_tokenze(sentences)))

rawDescription: How to split sentences using the nltk.parse.stanford library

description: Split sentences using the nltk.parse.stanford library


code:
maximum = max(mylist)
if maximum < w:
    status = 'OK'
elif maximum < c:
    status = 'WARNING'
else:
    status = 'CRITICAL'

rawDescription: iterating list through multiple if statement in python

description: Iterating list through multiple if statement in python


code: MY_VARIABLE = 10**9

description: Cost of using 10**9 over 1000000000


rawDescription: Generating a string with python using loops with logic conditions issues against join function alternative?


rawDescription: Function statement() that outputs the sum of the deposit and the sum of the withdraw


code:
for ns in Ns:
    for ops in Ops:
        result = ns[0]
        result = op24(result, ops[0], ns[1])
        result = op24(result, ops[1], ns[2])
        result = op24(result, ops[3], ns[3])
        if result == 24:
            return True

    for ops in Ops:
        result1 = op24(ns[0], ops[0], ns[1])
        result2 = op24(ns[2], ops[1], ns[3])
        result = op24(result1, ops[2], result2)
        if result == 24:
            return True

# none of the permutations were equal to 24
return False

rawDescription: 24 game using Python

description: 24 game using Python


code:
server.fetch([456], ['BODY[HEADER.FIELDS (FROM)]'])
# {456: {'BODY[HEADER.FIELDS (FROM)]': 'From: Facebook <register+mr4k25sa@facebookmail.com>\r\n\r\n', 'SEQ': 456}}

rawDescription: Using IMAPClient how do you view the Senders address?


code:
q = (
    session
    .query(A)
    .filter(or_(
        A.stuff.any(Stuff.id == X),  # here Stuff will refer to `A.stuff`
        A.more_stuff.any(Stuff.id == X),  # here Stuff will refer to `A.more_stuff`
    ))
)

rawDescription: SQLAlchemy: how to select if in one list or another list?


code: parseTags("tHiS iS a tAg, \t\n!&#^ , secondcomment , no!punc$$, ifNOSPACESthenPRESERVEcaps")

rawDescription: Python regular expression to remove space and capitalize letters where the space was?


code: "Mary,Jade,Jenn\n".split(',', 1)

rawDescription: Indexing lines of text in a .txt file

description: Indexing lines of text in a .txt file


code: last_ob = max(candidates, key=lambda ob: ob['realtime_start'])

rawDescription: Find dictionary with greatest date less than or equal to variable, return value


code: ["%03d" % i for i in range(121)]

rawDescription: Generate numbers with 3 digits

description: Generate numbers with 3 digits


code: del Singleton._instances[MyClass]

rawDescription: How to deregister a class entry from Metaclass?

description: Deregister a class entry from Metaclass


rawDescription: searching for element in a dictionary key

description: Searching for element in a dictionary key


code:
for idx in range(len(start_list)):  # the range is created just once
    start_list.append(start_list[idx] ** 2)

rawDescription: How do I square each item in a list using append?

description: Square each item in a list using append


code:
columns = ['Klasa', 'E Hene', 'E Marte', 'E Merkurre', 'E Enjte', 'E Premte']
for column in columns:
    model.addColumn(column)

rawDescription: How can I have the tkintertable table's columns sorted the way they are in the dictionary?

description: Have the tkintertable table's columns sorted the way they are in the dictionary


code:
@property
def age(self):
    return ... # return the calculated years since date_of_birth

rawDescription: Python Django: in view is it better to add properties to an object or make a dictionary of the data?


code:
import requests
from bs4 import BeautifulSoup
response = requests.get("http://www.boxofficemojo.com/movies/?id=ironman3.htm")
soup = BeautifulSoup(response.content)
soup.find(text="Genre: ").next_sibling.text

rawDescription: BeautifulSoup webcrawling: How to get piece of text


code: result = db.test.find_one({"id":"test"},{'_id':0, 'specific_array':1})

rawDescription: Get array count of specific document in Pymongo


code: t = soup.findAll('table', {'class': 'data'})

rawDescription: How to use Beautiful Soup to select only one of multiple tables

description: Use Beautiful Soup to select only one of multiple tables


code:
with open(outname, "w") as outfile:
    in_csv = csv.reader(infile)
    out_csv = csv.writer(outfile, lineterminator="\n")

rawDescription: Regular Expression, Matrix, CSV in Python


rawDescription: How would I make a car move the direction it's pointing (After use of pygame.translation.rotate)


code:
from itertools import zip_longest

def foo():
    yield from (i for pair in zip_longest(range(10), range(10, 22))
                  for i in pair if i is not None)

rawDescription: Is there a way in python to change the order in which yield from get's processed?


code:
if place.data == conn_1 and conn_1 != conn_2:
    # place is the Place instance described by conn_1.
    # Let's connect it to conn_2!
    place.connected_to.add(conn_2)

rawDescription: Checking if ForeignKeys are equal to one another


rawDescription: Python: split bytes with a hexadecimal delimiter


code:
go
click
go
text
5

rawDescription: Method chaining with asyncio coroutines

description: Method chaining with asyncio coroutines


code:
def _is_identical_aux(self, node1, node2):
    if node1 is None and node2 is None:
        return True
    if node1 is not None and node2 is not None:
        return ((node1._value == node2._value) and
                _is_identical_aux(node1.left, node2.left) and
                _is_identical_aux(node1.right, node2.right))
    return False

rawDescription: python-Implement and test the following BST method

description: Python-Implement and test the following BST method


code:
def dictfetchall(cursor):
    "Returns all rows from a cursor as a dict"
    desc = cursor.description
    return [dict(zip([col[0] for col in desc], row))
           for row in cursor.fetchall()]

cursor = connection.cursor()
cursor.execute("SELECT * FROM app_person <YOUR JOINS HERE>");
values =  dictfetchall(cursor)

rawDescription: Queryset object

description: Queryset object


code:
df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55

rawDescription: Add new column in Pandas DataFrame Python


code: ts

rawDescription: python pandas timeseries: assign value to time (currently omitted from index)

description: Python pandas timeseries: assign value to time (currently omitted from index)


code:
class Tree:

    def __init__(self, name, branches):
        self.name = name
        self.branches = branches

rawDescription: Extract parent and child node from python tree representation


code:
class T2( object ):
    class C2( object ):
        __doc__ = 'Inner class doc string'

rawDescription: Python Docstrings in Subclasses

description: Python Docstrings in Subclasses


code:
def get_xbits_list(num, x):
    mask = 2**x - 1
    return map(lambda i: (num >> (i * x)) & mask, reversed(xrange(32/x)))

rawDescription: How to get each Xbits from a int with python

description: Get each Xbits from a int with python


code: [x for x, y in zip(a, b) if y]

rawDescription: Mapping an array of booleans to an array of values and returning True instances in Python


code:
s = r'{\x7f5  x'
s
s.encode('latin1').decode('unicode_escape')

rawDescription: How to read interpreted data strings in Python?

description: Read interpreted data strings in Python


rawDescription: Permute rows and columns of a matrix

description: Permute rows and columns of a matrix


code:
if (dem_arr[randx, randy] > -100):
    ...
else:
    ...

rawDescription: Python: How to return a result from a conditional and then have it re-enter the conditional statement


rawDescription: What is the recommended way of allocating memory for a typed memory view?


code: Database.data = self.data[1:]

rawDescription: Confusion over how to share and modify class level data between instances.


code: datalists = [d.tolist() for d in datasets]

rawDescription: Python for & if loop not working?

description: Python for & if loop not working


code:
# in the __init__ function
self.table.itemDoubleClicked.connect(self.onItemDoubleClick)

# in onItemDoubleClicked function
def onItemDoubleClicked(self, item):
    # Every data has a role, you can specify your own (it's an integer) as long as it's greater than UserRole. Others are used internally, like DisplayRole and some others you can find in the QtCore package.
    # You can use data with other widgets also, not just TableWidgets.
    user = item.data(QtCore.Qt.UserRole+1)
    # you get a session however you want, then delete the user. This object is the same as the one you passed earlier when creating the item, it can be whatever you like.
    session.delete(user)
    session.commit()

rawDescription: Design of the 'model' for QTableView in PySide + SQLAlchemy.


code:
q = Song.query.filter(Song.artist.has(Artist.genres.any(Genre.name == 'rock')))
assert len(q.all()) == 2

rawDescription: SQLAlchemy: filter many-to-one relationship where the one object has a list containing a specific value


code:
from reportlab.platypus import BaseDocTemplate
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import A4
from reportlab.platypus import Paragraph

class MyDocTemplate(BaseDocTemplate):
    """Override the BaseDocTemplate class to do custom handle_XXX actions"""

    def __init__(self, *args, **kwargs):
        BaseDocTemplate.__init__(self, *args, **kwargs)

    def afterPage(self):
        """Called after each page has been processed"""

        # saveState keeps a snapshot of the canvas state, so you don't
        # mess up any rendering that platypus will do later.
        self.canv.saveState()

        # Reset the origin to (0, 0), remember, we can restore the
        # state of the canvas later, so platypus should be unaffected.
        self.canv._x = 0
        self.canv._y = 0

        style = getSampleStyleSheet()

        p = Paragraph("This is drawn after the page!", style["Normal"])

        # Wraps and draws the paragraph onto the canvas
        # You can change the last 2 parameters (canv, x, y)
        p.wrapOn(self.canv, 2*inch, 2*inch)
        p.drawOn(self.canv, 1*inch, 3*inch)

        # Now we restore the canvas back to the way it was.
        self.canv.restoreState()

rawDescription: Conditional page break in reportlab

description: Conditional page break in reportlab


rawDescription: Adding 'n' values in list using for-loop and step-loop for that 'n' values in python


code:
import win32api, win32con
def CopyBox(x, y):
    time.sleep(.2)
    win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_EXTENDEDKEY, 0)
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
    win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_KEYUP, 0)

rawDescription: Generating Mouse-Keyboard combination events in python


code:
def home():
    return 'home'

app.add_url_rule('/', None, home, {})

rawDescription: How to centralise routing in Flask using a single file instead of decorators?

description: Centralise routing in Flask using a single file instead of decorators


code: df = pd.DataFrame(A.toarray())

rawDescription: transform scipy sparse csr to pandas?

description: Transform scipy sparse csr to pandas


code:
def roll(sides, num_of_dices):
    return [roll_one_dice(sides) for i in range(num_of_dices)]

rawDescription: How does xrange() work inside of a while loop?


code:
phrases = {"1931-125", "699-126", "1851-127"}

for s in phrases:
    make_link(TEXT_W, s, s+".pdf") #make a link to same name with .pdf added to end.

rawDescription: Converting a string automatically into a link to a pdf document


code:
def lenRecur(s):
    def characters_only(s):
        return ''.join([c for c in s if c.isalpha()])
    def len_recursive(s):
        if not s:
            return 0
        return 1 + len_recursive(s[1:])
    return len_recursive(characters_only(s))

lenRecur('The Quick Brown Fox')

rawDescription: Global variables in recursion. Python

description: Global variables in recursion. Python


rawDescription: Encoding in Python - non-English characters into a URL


rawDescription: python: find and replace numbers < 1 in text file

description: Python: find and replace numbers < 1 in text file


code:
from collections import defaultdict
lst = [{'year': 2013, 'snow': 64.8, 'month': 1},
       {'year': 2013, 'snow': 66.5, 'month': 2},
       {'year': 2013, 'snow': 68.3, 'month': 12},
       {'year': 2013, 'snow': 68.8, 'month': 3},
       {'year': 2013, 'snow': 70.9, 'month': 11},
       {'year': 2012, 'snow': 76.8, 'month': 7},
       {'year': 2012, 'snow': 79.6, 'month': 5},
       {'year': 1951, 'snow': 86.6, 'month': 12}]
snowfall = defaultdict(float)
for info in lst:
    snowfall[info['year']] += info['snow']

snowfall = [{'year': year, 'totalsnow': snowfall[year]}
            for year in sorted(snowfall, reverse=True)]
from pprint import pprint
pprint(snowfall)

rawDescription: sum of one value in the list of dictionary based on one key in dict

description: Sum of one value in the list of dictionary based on one key in dict


rawDescription: Handle Nan when using Pandas ExcelWriter in python


code:
while True:
    r = log_queue.get()
    my_handler.emit(r)

rawDescription: Why doesn't TimedRotatingFileHandler work properly and how to solve this issue(rotation is working, but missing logging lines) when log lines


code:
import re

last_post = soup.find('dt', text=re.compile('Last Post'))
last_post.find_next_sibling('dd').span.string

rawDescription: Unique attributes for certain data

description: Unique attributes for certain data


code:
import platform
platform.mac_ver()

rawDescription: How to detect Mac OS version using Python?

description: Detect Mac OS version using Python


code:
with open("your_file", "w") as f:
    for key,value in my_dict.items():
        f.write("{}:{}".format(key, ",".join(value)))

rawDescription: How to dynamically add keys and values in python

description: Dynamically add keys and values in python


rawDescription: Python3.4 - math with index numbers

description: Python3.4 - math with index numbers


code:
HTML2Markdown.new('
HTMLcode
').to_s

rawDescription: How to run Ruby/Python scripts from inside PHP passing and receiving parameters?

description: Run Ruby/Python scripts from inside PHP passing and receiving parameters


code:
import requests

params = {"SC":"132","vrm":"foobar"}

req = requests.get("https://www.vehiclecheck.co.uk/",params=params)

print(req.content)

rawDescription: manipulating web forms in python

description: Manipulating web forms in python


code:
ops1 = {
        "1": print("1"), # this value is actually the value returned by print
        "2": print("2"),
        "4": print("4")
} # when the dictionary is created, everything in it is evaluated,
# so it executes those print calls
# that's why you see all three printed

lis = [1, 2, 3]

for x in range(0, len(lis)-1): # this includes 0 and 1
    if (lis[x] in ops1.keys()): # lis[0] is 1 and lis[1] is 2
        ops1.get(x) # look for 0 and then 1 in the dictionary

rawDescription: Python, run functions from lookup table

description: Python, run functions from lookup table


code:
l = []
for y in range(7):
    l.append(list(permutations('1379', y)))

rawDescription: Multi-variable List Comprehension

description: Multi-variable List Comprehension


code:
def are_items_equal(a, b):
    # First the guard clause: if the first list is empty,
    # return True if the second list is empty too, False otherwise
    if not a:
        return not b

    # There is now at least 1 item in list a
    # Perform a linear search in the b list to find a[0]
    # (could have used a "for" loop, but I assumed here this was
    # forbidden too)
    ib = 0;
    while ib < len(b):
        if a[0] == b[ib]:
            # At this point, we know that at index `ib` in list `b`
            # there is the same item as in `a[0]`
            # Both list match if the "rest" of those two lists match too
            # Check that by performing a recursive call to are_items_equal
            # (discarding the pair matched at this step)
            return are_items_equal(a[1:], b[:ib]+b[ib+1:])
        ib += 1

    # You only reach this point when `a[0]` was not found
    # in the `b` list.
    return False

rawDescription: how to make a function which tells if two lists are equivalent in python

description: Make a function which tells if two lists are equivalent in python


rawDescription: Find previous occurrence of an element

description: Find previous occurrence of an element


code:
def getKey():
    print("Enter the key you want to use to decrypt/encrypt the message")
    key = int(input()) # key input
    if key >= 1 and key <= 26: #checking if key is in between range
        return key #giving back the key
    else: # this should run whenever the input is invalid
        print ("The key must be inbetween 1 and 26")
        return getKey() # Recursion, to restart the function

rawDescription: Recursion in function causing return variable to equal 'None'


rawDescription: Flatten the results of a group by in a python dataframe after printing the grouped instance counts


rawDescription: How can I get the product of all elements in a one dimensional numpy array

description: Get the product of all elements in a one dimensional numpy array


rawDescription: Use multiple functions at once on a list


code:
# Tkinter in Python 2.7 & tkinter in 3.2
import Tkinter as tk

class GUI(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        bF = tk.Frame(self, bd=8, relief='sunken')
        bF.pack(expand='true', fill='x')
        changeButton = tk.Button(bF, text='Change', bd=4, fg='white',
                                relief='groove', activebackground='green',
                                command=self.change_label)
        changeButton.pack()

        self.entryLabel = tk.Label(self, text='Hello')
        self.entryLabel.pack()

        self.mEntry = tk.Entry(self, bd=4, relief='sunken')
        self.mEntry.pack()

    def change_label(self):
        data = self.mEntry.get()
        self.entryLabel.configure(text=data)

gui = GUI()
gui.mainloop()

rawDescription: How to call an action when a button is clicked in Tkinter

description: Call an action when a button is clicked in Tkinter


code:
p = Pool()
processed = p.map(processItem, lst)

rawDescription: Multi threading read and write file using python


code:
#!/usr/bin/env python

# Python 2/3 compatibility
from __future__ import print_function

import numpy as np
import cv2

def init_feature():
    detector = cv2.BRISK_create()
    norm = cv2.NORM_HAMMING
    matcher = cv2.BFMatcher(norm)
    return detector, matcher

def filter_matches(kp1, kp2, matches, ratio = 0.75):
    mkp1, mkp2 = [], []
    for m in matches:
        if len(m) == 2 and m[0].distance < m[1].distance * ratio:
            m = m[0]
            mkp1.append( kp1[m.queryIdx] )
            mkp2.append( kp2[m.trainIdx] )
    p1 = np.float32([kp.pt for kp in mkp1])
    p2 = np.float32([kp.pt for kp in mkp2])
    kp_pairs = zip(mkp1, mkp2)
    return p1, p2, kp_pairs

def explore_match(win, img1, img2, kp_pairs, status = None, H = None):
    h1, w1 = img1.shape[:2]
    h2, w2 = img2.shape[:2]
    vis = np.zeros((max(h1, h2), w1+w2), np.uint8)
    vis[:h1, :w1] = img1
    vis[:h2, w1:w1+w2] = img2
    vis = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)

    if H is not None:
        corners = np.float32([[0, 0], [w1, 0], [w1, h1], [0, h1]])
        corners = np.int32( cv2.perspectiveTransform(corners.reshape(1, -1, 2), H).reshape(-1, 2) + (w1, 0) )
        cv2.polylines(vis, [corners], True, (0, 0, 255))

    cv2.imshow(win, vis)
    return vis

if __name__ == '__main__':

    img1 = cv2.imread('rB4Yy_big.jpg' , 0)
    img2 = cv2.imread('ZjBAA.jpg', 0)
    detector, matcher = init_feature()

    kp1, desc1 = detector.detectAndCompute(img1, None)
    kp2, desc2 = detector.detectAndCompute(img2, None)

    raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2)
    p1, p2, kp_pairs = filter_matches(kp1, kp2, raw_matches)
    if len(p1) >= 4:
        H, status = cv2.findHomography(p1, p2, cv2.RANSAC, 5.0)
        print('%d / %d  inliers/matched' % (np.sum(status), len(status)))
        vis = explore_match('find_obj', img1, img2, kp_pairs, status, H)
        cv2.waitKey()
        cv2.destroyAllWindows()
    else:
        print('%d matches found, not enough for homography estimation' % len(p1))

rawDescription: Resolution Manipulation for Template Matching in OpenCV


code:
import csv
from itertools import islice

outerdict = defaultdict(lambda: defaultdict(list))

with open('ImmgenCons_all_celltypes_MicroarrayExp.csv', 'rb') as infh:
    reader = csv.reader(infh, skipinitialspace=True)
    # first row contains metadata we need
    celltypes = next(reader, [])[3:]

    # next two rows can be skipped
    next(islice(infh, 2, 2), None)

    for row in reader:
        name = row[1]
        for celltype, value in zip(celltypes, row[3:]):
            outerdict[name][celltype].append(float(value))

rawDescription: Python idiom for creating dict of dict of list


rawDescription: Return function name in python?

description: Return function name in python


code:
class Profile(models.Model):
    user = models.OneToOneField(User)
    phone = models.CharField(max_length=255, blank=True, null=True, verbose_name='phone')
    description = models.TextField(blank=True, verbose_name='descripction')
    ...
    ...
    class Meta:
        ordering = ['user']
        verbose_name = 'user'
        verbose_name_plural = 'users'

rawDescription: Django: Add another field to django-registration


code: sorted(mycount.items(), key=lambda kv: [c[1] for c in kv[1].most_common()], revers=True)

rawDescription: How can I sort data in python by the specific part of data?

description: Sort data in python by the specific part of data


code:
r = np.arange(24).reshape(4,6)
mask1 = (r>=8) & (r<=16)
res1 = r[mask1]*0.2
I,J = np.where(mask1)

rawDescription: How can I create a sparse matrix instead of a dense one in this program?

description: Create a sparse matrix instead of a dense one in this program


rawDescription: Query CSV files maintaining foreign key relationship? Is this possible?


rawDescription: How to trigger event every time text ctrl input complete?

description: Trigger event every time text ctrl input complete


rawDescription: creating a numpy array filled with a character

description: Creating a numpy array filled with a character


code: index = np.arange(df.index.values.min(), df.index.values.max() + 1)

rawDescription: Python Pandas value-dependent column creation


code: c_layer_points = models.layer_points.objects.filter(location_id=c_location.pk, season_id=c_season.pk, line_path_id=c_line_path.pk,radar_id=c_radar.pk, layer_id__in=c_layer_pks, gps_time__gte=start_gps, gps_time__lte=stop_gps).values_list('gps_time', 'twtt')

rawDescription: Most Efficient Way to get list of values from Django Queryset


code: input("Press Enter to exit")

rawDescription: Python time.sleep closes terminal

description: Python time.sleep closes terminal


code:
import xively

from os import environ
from hashlib import sha1
from binascii import a2b_hex
import hmac

secret = environ['XIVELY_PRODUCT_SECRET']
serial = environ['XIVELY_DEVICE_SERIAL_NUMBER']

activation = hmac.new(a2b_hex(secret), serial, sha1).hexdigest()

creds = xively.Client(key=None).get('/v2/devices/'+activation+'/activate').json()

xi_feed = xively.XivelyAPIClient(creds['apikey']).feeds.get(creds['feed_id'])

rawDescription: Xively: how to activate a device with the python api?


code:
def time2algorithms(sound, number=10000):
    t = time.time()
    for i in range(number):
        normal(sound)
    print(time.time() - t)
    t = time.time()
    for i in range(number):
        onlyMax(sound)
    print(time.time() - t)

rawDescription: timing two algorithms (python) using timeit or time

description: Timing two algorithms (python) using timeit or time


code:
# this will read from the stdin
import sys
for line in sys.stdin:
   print(line)

rawDescription: how to take a file as input stream in Python

description: Take a file as input stream in Python


rawDescription: Palindrome generator

description: Palindrome generator


code:
def param_dict_decorator(self, func):
    def wrapper(*args, **kw):
        self.instance.param_dict['a'] = self.composite_param_dict['a']
        return func(*args, **kw)
    return wrapper

rawDescription: Using decorators in python to build a complex composite class from a set of simple component classes


code:
class Default(Base):
    default_shapes = [Rectangle, Circle, Sphere]
    def __init__(self):
        self.shapes = [shape() for shape in self.__class__.default_shapes]

rawDescription: Using reflection to peep into a module and its classes


code: word_counts =pd.DataFrame(X.todense(),columns = vect.get_feature_names())

rawDescription: What is an efficient data structure for tokenized data in Python?


code:
from my_class import MyClassA

ca = MyClassA()

rawDescription: Importing an own python file, Class not defined


code:
import re
text = "Serial: 523524234235"
m = re.search(r'Serial: (\d+)', text)
m.group(1)

rawDescription: Extract data using regular expressions in python


code: virtualenv -p /path/to/python3 /path/to/virtualenv

rawDescription: How to use Django with Python 3 in an existing older venv?

description: Use Django with Python 3 in an existing older venv


rawDescription: how to sort files by the value of a dictionary using python

description: Sort files by the value of a dictionary using python


code:
import timeit
parsetime = timeit.timeit("mins = int(s[:-3]) * 60 + int(s[-2:])", "s='02:40'", number=100000) / 100000
parsetime

rawDescription: Parsing hh:mm in Python

description: Parsing hh:mm in Python


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

def arc_patch(center, radius, theta1, theta2, ax=None, resolution=50, **kwargs):
    # make sure ax is not empty
    if ax is None:
        ax = plt.gca()
    # generate the points
    theta = np.linspace(np.radians(theta1), np.radians(theta2), resolution)
    points = np.vstack((radius*np.cos(theta) + center[0],
                        radius*np.sin(theta) + center[1]))
    # build the polygon and add it to the axes
    poly = mpatches.Polygon(points.T, closed=True, **kwargs)
    ax.add_patch(poly)
    return poly

rawDescription: How to draw a filled arc in matplotlib

description: Draw a filled arc in matplotlib


code:
road = ['foo', 'bar']
distance = [1,2]
dict(zip(road,distance))

rawDescription: How to store the values of two lists in a single dictionary where values of first list is a key and the values of second list are attributes?

description: Store the values of two lists in a single dictionary where values of first list is a key and the values of second list are attributes


code:
#!/bin/bash
#/path/to/run-hourly
run-parts /path/to/hourly/jobs

rawDescription: Cronjobs per package

description: Cronjobs per package


rawDescription: What's the fastest way to get a random element from a tuple? (python)


rawDescription: Create multiple list with different variables


code:
foo
bar

rawDescription: Python decorator with optional argument (which is function)


rawDescription: Error in RK4 algorithm in Python

description: Error in RK4 algorithm in Python


code:
import collections
import functools
import types

def decorateAll(decorator):
    class MetaClassDecorator(type):

        def __new__(meta, classname, supers, classdict):
            for name, elem in classdict.items():
                if type(elem) is types.FunctionType:
                    classdict[name] = decorator(classdict[name])
            return type.__new__(meta, classname, supers, classdict)
    return MetaClassDecorator

class Counter(object):
    def __init__(self, fun):
        self.fun = fun
        self.cache = {None: self}
        self.count = collections.defaultdict(int)

    def __get__(self, obj, cls=None):
        if obj is None:
            return self

        try:
            return self.cache[obj]
        except KeyError:
            pass

        print('Binding {} and {}'.format(self.fun, obj))
        cex = self.cache[obj] = functools.partial(self.__call__, obj)
        return cex

    def __call__(self, obj, *args, **kwargs):
        print("args:", obj, *args, **kwargs)
        self.count[obj] += 1
        print("{0} Exec {1} times".format(self.fun.__name__, self.count[obj]))
        return self.fun(obj, *args, **kwargs)

class Account(object, metaclass=decorateAll(Counter)):

    def __init__(self, initial_amount):
        self.amount = initial_amount

    def withdraw(self, towithdraw):
        self.amount -= towithdraw

    def deposit(self, todeposit):
        self.amount += todeposit

    def balance(self):
        return self.amount

a = Account(33.5)

print(a.balance())

rawDescription: Metaclass which decorate all the class methods using two different decorator implementation


code:
#instead of
#risky_method(1,2,'x')
not_so_risky_method = try_x_times(3, (MyError,), myError2, risky_method)
not_so_risky_method(1,2,'x')

#or just
try_x_times(3, (MyError,), myError2, risky_method)(1,2,'x')

rawDescription: Repeat Python function call on exception?


rawDescription: Grab unique tuples in python list, irrespective of order


rawDescription: Saving numpy arrays as txt file [Beginner]


rawDescription: Reverse mapping on nested dictionary

description: Reverse mapping on nested dictionary


code:
funcs = {'sin': sin, 'cos': cos, 'tan': tan}
func = funcs[string]
func(x)

rawDescription: python evaluate commands in form of strings

description: Python evaluate commands in form of strings


code: [(i,j) for i in range(len(rows)-2,-1,-1) for (j) in range(i+1)]

rawDescription: Embedded for loops in python

description: Embedded for loops in python


code:
import signal
import pdb

def handler(signum, frame):
  pdb.set_trace()

signal.signal(signal.SIGQUIT, handler)

rawDescription: Drop into an Interpreter anytime in Python


rawDescription: numpy array partial sums with weights

description: Numpy array partial sums with weights


code:
working_monty = {}
for k, v in monty.items():
    for key in k:
        working_monty[key] = v

rawDescription: Python many-to-one mapping (creating equivalence classes)


code:
def onchange_standard_id(self, cr, uid, ids, standard_id,context = None):
        result = {'value': {}}
        student_list = []
        stud_obj = self.pool.get('fci.student')
        student_obj = self.pool.get('fci.standard')
        stud_id = stud_obj.search(cr, uid,[('standard_id', '=', standard_id)])
        student_data = student_obj.browse(cr, uid, standard_id, context=context)
        for id in stud_id:
            student_dict = {'student_id':id}
            student_list.append(student_dict)
        result['value']['attendance_line'] = student_list
        result['value']['group_id'] = [ g.id for g in student_data.groups_ids]
        return res

rawDescription: Why can't on_change refresh 2 fields is the same time?


code:
A
B
A[:,None,:]*B[:,:,None]
np.einsum('ijk,ij->ijk',A[:,None,:],B)

rawDescription: Multiply each row of one array with each element of another array in numpy


code:
from scipy.interpolate import interp1d

def trailing_diff(time, data, diff):
    ret = np.zeros_like(data)
    mask = (time - time[0]) >= diff
    interpolator = interp1d(time, data, kind='nearest')
    ret[mask] = data[mask] - interpolator(time[mask] - diff)
    return ret

rawDescription: speeding up moving time delta with irregular time intervals in a numpy array

description: Speeding up moving time delta with irregular time intervals in a numpy array


code:
def generate_auth_token(username=None, expiration=600):
    gen_serial = Serializer(secret_key, expires_in=expiration)
    data = {'username': username} if username is not None else {}
    return gen_serial.dumps(data)

rawDescription: Flask RESTful Destroy User Token

description: Flask RESTful Destroy User Token


code:
from itertools import product
from collections import Counter

def enumerate_rolls(die_n=2, max_num=6):
    for roll in product(range(1, max_num + 1), repeat=die_n):
        if len(set(roll)) != 1:
            yield roll
        else:
            for second_roll in product(range(1, max_num + 1), repeat=die_n):
                yield roll + second_roll

rawDescription: itertools dice rolls: doubles roll twice

description: Itertools dice rolls: doubles roll twice


code:
import shutil, re, os, fnmatch
directory = 'your_path'

for root, dirnames, filenames in os.walk(directory):
    for filename in fnmatch.filter(filenames, '*.dat'):
        filename_new = re.sub(r'_[A-Za-z0-9]{2}', '', filename)
        shutil.move(os.path.join(root, filename), os.path.join(root, filename_new))

rawDescription: Python - Truncate unknown file names

description: Python - Truncate unknown file names


code:
from functools import partial

self.FunctionBuffer["stack"].append(partial(self.ApplyFunction, arg1, arg2, arg3))

rawDescription: Is there a way to append a function with arguments into a list?


code: json.dumps({'some': {'nested': {'data': [b'\xe0\x01\x02\x03?']}}}, cls=MyJsonEncoder)

rawDescription: How can I override behavior of JSONEncoder for binary data?

description: Override behavior of JSONEncoder for binary data


code:
class Person(object):

    persons_dict = {}
    '''Creates a person object'''
    def __init__(self, firstname, lastname):
        self.lname = lastname.title()
        self.fname = firstname.title()
        fullname = "%s %s" % (self.fname, self.lname)
        Person.persons_dict[fullname] = self

rawDescription: Python: Checking whether an object already exists before creating a new one


rawDescription: Python: finding the intersection point of two gaussian curves


code:
def invert(d):
    """Turn {a:x, b:x} into {x:[a,b]}"""
    r = {}
    for k, v in d.items():
        r.setdefault(v, []).append(k)
    return r

rawDescription: Reverse multiple values with keys in dictionary


code:
def __init__(self):
    type(self).counter += 1

rawDescription: Parent changing child's attribute

description: Parent changing child's attribute


code:
import json

file = 'data.json';
data = json.loads(open(file).read())

print(data)

rawDescription: Feeding a Python array into a Perl script


code:
Characters = {
    'A': MethodA,
    'B': MethodB,
    # ...
}

rawDescription: How to write a python program that read the input and convert it to pre-defined 14-segments characters with turtle graphics?

description: Write a python program that read the input and convert it to pre-defined 14-segments characters with turtle graphics


code: diff(y, x)  # meaning differentiate y with respect to x

rawDescription: What does "symbolic" mean in this sentence?


code:
from itertools import izip
map(''.join, izip(data, data[1:]))

rawDescription: Parse String every 2 letters

description: Parse String every 2 letters


code:
from django.db import connections, reset_queries
reset_queries()

users = User.objects.all().prefetch_related('vote_set')
table = []
table.append([''] + list(users))
for board_game in BoardGame.objects.all().prefetch_related('vote_set'):
    row = [board_game]
    for user in users:
        for vote in user.vote_set.all():
            if vote in board_game.vote_set.all():
                row.append(vote)
                break
        else:
            row.append('')
    table.append(row)

len(connection.queries)  # Returns always 4

rawDescription: Two way table and django ORM

description: Two way table and django ORM


code: con.commit() #after inserts

rawDescription: why cx_Oracle and sqlplus give different results for the same select query

description: Why cx_Oracle and sqlplus give different results for the same select query


code: [v for k, v in sorted(dictionary.iteritems())]

rawDescription: python : list of dictionary values by alphabetical order of keys

description: Python : list of dictionary values by alphabetical order of keys


code:
# list of toolitems to add to the toolbar, format is:
# (
#   text, # the text of the button (often not visible to users)
#   tooltip_text, # the tooltip shown on hover (where possible)
#   image_file, # name of the image for the button (without the extension)
#   name_of_method, # name of the method in NavigationToolbar2 to call
# )
toolitems = (
    ('Home', 'Reset original view', 'home', 'home'),
    ('Back', 'Back to  previous view', 'back', 'back'),
    ('Forward', 'Forward to next view', 'forward', 'forward'),
    (None, None, None, None),
    ('Pan', 'Pan axes with left mouse, zoom with right', 'move', 'pan'),
    ('Zoom', 'Zoom to rectangle', 'zoom_to_rect', 'zoom'),
    (None, None, None, None),
    ('Subplots', 'Configure subplots', 'subplots', 'configure_subplots'),
    ('Save', 'Save the figure', 'filesave', 'save_figure'),
    )

rawDescription: Matplotlib/Tkinter - customizing toolbar tooltips


rawDescription: Consuming GAE Endpoints with a Python client


code:
import numpy as np

num = int(input("Enter a number: "))

primes = []

for a in range(2,num+1):

  maxInt= int(np.sqrt(a)) + 1

  for i in range(2,maxInt):

    if (a%i==0):
      break

  else:
    primes.append(a)

print(sum(primes))

rawDescription: How do I find the sum of prime numbers in a given range in Python 3.5?

description: Find the sum of prime numbers in a given range in Python 3.5


rawDescription: Write list of tuples to txt file

description: Write list of tuples to txt file


rawDescription: how to apply functions to grouped dataframes in Python pandas?

description: Apply functions to grouped dataframes in Python pandas


code:
import matplotlib
import matplotlib.pyplot as plt

min_val = 0
max_val = 1

my_cmap = matplotlib.cm.get_cmap('jet')
norm = matplotlib.colors.Normalize(min_val, max_val)

cmmapable = matplotlib.cm.ScalarMappable(norm, my_cmap)
cmmapable.set_array(range(min_val, max_val))

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)

cbar = plt.colorbar(cmmapable, ax = ax1, ticks=[0, 1])
cbar.ax.set_yticklabels(['Min', 'Max'])

# gives bounding box with left, right, bottom, top
print(ax1.get_position())
# gives rectangle with left, bottom, width, height
print(ax1._position.bounds)

fig2 = plt.figure()
ax2 = fig2.add_axes(ax1._position.bounds)

plt.show()

rawDescription: Matplotlib - Same padding as the one used by a `colorbar`


rawDescription: Binary to ASCII in Python

description: Binary to ASCII in Python


code:
result = list()
for item in mylist:
    for part in item.split():
        result.append(part)

rawDescription: separating multiple words out of the same index

description: Separating multiple words out of the same index


code: self.ser = serial.Serial('COM3', 9600, timeout=0)

rawDescription: Using while loop in Pycharm and Kivy

description: Using while loop in Pycharm and Kivy


title: example glossary

title: S

SortAs: SGML

GlossTerm: Standard Generalized Markup Language

Acronym: SGML

para: A meta-markup language, used to create markup languages such as DocBook.

GlossSeeAlso: GML XML

GlossSee: markup

rawDescription: What is faster - Loading a pickled dictionary object or Loading a JSON file - to a dictionary?


rawDescription: Python - Replace data of an array by 2 values of a second array


code:
regex = re.compile('.*This post is about.*Google.com.*')
[post for post in soup.findAll(True, 'post') if regex.match(post.text)]

rawDescription: How can I emulate ":contains" using BeautifulSoup?

description: Emulate ":contains" using BeautifulSoup


code:
new_data = test()
new_data # calling this would return your dictionary

rawDescription: Compare length of list in dictionary

description: Compare length of list in dictionary


code:
p = Python()
p.exec("print('foo')")
p.exec("print('bar')")
p.process.stdin.close() # force interpreter to exit ...
time.sleep(0.1) # wait for the interpreter to exit ...
p.read()

rawDescription: Open a python process using python's subprocess module


code: len(yourdict)

rawDescription: Counting the Number of keywords in a dictionary in python


code:
url = 'http://www.somesite.com/'
fp = opener.open(url)
html_object = BeautifulSoup(fp)

rawDescription: Data from a custom Google Map

description: Data from a custom Google Map


rawDescription: How to do a simple groupby in pandas?

description: Do a simple groupby in pandas


code:
def get_vowels(word):
    vowels = "AEIOU"
    return [c for c in word if c.upper() in vowels]

rawDescription: Python good programming practice for enumerating lists


code: print_matrix(spiral(5, 5))

rawDescription: creating a spiral array in python?

description: Creating a spiral array in python


code:
from types import SimpleNamespace
def location():
    return SimpleNamespace(x=5, y=0, z=0)
location().x

rawDescription: Return different value from function depending on suffix


code:
keep = []
for mem in memberlist:
    if ...:
       keep.append(mem)
return keep

rawDescription: Simplifying a list filter in Python

description: Simplifying a list filter in Python


code:
def standardize_date(date_str):
    ntuple=eutils.parsedate(date_str)
    timestamp=time.mktime(ntuple)
    date=datetime.datetime.fromtimestamp(timestamp)
    return date.strftime('%a, %d %b %Y %H:%M:%S')

print(standardize_date('Mon, 16 Aug 2010 24:00:00'))
# Tue, 17 Aug 2010 00:00:00

rawDescription: How can I convert the time in a datetime string from 24:00 to 00:00 in Python?

description: Convert the time in a datetime string from 24:00 to 00:00 in Python


code:
from numpy import sqrt   # leave this outside the function
from scipy.optimize import fsolve

#  here it is     V
def terminalV(Vt, *data):
    ro_p, ro, D_p, mi, g = data   # automatic unpacking, no need for the 'i for i'
    return sqrt((4*g*(ro_p - ro)*D_p)/(3*C_d(Re(data, Vt))*ro)) - Vt

data = (1800, 994.6, 0.208e-3, 8.931e-4, 9.80665)
Vt0 = 1
Vt = fsolve(terminalV, Vt0, args=data)

rawDescription: Passing arguments to fsolve

description: Passing arguments to fsolve


code:
from enum import Enum

class Color(Enum):
    red = 1
    blue = 2

input_var = 'red'

if hasattr(Color, input_var):
    print('Everything is fine and dandy.')

rawDescription: Validate against enum members in Python

description: Validate against enum members in Python


code: matrices @ vectors[..., None]

rawDescription: Broadcasting matrix-vector dot product

description: Broadcasting matrix-vector dot product


code: my_array = my_array.reshape((50, 50)).astype('uint8')

rawDescription: Convert black and white array into an image in python?


code:
class TheIterator(object):
    def __init__(self, data):
        self.data = data
        self.index = -1

    # Note: In  Python 3 this is called __next__
    def next(self):
        self.index += 1
        try:
            return self.data[self.index]
        except IndexError:
            raise StopIteration

    def __iter__(self):
        return self

class Iter(object):
    def __init__(self, data):
        self.data = data

    def __iter__(self):
        return TheIterator(data)

rawDescription: Python: the mechanism behind list comprehension


code: entries['Categoria'] = entries['Commerciante'].apply(lambda v: dealer_replace(dealer, str(v)))

rawDescription: python pandas use map with regular expressions

description: Python pandas use map with regular expressions


code:
with mock.patch.object(MyClass, 'my_method', classmethod(mocked_method)):
    MyClass.my_method()

rawDescription: TypeError: unbound method when trying to mock a classmethod


code:
Product.objects.raw("""
SELECT t3.*, count(t2.tag_id) as similar_tags_count
FROM {m2m_tbl} t1 INNER JOIN {m2m_tbl} t2
     ON (t1.tag_id = t2.tag_id and t1.product_id != t2.product_id and t1.product_id = %s)
     INNER JOIN {product_tbl} t3 ON (t2.product_id = t3.id)
GROUP BY t3.id, t3.name
ORDER BY similar_tags_count DESC;
""".format(m2m_tbl=Product.tags.through._meta.db_table, product_tbl=Product._meta.db_table),
    [the_given_product.pk])

rawDescription: Django Query - Sort by Tags in common

description: Django Query - Sort by Tags in common


code:
import gevent
import gevent.monkey; gevent.monkey.patch_all() # patch stdlib

import json
import urllib
import urllib2

def f(querystr):
    query = urllib.urlencode(dict(q=querystr, rpp=5, include_entities=1,
                                  result_type="mixed"))
    resp = urllib2.urlopen("http://search.twitter.com/search.json?" + query)
    d = json.load(resp)
    print('number of results %d' % (len(d['results']),))

jobs = [gevent.spawn(f, q) for q in ['blue angel', 'another query']]
gevent.joinall(jobs) # wait for completion

rawDescription: python asynchronous httprequest

description: Python asynchronous httprequest


rawDescription: django reverse query

description: Django reverse query


code: [set((i,)) for i in range(5)]

rawDescription: How can I write a list comprehension to create a list of sets?

description: Write a list comprehension to create a list of sets


rawDescription: Merging Pandas DataFrames with the same column name


rawDescription: Regex conditioning

description: Regex conditioning


code:
Output
set(['Asia/Colombo', 'Asia/Calcutta', 'Asia/Kolkata'])

rawDescription: Getting timezone name from UTC offset

description: Getting timezone name from UTC offset


rawDescription: How to run batch file using IronPython

description: Run batch file using IronPython


rawDescription: Find all references to an object in python


rawDescription: A superfluous but cool dynamic python structure and questions about decorators, comprehensions, syntax


rawDescription: Why does skimage.imread() not return RGB values for my bmp?


code:
label1;label2;label3
val1;otherval1;yetanotherval1
val2;otherval2;dummy
val3;dummy;dummy

rawDescription: python - Nested list in dict to csv files

description: Python - Nested list in dict to csv files


code: model = self.treeview.get_model()

rawDescription: How to get a list of the elements in TreeView? PyGtk

description: Get a list of the elements in TreeView? PyGtk


rawDescription: Most Pythonic way to print *at most* some number of decimal places


code:
from datetime import datetime as dt
from datetime import timedelta
a='2015-01-15 08:59:16'
dt_obj = dt.strptime(a, '%Y-%m-%d %H:%M:%S')
dt_with_one_more_min = dt_obj + timedelta(minutes=1)
print('original time = {}'.format(dt_obj))
print('new time = {}'.format(dt_with_one_more_min))

rawDescription: How to add a minute in Python to Hive timestamp format

description: Add a minute in Python to Hive timestamp format


code:
d = {}
for items in (list1, list2):
    for item in items:
        d.setdefault(item[0], [item[0]]).extend(item[1:])

rawDescription: Grouping two lists in python

description: Grouping two lists in python


code:
import sage

sol = sage.combinat.designs.block_design.projective_plane(7)

for row in sol.incidence_matrix().rows():
    print(row)

rawDescription: Python - Spot it! Cards

description: Python - Spot it! Cards


code:
df
df.to_dict('records')

rawDescription: Create json array using list in python

description: Create json array using list in python


code:
def encrypt_password(password):
   ...
   return _pwd_context.encrypt(signed)

_pwd_context = LocalProxy(lambda: _security.pwd_context)

rawDescription: Unique Salt per User using Flask-Security


code:
from collections import defaultdict
sums = defaultdict(float)
for tr in credit_transactions:
    sums[tr.category] += tr.amount

rawDescription: Generating python dictionary only stores last value from iterable


code: sentence = ' '.join(wordlist[pos] for pos in poslist)

rawDescription: How can I create a list that is created using the indexes and items of two other lists?

description: Create a list that is created using the indexes and items of two other lists


code:
if key in a:
    del a[key]

rawDescription: How to efficiently loop through a dictionary when deleting elements from the same (mutated)

description: Efficiently loop through a dictionary when deleting elements from the same (mutated)


code: ax.legend(lines, [l.get_label() for l in lines], loc='upper center')

rawDescription: Legend only shows one label when plotting with pandas


rawDescription: Adding a tuple to a tuple of tuples

description: Adding a tuple to a tuple of tuples


code:
with open(...) as file_in, open (...) as file_out: # same as previously
    good_lines = (line for line in file_in if any(word in line for word in words))
    for good_line in good_lines:
        file_out.write(good_line)

rawDescription: Searching words from a file in another file


rawDescription: How do I retrieve a list within dictionary within a list?

description: Retrieve a list within dictionary within a list


rawDescription: Group by FK field

description: Group by FK field


code: data = j['data']

rawDescription: Trouble parsing API JSON output with python using 'requests'


rawDescription: How do I merge two columns in a dataframe based on a datetime index?

description: Merge two columns in a dataframe based on a datetime index


code: assert inspect.ismethod(Test().method)

rawDescription: Python : Assert that variable is instance method?


code:
{'body_bytes_sent': '546849',
 'http_referer': 'http://example.com/video/302/',
 'http_user_agent': 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36',
 'remote_addr': '112.3.194.120',
 'remote_user': '-',
 'request': 'GET /Introdction%20to%20Guitar/1%20-%202%20-%20Choosing%20the%20Right%20Guitar-%20Right-Handed%20vs%20Left-Handed%20(3-20).mp4 HTTP/1.1',
 'status': '206',
 'time_local': '17/Jan/2015:20:07:34 +0800'}

rawDescription: How to generate regex to match access.log acording to its format config?

description: Generate regex to match access.log acording to its format config


code:
import os
import numpy as np

swap = lambda x: (x[1], x[0])

def add_random_key(it):
    # make sure we get a proper random seed
    seed = int(os.urandom(4).encode('hex'), 16)
    # create separate generator
    rs = np.random.RandomState(seed)
    # Could be randint if you prefer integers
    return ((rs.rand(), swap(x)) for x in it)

rdd_with_keys = (rdd
  # It will be used as final key. If you don't accept gaps
  # use zipWithIndex but this should be cheaper
  .zipWithUniqueId()
  .mapPartitions(add_random_key, preservesPartitioning=True))

rawDescription: Pyspark: shuffle RDD

description: Pyspark: shuffle RDD


rawDescription: "Slicing" in Python Expressions documentation


code: {u'body': u"Don't forget me this weekend!", u'to': u'Tove', u'from': u'Jani', u'heading': u'Reminder'}

rawDescription: convert xml to python dict

description: Convert xml to python dict


code:
from prettytable import PrettyTable
table = PrettyTable(['name', 'age', 'marks'])
table.add_row(['X', 20, 100])
table.add_row(['Z', 20, 700])
table.add_row(['Y', 21, 900])
print(table)

rawDescription: Accept 3 dictionary inputs with keys Name, age and total marks. print them in a table in ascending order of marks


rawDescription: argument unpacking and assignment to class variables

description: Argument unpacking and assignment to class variables


code:
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
cursor = cnxn.cursor()
cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome library')")
cnxn.commit()

rawDescription: Export Python Dataframe to SQL Table

description: Export Python Dataframe to SQL Table


code:
from __future__ import division

def cluster(data, maxgap):
    """Arrange data into groups where successive elements
       differ by no more than *maxgap*

        >>> cluster([1, 6, 9, 100, 102, 105, 109, 134, 139], maxgap=10)
        [[1, 6, 9], [100, 102, 105, 109], [134, 139]]

        >>> cluster([1, 6, 9, 99, 100, 102, 105, 134, 139, 141], maxgap=10)
        [[1, 6, 9], [99, 100, 102, 105], [134, 139, 141]]
    """
    data.sort()
    groups = [[data[0]]]
    for item in data[1:]:
        val = abs(item - groups[-1][-1])
        if val <= maxgap:
            groups[-1].append(item)
        else:
            groups.append([item])
    return groups

peaks = [1,3,7,9,12]
print([sum(arr)/len(arr) for arr in cluster(peaks, maxgap=2)])

rawDescription: Averaging indexes of peaks if they are close in Python


rawDescription: Python: adding value from list of lists

description: Python: adding value from list of lists


code:
# or keep iterating until the longer fToC generator is exhausted
from itertools import zip_longest

for f, c in zip_longest(cToF(), fToC()):
    print('{}\t\t{}'.format(f, c))  # will print None, c once cToF is exhausted

rawDescription: Print two functions side by side

description: Print two functions side by side


code:
def _orders(self, cr, uid, ids, fields, arg, context=None):
    res = {}
    for _obj in self.browse(cr, uid, ids, context=context):
        _orders = _order_pool.search(cr, uid, [('partner_id', '=', statement.partner_id.id), ], context=context)
        res[_obj.id] =_orders
    return res

rawDescription: Odoo. Function field that returns list

description: Odoo. Function field that returns list


code:
def display(x,y,z):
    if z["text"] == " ":
        # switch to Goodbye
        z["text"] = level1[x][y]
    else:
        # reset to Hi
        z["text"] = " "

rawDescription: changing buttons within tkinter

description: Changing buttons within tkinter


code:
from itertools import chain
mylist = list(chain.from_iterable(myarray))

rawDescription: how to add all array's elements to one list in python

description: Add all array's elements to one list in python


code:
import dill
class Foo(object):
  def bar(self, x):
    return x+self.x
  x = 1

b = Foo()
b.x = 5

with open('blah.pkl', 'wb') as s:
  dill.dump((Foo, b), s)

rawDescription: Pickle python class instance plus definition


code:
import lxml.etree as ET
def process_element(elem):
    ...
context=ET.iterparse(filename, events=('end',), tag=...)
fast_iter(context, process_element)

rawDescription: Parsing large XML using iterparse() consumes too much memory. Any alternative?


code:
data = pd.read_csv('/home/Desktop/dataset.txt')
i = 0
while True:
    if i > 100:
       break

    if data[i, 0] == 5:
        i = i + 5
    elif data[i, 0] == 10:
        i = i + 10
    else:
        i = i + 20

rawDescription: Steps for "for loop" in python

description: Steps for "for loop" in python


rawDescription: Python : Getting the Row which has the max value in groups using groupby


code: ['hello there', 'Watermelons are delicious']

rawDescription: How to remove an item in a list that has a specific ordering of words

description: Remove an item in a list that has a specific ordering of words


code:
hdr = b'\x00' * 4
blocksize = 51
leds = (
    #LED off
    hdr + b'\x80\x00' * blocksize,
    #LED on
    hdr + b'\xff\xff' * blocksize,
)

fname = '/dev/stdout'
with open(fname, 'wb') as f:
    f.write(leds[0])

rawDescription: Send HEX values to SPI on a Raspberry PI B+


code:
df[0] = df.index.year
df[1] = df.index.month
df[2] = df.index.day
df

rawDescription: Convert datetime index in pandas to separate columns


rawDescription: Storage size of array.array in a file

description: Storage size of array.array in a file


code:
@asyncio.coroutine
def listener():
    while True:
        message = yield from websocket.recieve_message()
        if message:
            asyncio.ensure_future(handle(message))

rawDescription: Asyncio and infinite loop

description: Asyncio and infinite loop


code:
n = 3
for i in range(0, len(content), 3):
   q= content[i:i+n]
   con = dbapi.connect(database='import', user='postgres', password='xxx')
   cur = con.cursor()
   cur.execute("INSERT into import VALUES (%s,%s,%s)",q)
   con.commit()

rawDescription: dynamical list from site into postgres python

description: Dynamical list from site into postgres python


code:
def add_attribute_block(toybox = None, key = "" ):
    if toybox is not None:
        for obj in AttributeBlock.objects:
            if obj.key == key:
                toybox.attributes.append(obj)
                break

rawDescription: creating a new copy of a python class each time it's called

description: Creating a new copy of a python class each time it's called


code:
# Create the shared queue and launch both thread pools
in_queue = Queue()
out_queue = Queue()

ip_list = ['ip1', 'ip2', '....']
# This is to add all the ips to the queue or you can
# customize to add through some producer way.
for ip in ip_list:
    in_queue.put(ip)

pingerer_pool = []

for i in xrange(1, 10):
    pingerer_worker = Pinger(kwargs={'in_queue': in_queue, 'out_queue': out_queue}, name=str(i))
    pingerer_pool.append(pinger_worker)
    pingerer_worker.start()

while 1:
    if out_queue.get() == 'success':
        for pinger in pinger_pool:
            pinger_worker.stop_pinging = True

        break

rawDescription: How to implement a python thread pool to test for network connectivity?

description: Implement a python thread pool to test for network connectivity


code:
def open(filename, mode='rb', encoding=None, errors='strict', buffering=1):

    if encoding is not None:
        if 'U' in mode:
            # No automatic conversion of '\n' is done on reading and writing
            mode = mode.strip().replace('U', '')
            if mode[:1] not in set('rwa'):
                mode = 'r' + mode
        if 'b' not in mode:
            # Force opening of the file in binary mode
            mode = mode + 'b'
    file = __builtin__.open(filename, mode, buffering)
    if encoding is None:
        return file
    info = lookup(encoding)
    srw = StreamReaderWriter(file, info.streamreader, info.streamwriter, errors)
    # Add attributes to simplify introspection
    srw.encoding = encoding
    return srw

rawDescription: Python 2.7.1, codecs, and MySQLdb; why is setting file encoding not needed


rawDescription: Add missing dates to pandas dataframe

description: Add missing dates to pandas dataframe


code:
from collections import OrderedDict
res = OrderedDict()
for v, k in input:
  if k in res: res[k].append(v)
  else: res[k] = [v]

[{'type':k, 'items':v} for k,v in res.items()]

rawDescription: Python group by

description: Python group by


rawDescription: Draw a cumulative chart from a pandas dataframe?


code:
class AdminEmailHandler(logging.Handler):
    """An exception log handler that emails log entries to site admins.

    If the request is passed as the first argument to the log record,
    request data will be provided in the email report.
    """

    def __init__(self, include_html=False):
        logging.Handler.__init__(self)
        self.include_html = include_html

    def emit(self, record):
        try:
            request = record.request
            subject = '%s (%s IP): %s' % (
                record.levelname,
                (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'),
                record.msg
            )
            filter = get_exception_reporter_filter(request)
            request_repr = filter.get_request_repr(request)
        except:
            subject = '%s: %s' % (
                record.levelname,
                record.getMessage()
            )
            request = None
            request_repr = "Request repr() unavailable."

        if record.exc_info:
            exc_info = record.exc_info
            stack_trace = '\n'.join(traceback.format_exception(*record.exc_info))
        else:
            exc_info = (None, record.getMessage(), None)
            stack_trace = 'No stack trace available'

        message = "%s\n\n%s" % (stack_trace, request_repr)
        reporter = ExceptionReporter(request, is_email=True, *exc_info)
        html_message = self.include_html and reporter.get_traceback_html() or None
        mail.mail_admins(subject, message, fail_silently=True, html_message=html_message)

rawDescription: Is it possible to add a header to the email django sends to admins when a 500 is generated?


code:
import re

h, e = re.compile("H+"), re.compile("E+")

with open("in.txt") as f:
    for line in f:
        if line.startswith("PROF_sec"):
            print([(s.start() +sm, s.end()+ sm) for s in h.finditer(line)])
            print([(s.start()+sm, s.end()+sm) for s in e.finditer(line)])
            break
        sm += len(line)

rawDescription: return the position with specific word

description: Return the position with specific word


code:
a[:] = numpy.NaN
b=numpy.copy(a)
b[numpy.isnan(b)]=1
a
b

rawDescription: Python array assignments

description: Python array assignments


code:
keys = ['firstKey', 'secondKey', 'thirdKey']
for key in keys:
    myDictionary.get(key)

rawDescription: Python dictionary get multiple values

description: Python dictionary get multiple values


code:
lists = [
    ['Tryndamere', 'Barbarian', 'Fighter'],
    ['Caitlyn', 'Sheriff', 'Marksmen'],
    ['Veigar', 'Midget', 'Mage']
]

rawDescription: Split lists within list

description: Split lists within list


code: form = MyForm(self.request.params, self.get_uploaded_files())

rawDescription: Uploading files to App Engine using webapp and Django forms


code:
l = 4
o = 2
e = 7

print([[x for x in range(s, s + l)] for s in range(0, e, o) if s + l <= e + 1])

rawDescription: Generating overlapping sequences

description: Generating overlapping sequences


rawDescription: How to solve non-linear sets of equations

description: Solve non-linear sets of equations


code:
def quality_check(q):
    spl = q.split(",") # split to check both numbers
    if  all(x in  ["7", "8", "9", "10", "12", "13", "15", "23", "24", "25", "26"]for x in  spl):
        return "good"
    else:
        return "poor"

rawDescription: Check list of numbers is a subset

description: Check list of numbers is a subset


code:
tup_b =  itertools.combinations(list_b, 2)
list_b = map(list,tup_b)
df_b = pd.DataFrame(list_b)

#Extending the list
df_b['B'] = df_b[0] + df_b[1]
df_b = df_b[['B']]

#flatten list
b = df_b.values.tolist()
b = list(itertools.chain(*r))

# adding values and costs
r = len(b)
x=0
for x in range(0,r):
    cost = [b[x][1] +b[x][4]]
    value = [b[x][2] +b[x][5]]
    r[x] = r[x] +cost +value
    x +=1

#shortening list
df_b = pd.DataFrame(b)
df_b = df_b[[0,3,6,7]]
df_b.columns = ['B1','B2','cost','value']

rawDescription: Optimizing Python script with multiple for loops


code:
def add_product(request):
    success = False

    if request.method == "POST":
        product_form = ProductForm(request.POST)

        if product_form.is_valid():
            success = True

            category = Category.objects.get(name=product_form.cleaned_data['category'])
            product = product_form.cleaned_data['product']
            quantity = product_form.cleaned_data['quantity']
            price = product_form.cleaned_data['price']

            new_product = Product(category = category, product = product, quantity = quantity, price = price )
            new_product.save()

            new_product_form = ProductForm()

            ctx2 = {'success':success, 'product_form':new_product_form}
            return render_to_response('product/add_product.html', ctx2 , context_instance=RequestContext(request))
    else:
        product_form = ProductForm()
    ctx = {'product_form':product_form}
    return render_to_response('product/add_product.html', ctx , context_instance=RequestContext(request))

rawDescription: Saving data using Django ModelForms

description: Saving data using Django ModelForms


rawDescription: Can I make test dummies for every kind of service for an integrated app?

description: Make test dummies for every kind of service for an integrated app


code: list1 = sorted(list1, key=lambda object1: object1.fitness, reverse=True)

rawDescription: python object list, sort in descending order based on object attribute

description: Python object list, sort in descending order based on object attribute


code:
a = range(10)
b = iter(a)
from itertools import islice
l = [3, 5, 2]
[list(islice(b, x)) for x in l]

rawDescription: Split a list into chunks of varying length


code:
dic = {}
dic.update({i:np.sum for i in df.filter(regex='d_.*').columns})
dic.update({'col':np.mean})

In [48]: df.groupby(['day','type'], as_index=False).agg(dic)
#Out[48]:
#   day type  d_2  d_3  d_1  col  d_4
#0    1    A    0    2    2  1.5    0
#1    2    B    1    0    1  1.0    0

rawDescription: how to sum across many columns with pandas groupby?

description: Sum across many columns with pandas groupby


rawDescription: Find values from MongDB from an array for only one date


code:
def zippy(x, y):
    zipper = []
    for i in range(len(x)):
        zipper.append((x[i], y[i]))
    return zipper

rawDescription: Trouble creating my own "zip" function in Python


code:
import random

sides = 4
count = 1

def tossdie():
    """Function to create a random integer for a die"""
    return random.randint(1,4)

while True:
    die1 = tossdie()
    die2 = tossdie()
    print (count, ". die number 1 is", die1, "and die number 2 is", die2,".")
    if die1 == die2:
        break
    count += 1

print ("You got snake eyes! Finally! On try number", count,".")

rawDescription: Counting/random int in while loop

description: Counting/random int in while loop


code:
class MyListView(ListView):

    def get_template_names(self):
        return ["transactions/batchfiles/list.html"]

rawDescription: Can I change the template search behavior of class based views?

description: Change the template search behavior of class based views