code: parsedHtml = BeautifulSoup(pageContent, 'html5lib')

rawDescription: Python 3: Can't properly encode and print a downloaded string with /xXX literals


code:
def mount(self, root, script_name="", config=None):
    ...
    if isinstance(root, Application):
        app = root
        if script_name != "" and script_name != app.script_name:
            raise ValueError(
                "Cannot specify a different script name and pass an "
                "Application instance to cherrypy.mount")
        script_name = app.script_name
    else:
        app = Application(root, script_name)

        # If mounted at "", add favicon.ico
        if (script_name == "" and root is not None
                and not hasattr(root, "favicon_ico")):
            favicon = os.path.join(os.getcwd(), os.path.dirname(__file__),
                                   "favicon.ico")
            root.favicon_ico = tools.staticfile.handler(favicon)

    if config:
        app.merge(config)

    self.apps[script_name] = app

rawDescription: Python CherryPy server, what does cherrypy.Application do?


code:
def nice_repr(timedelta, display="long"):
    """
    Turns a datetime.timedelta object into a nice string repr.

    display can be "minimal", "short" or "long" [default].

    >>> from datetime import timedelta as td
    >>> nice_repr(td(days=1, hours=2, minutes=3, seconds=4))
    '1 day, 2 hours, 3 minutes, 4 seconds'
    >>> nice_repr(td(days=1, seconds=1), "minimal")
    '1d, 1s'
    """

    assert isinstance(timedelta, datetime.timedelta), "First argument must be a timedelta."

    result = ""

    weeks = timedelta.days / 7
    days = timedelta.days % 7
    hours = timedelta.seconds / 3600
    minutes = (timedelta.seconds % 3600) / 60
    seconds = timedelta.seconds % 60

    if display == 'minimal':
        words = ["w", "d", "h", "m", "s"]
    elif display == 'short':
        words = [" wks", " days", " hrs", " min", " sec"]
    else:
        words = [" weeks", " days", " hours", " minutes", " seconds"]

    values = [weeks, days, hours, minutes, seconds]

    for i in range(len(values)):
        if values[i]:
            if values[i] == 1 and len(words[i]) > 1:
                result += "%i%s, " % (values[i], words[i].rstrip('s'))
            else:
                result += "%i%s, " % (values[i], words[i])

    return result[:-2]

rawDescription: Converting fractional days to H:M:S.MS - Two examples


code: longitudes = np.linspace(0, np.pi, N_POINTS)

rawDescription: Matplotlib plot_surface spurious faces

description: Matplotlib plot_surface spurious faces


code: os.kill(programID.pid, signal.SIGSTOP)

rawDescription: Is there a way to pause a Python subprocess, specifically in Ubuntu?


code:
dict = {}
for rows in data_set:
      rows.strip()
      rows.split('\t')
      if rows[0] in dict:
         dict[rows[0]] += rows[1]
      else:
         dict[rows[0]]  = rows[1]

rawDescription: merging values in rows dependent on values in columns

description: Merging values in rows dependent on values in columns


code:
#!/usr/bin/env python3
import base64, subprocess, sys

def powershell(cmd, input=None):
    cmd64 = base64.encodebytes(cmd.encode('utf-16-le')).decode('ascii').strip()
    stdin = None if input is None else subprocess.PIPE
    process = subprocess.Popen(["powershell.exe", "-NonInteractive", "-EncodedCommand", cmd64], stdin=stdin, stdout=subprocess.PIPE)
    if input is not None:
        input = input.encode(sys.stdout.encoding)
    output, stderr = process.communicate(input)
    output = output.decode(sys.stdout.encoding).replace('\r\n', '\n')
    return output

command=r"""
$data = Get-ChildItem C:\Python34
$data | Export-Clixml -Path c:\temp\state.xml
$data
"""
output = powershell(command)
print(output)
print("Do some processing here...")
result = """NEWS.txt=1
README.txt=1
\u00a3.txt=1
"""
command = r"""
$in = $input|Out-String
$selected = $in | ConvertFrom-StringData
$data = Import-Clixml -Path c:\\temp\\state.xml
$data |? { $selected.ContainsKey($_.Name) } | Select Length,FullName
"""
output = powershell(command, result)
print(output)

rawDescription: Passing variables between Powershell commands in a python script


code:
# x.py
import y
y.foo()

rawDescription: How can I replace a module without importing it?

description: Replace a module without importing it


code: list(itertools.product('LE', repeat=3))

rawDescription: Combinations or permutations of input, for a given length


code:
cur = psql.execute(sql, con, params=cus2)
rows = cur.fetchall()
columns = [col_desc[0] for col_desc in cur.description]
cur.close()

result = DataFrame.from_records(rows, columns=columns, coerce_float=True)

rawDescription: Remove Brackets from Python List for an SQL query


code:
df.sort(['ticker', 'date'], inplace=True)
df['diffs'] = df['value'].diff()

rawDescription: Computing diffs within groups of a dataframe


code:
coordinate_list = [x for location in locations
                   for x in [Coordinates(location.latitude,
                                         location.longitude)
                            ] * location.number_of_times]

rawDescription: Python: Repeat elements in a list comprehension?


code: r = round(x, n - 1 - left)

rawDescription: How to get the exact number of positions after a decimal for the round() function

description: Get the exact number of positions after a decimal for the round() function


code:
index=list('ABCD')
df = pd.DataFrame(columns=index)
df.append(Series(aa[0:4],index=index),ignore_index=True)

rawDescription: Appending Tuples to Pandas DataFrame

description: Appending Tuples to Pandas DataFrame


code: import pdb; pdb.set_trace()

rawDescription: Strings won't compare properly

description: Strings won't compare properly


code: ['Server1', 'Server2', 'Server3']

rawDescription: Extracting values from a string and store them in a list


code:
# Custom formatter
class MyFormatter(logging.Formatter):

    err_fmt  = "ERROR: %(msg)s"
    dbg_fmt  = "DBG: %(module)s: %(lineno)d: %(msg)s"
    info_fmt = "%(msg)s"

    def __init__(self):
        super().__init__(fmt="%(levelno)d: %(msg)s", datefmt=None, style='%')

    def format(self, record):

        # Save the original format configured by the user
        # when the logger formatter was instantiated
        format_orig = self._style._fmt

        # Replace the original format with one customized by logging level
        if record.levelno == logging.DEBUG:
            self._style._fmt = MyFormatter.dbg_fmt

        elif record.levelno == logging.INFO:
            self._style._fmt = MyFormatter.info_fmt

        elif record.levelno == logging.ERROR:
            self._style._fmt = MyFormatter.err_fmt

        # Call the original formatter class to do the grunt work
        result = logging.Formatter.format(self, record)

        # Restore the original format configured by the user
        self._style._fmt = format_orig

        return result

rawDescription: Modifying logging message format based on message logging level in Python3


code:
class B(A):
    @property
    def attr(self):
        return super(B, self).attr()

rawDescription: Overriding inherited properties’ getters and setters in Python


code:
from django.views.generic import ListView

class EntryList(ListView):
    model = Entry
    template_name = 'blog/entry_list.html'
    context_object_name = 'entry_list'
    paginate_by = 10

rawDescription: django-endless with class based views example

description: Django-endless with class based views example


code:
def inplace_flatten(d):
    keys = list(d.keys())
    for k in keys:
        if isinstance(d[k], dict):
            inplace_flatten(d[k])
            d.update(d.pop(k))

rawDescription: Chained Method Calls in Python with dict


code:
class MyTest(BaseTestSuite):
    xmlfile = '<some_xml></some_xml>'

rawDescription: python unittest multiple mixins

description: Python unittest multiple mixins


code: add.apply_async((4, 4), headers={'time_sent': time.time()})

rawDescription: Why Celery does not embed a timestamp into the queued message?


code:
#f is going to be your file in string form
re.sub(r'(?m)self\.assertRaisesRegexp\((.+?),((?P<quote>[\'"]).*?(?P=quote))\)',r'self.assertRaisesRegexp(\1,somemethod(\2))',f)

rawDescription: replace a string with regular expression in python

description: Replace a string with regular expression in python


code:
def f(n):
    return n**2

lst = [f]  # save function reference in a list
del(f)  # unbind the name

rawDescription: How to get function object inside a function (Python)

description: Get function object inside a function (Python)


code: classname = get_class_name(user)

rawDescription: Django custom user model with django-polymorphic


code:
data = [
    # some made-up numbers for illustration
    ("France", 2006, 64026, 72527, 87442, 98435),
    ("France", 2007, 82051, 75285, 97193, 69527),
    ("France", 2008, 88827, 51960, 77807, 81725),
    ("Germany", 2006, 85653, 83989, 66603, 66559),
    ("Germany", 2007, 85431, 83590, 88482, 87827),
    ("Germany", 2008, 67184, 96350, 84947, 67874),
    ("Greece", 2006, 72062, 55844, 51758, 53004),
    ("Greece", 2007, 58566, 62006, 65323, 80320),
    ("Greece", 2008, 71298, 69158, 74774, 93267)
]

def average(lst):
    return sum(lst) / (len(lst) or 1)

def main():
    # prompt for country
    country = input("For which country? ")

    # filter data by specified country
    country_data = [row for row in data if row[0]==country]

    # get average yearly emigration
    avg_emigration = average([row[3] + row[5] for row in country_data])

    # print years in which emigration exceeds average
    print("Above-average emigration in:")
    for row in country_data:
        if row[3] + row[5] >= avg_emigration:
            print(row)

    # I'll leave the last bit for you to figure out;
    # very similar to the preceding clause

if __name__ == "__main__":
    main()

rawDescription: Python list data analysing

description: Python list data analysing


code:
mdf.update(pdf)
mdf

rawDescription: Partial merge in Pandas

description: Partial merge in Pandas


rawDescription: Indexing in numpy array

description: Indexing in numpy array


code:
Rxy = np.empty_like(x2)
freqs_xy = np.empty_like(x2)

rawDescription: Splitted Array being filled in for loop by function calculating values from a splitted array


rawDescription: sendmail with HTML message

description: Sendmail with HTML message


code:
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...

rawDescription: python: Open file from zip without temporary extracting it

description: Python: Open file from zip without temporary extracting it


code:
def o_and_t():
    o()
    t()
button = Button(admin, text='Press', command=o_and_t)

rawDescription: tkinter call two functions

description: Tkinter call two functions


code:
class DrawingPointsWidget(QWidget):
    def __init__(self):
        super(QWidget, self).__init__()
        self.setMouseTracking(True)

rawDescription: eventFilter on a QWidget with PyQt4

description: EventFilter on a QWidget with PyQt4


rawDescription: Right data structure for containing shapes and spatial relations between them


code: from multiprocessing import Process

rawDescription: Python - Fork Modules

description: Python - Fork Modules


rawDescription: groupby on sparse matrix with scipy

description: Groupby on sparse matrix with scipy


code: guess in word

rawDescription: Python while/if statements not working

description: Python while/if statements not working


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('''

                Australia
                New Zealand
                Indonesia
                Thailand
                Singapore
                United Kingdom
                Thailand
                Australia
                Argentina
                New Zealand

''')
all_countries = soup.select('div#country-box ul li a')
list(iter_uniq_link(all_countries))

rawDescription: Extract unique elements from a list returned by BeautifulSoup


code: from flask import g

rawDescription: How to get parameters from root function

description: Get parameters from root function


code:
class MainWidget(Widget):
    manager = ObjectProperty(None)

rawDescription: Kivy Screen manager reference in kv language


code: series = chart.SeriesCollection(1)

rawDescription: Python - Extra Excel chart series with win32com


code:
from math import sin, cos, radians

def rotate_lines(self, deg=-90):
    """ Rotate self.polylines the given angle about their centers. """
    theta = radians(deg)  # Convert angle from degrees to radians
    cosang, sinang = cos(theta), sin(theta)

    for pl in self.polylines:
        # Find logical center (avg x and avg y) of entire polyline
        n = len(pl.lines)*2  # Total number of points in polyline
        cx = sum(sum(line.get_xdata()) for line in pl.lines) / n
        cy = sum(sum(line.get_ydata()) for line in pl.lines) / n

        for line in pl.lines:
            # Retrieve vertices of the line
            x1, x2 = line.get_xdata()
            y1, y2 = line.get_ydata()

            # Rotate each around whole polyline's center point
            tx1, ty1 = x1-cx, y1-cy
            p1x = ( tx1*cosang + ty1*sinang) + cx
            p1y = (-tx1*sinang + ty1*cosang) + cy
            tx2, ty2 = x2-cx, y2-cy
            p2x = ( tx2*cosang + ty2*sinang) + cx
            p2y = (-tx2*sinang + ty2*cosang) + cy

            # Replace vertices with updated values
            pl.set_line(line, [p1x, p2x], [p1y, p2y])

rawDescription: Rotate line around center point given two vertices


code:
graph = {'A': ['B', 'C'],
         'B': ['A', 'D', 'E'],
         'C': ['A', 'F'],
         'D': ['B'],
         'E': ['B', 'F'],
         'F': ['C', 'E']}

def dfs_path(graph,start,end):
    result = []
    dfs(graph,start,end,[],result)
    return result

def dfs(graph,start,end,path,result):
    path+=[start]
    if start == end:
        result.append(path)
    else:
        for node in graph[start]:
            if node not in path:
                dfs(graph,node,end,path[:],result)
print(dfs_path(graph,'A','F'))

rawDescription: dfs to implement a graph, python

description: Dfs to implement a graph, python


code:
def firstNonRep(word):
    count = {}
    for c in word:
        if c not in count:
            count[c] = 0
        count[c] += 1
    for c in word:
        if count[c] == 1:
            return c

rawDescription: Find the first non-repeated character in a string


code:
import pyperclip
y = []
for x in range(1,158):
    y.append("- " + str(x) + '\n')

pyperclip.copy(y)

rawDescription: Python - How do you assign a variable to a table displayed on seperate lines


code:
def unpack_bigint(b):
    b = bytearray(b) # in case you're passing in a bytes/str
    return sum((1 << (bi*8)) * bb for (bi, bb) in enumerate(b))

rawDescription: How to encode a long in Base64 in Python?

description: Encode a long in Base64 in Python


code: line[:max(line.find(' '), 0) or None]

rawDescription: Python: read one word per line of a text file


code:
import numpy

x = numpy.array([1, 2, 3, 4, 5, 6])

numpy.mean(x.reshape(-1, 2), 1) # Prints array([ 1.5,  3.5,  5.5])

rawDescription: Subsampling/averaging over a numpy array


rawDescription: How to do a 'groupby' by multilevel index in Pandas

description: Do a 'groupby' by multilevel index in Pandas


code:
a = int(input("Look up to: "))
print(filter(prime, range(0, a)))

rawDescription: How can I add the outcome of a function to a list in python?

description: Add the outcome of a function to a list in python


code: a

rawDescription: Convert row-column-value data to an array - numpy


rawDescription: Split string by regular expression

description: Split string by regular expression


code:
with open("power3X.txt","r") as infile:
    x1 = [float(line) for line in infile]

with open("power3Y.txt","r") as infile:
    y = [float(line) for line in infile]

xpl = numpy.arange(xmin, xmax, 0.1)   # no need for .tolist()
ypl = numpy.arange(ymin, ymax, 0.01)  # meshgrid can work with numpy.array's
xpl, ypl = numpy.meshgrid(xpl, ypl)

# we can form z with list comprehension
z = [[func_power_3([p1,p2], x1, y) for p1, p2 in zip(p1row, p2row)]
                                   for p1row, p2row in zip(xpl, ypl)]

fig = plt.figure('Power 3')
ax = fig.gca(projection='3d')
surf=ax.plot_surface(xpl, ypl, z, rstride=8, cstride=8, alpha=0.3,cmap=cm.jet)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
plt.show()

rawDescription: Python matplotlib - formatting with meshgrid for user-defined function


code:
import data_loader_and_executor

def function(x):
    return len(x)

data_loader_and_executor.run(function)

rawDescription: How do I pass function definition to python script as string

description: Pass function definition to python script as string


code:
foo_list = [1,2,3,4,5,6]
bar = 6
for i in range(len(foo_list)):
    print("range i ",i)
    if foo_list[i] < bar:
        i += 4
        print("if i",i)

('range i ', 0)
('if i', 4)
('range i ', 1)
('if i', 5)
('range i ', 2)
('if i', 6)
('range i ', 3)
('if i', 7)
('range i ', 4)
('if i', 8)
('range i ', 5)

rawDescription: Incrementing a for loop, inside the loop


code:
x in [x_min, x_max]
y in [y_min, x - answer_min]

rawDescription: Avoiding bias in randomly generated subtraction problems


rawDescription: Write to_csv with Python Pandas: Choose which column index to insert new data


code:
colspecs = [(5 + 13 * i, 5 + 13 * (i + 1)) for i in range(8)]
pd.read_fwf(StringIO(s), colspecs=colspecs, header=None)

rawDescription: Reading column delimited text data in python quickly


code:
df2['ts'] = df2.index
df2

rawDescription: Calculating time elapsed on a groupby object


code:
def cintelpair3(a, b, c, d, e):
    if any([a, b, c, d, e].count(card) == 2 for card in ['Ace', 'Two']):
        print("You have a pair")

rawDescription: Checking several values/strings/variables for a pair of phrases in python 3.3


code: dd.compute(df.a.mean(), df.a.std())

rawDescription: How do I actually get dask to compute a list of delayed or dask-container-based results?

description: Actually get dask to compute a list of delayed or dask-container-based results


rawDescription: Python sorting list of tuples by frequency


code:
sortedGroups = [frozenset({'user2@a.com'}),
                frozenset({'user1@a.com', 'user3@b.com', 'user4@b.com'})]

rawDescription: Sorting rows into groups based on shared values


code:
from cffi import FFI
from numpy import uint32

__all__ = ['integer_sort']

ffi = FFI()
ffi.cdef('void spreadsort(uint32_t* begin,  size_t len);')
C = ffi.dlopen('./spreadsort.so')

def integer_sort(arr):
    assert arr.dtype == uint32, 'Expected uint32, got {}'.format(arr.dtype)
    begin = ffi.cast('uint32_t*', arr.ctypes.data)
    C.spreadsort(begin, arr.size)

rawDescription: How to sort an array of integers faster than quicksort?

description: Sort an array of integers faster than quicksort


rawDescription: Python numpy nan compare to true in arrays with strings


code: min(lst, key=abs)

rawDescription: Python - find integer closest to 0 in list


code:
import operator
sorted(people, key=operator.itemgetter('name'))

rawDescription: Sorting associative arrays in Python

description: Sorting associative arrays in Python


code: HELLO

rawDescription: How to filter only printable characters in a file on Bash (linux) or Python?

description: Filter only printable characters in a file on Bash (linux) or Python


rawDescription: Adding values to a matrix with a for loop in python


code: string2 = string1.translate(None, ";.,:")

rawDescription: Removing many types of chars from a Python string


rawDescription: Python mock object instantiation

description: Python mock object instantiation


rawDescription: scatter plot in matplotlib

description: Scatter plot in matplotlib


rawDescription: Python: Iterating through a set so we don't compare the same objects multiple times?


code:
# Make a copy of ds1 to initialize output array
out = ds1.copy()

# Find out the row indices in ds2 that have intersecting elements between
# its first column and ds1
_,C = np.where(ds1.ravel()[:,None] == ds2[:,0])

# New values taken from the second column of ds2 to be put in output
newvals = ds2[C,1]

# Valid positions in output array to be changed
valid = np.in1d(ds1.ravel(),ds2[:,0])

# Finally make the changes to get desired output
out.ravel()[valid] = newvals

rawDescription: Any function in numpy/pandas/python to search and replace


code: return traced

rawDescription: higher order function python walkthrough

description: Higher order function python walkthrough


code: not (matrix_a < matrix_b).any()

rawDescription: Elegant way to check empty result of numpy.nonzero


code:
import numpy as np
a = np.array([[], [(2, 0), (2, 2)], [(2, 2), (2, 0), (2, 1), (2, 2)]], dtype=object)

s = a.tolist()  # Lists are a better container type for your data...
cols = len(s)
rows = max( len(l) for l in s)

m = np.ones((cols, rows, 2))*np.nan

rawDescription: Reshape list of unequal length lists into numpy array


rawDescription: Dealing with wacky encodings in Python

description: Dealing with wacky encodings in Python


code:
tok_from_to = ['-'.join(tok[max(i-3, 0): min(i, len(l))]) for i in range(2, len(l)+2)]
# ['sil-dh', 'sil-dh-ax', 'dh-ax-t', 'ax-t-r', 't-r-ih', 'r-ih-p', 'ih-p']
val_from = [0] + val[:-1]
val_to = val[2:] + [end_point]*2

rawDescription: Operation on current, precedent, and succeeding element in a list


code:
from operator import add

flattened = rdd.flatMap(lambda kv: ((v, kv[0]) for v in kv[1])) # Flatten input
flattened.first()
# (1, 3) <- from (3, [1, 4])

result = (flattened
    .join(flattened) # Perform self join using value from input as key
    .filter(filter_source) # Remove pairs from the same source
    .map(swap)
    .reduceByKey(add)
    .map(reshape)) # Get final output

rawDescription: Alternatives to cartesian in Spark?

description: Alternatives to cartesian in Spark


code: price = just.split(":")[1]

rawDescription: Get only numbers from string in python

description: Get only numbers from string in python


rawDescription: Reduce Two Pandas Series to a Single One


code:
from itertools import chain, combinations
import copy
from nltk.util import ngrams

def pad_sequence(sequence, n, pad_left=False, pad_right=False, pad_symbol=None):
    if pad_left:
        sequence = chain((pad_symbol,) * (n-1), sequence)
    if pad_right:
        sequence = chain(sequence, (pad_symbol,) * (n-1))
    return sequence

def skipgrams(sequence, n, k, pad_left=False, pad_right=False, pad_symbol=None):
    sequence_length = len(sequence)
    sequence = iter(sequence)
    sequence = pad_sequence(sequence, n, pad_left, pad_right, pad_symbol)

    if sequence_length + pad_left + pad_right < k:
        raise Exception("The length of sentence + padding(s) < skip")

    if n < k:
        raise Exception("Degree of Ngrams (n) needs to be bigger than skip (k)")

    history = []
    nk = n+k

    # Return point for recursion.
    if nk < 1:
        return
    # If n+k longer than sequence, reduce k by 1 and recur
    elif nk > sequence_length:
        for ng in skipgrams(list(sequence), n, k-1):
            yield ng

    while nk > 1: # Collects the first instance of n+k length history
        history.append(next(sequence))
        nk -= 1

    # Iterative drop first item in history and picks up the next
    # while yielding skipgrams for each iteration.
    for item in sequence:
        history.append(item)
        current_token = history.pop(0)
        # Iterates through the rest of the history and
        # pick out all combinations the n-1grams
        for idx in list(combinations(range(len(history)), n-1)):
            ng = [current_token]
            for _id in idx:
                ng.append(history[_id])
            yield tuple(ng)

    # Recursively yield the skigrams for the rest of seqeunce where
    # len(sequence) < n+k
    for ng in list(skipgrams(history, n, k-1)):
        yield ng

rawDescription: How to compute skipgrams in python?

description: Compute skipgrams in python


code:
pattern1 = r"""(?x)               # set flag to allow verbose regexps
              ([A-Z]\.)+         # abbreviations, e.g. U.S.A.
              |\$?\d+(\.\d+)?%? # numbers, incl. currency and percentages
              |\w+([-']\w+)*    # words w/ optional internal hyphens/apostrophe
              |[+/\-@&*]        # special characters with meanings
              |\S\w*                       # any sequence of word characters#
"""
text="My weight is about 68 kg, +/- 10 grams."
re.findall(pattern1, text)
pattern2 = r"""(?x)                   # set flag to allow verbose regexps
                      (?:[A-Z]\.)+           # abbreviations, e.g. U.S.A.
                      |\d+(?:\.\d+)?%?       # numbers, incl. currency and percentages
                      |\w+(?:[-']\w+)*       # words w/ optional internal hyphens/apostrophe
                      |(?:[+/\-@&*])         # special characters with meanings
                    """
text="My weight is about 68 kg, +/- 10 grams."
re.findall(pattern2, text)

rawDescription: Python: Regular Expression not working properly


code: #!/usr/bin/env python2

rawDescription: how to run scripts with multiple python versions installed?

description: Run scripts with multiple python versions installed


rawDescription: python get list element according to alphabet

description: Python get list element according to alphabet


rawDescription: Finding indices in Python lists efficiently (in comparison to MATLAB)


code:
def adder(n):
    return lambda x: x + n

rawDescription: Write pure and functional code in Python using the concept higher-order functions like in JavaScript


code:
def readData():
    bank = []
    with open("example.txt", "r") as file:
        for line in file:
            bank += [int(i) if i.isdigit() else i for i in line.split()]
    return bank

rawDescription: Inputting a file of mixed data types and converting numbers into ints using Python


code:
All_data = [read_matrix(f) for f in Matrix_files]

Some_data = [read_matrix(f)['data'] for f in Matrix_files]

rawDescription: Load many files into one array - Python

description: Load many files into one array - Python


rawDescription: Iterate through list and going back one item


code:
NUMERALS_TRANSLATION_TABLE = {
    i: unicode(unicodedata.digit(unichr(i)))
    for i in range(2 ** 16) if unichr(i).isdigit()}
NUMERALS_TRANSLATION_TABLE.update(
    (i, u'.') for i in range(2 ** 16)
    if 'DECIMAL SEPARATOR' in unicodedata.name(unichr(i), ''))

rawDescription: Convert unicode representation of number to ascii string


code:
if getattr(report_v1, 'cache', None) is None:
    report_v1.cache = {}

rawDescription: Can I batch incrementing values in order to reduce database writes?

description: Batch incrementing values in order to reduce database writes


code:
def agreeing_members(member_to_votes, threshold):
    return [
        [a, b] for a, b in itertools.combinations(member_to_votes.keys(), 2)
        if votes_agree(member_to_votes[a], member_to_votes[b], threshold)
    ]

rawDescription: Create edgelist from a python dictionary


code: outlist2 = [x for x in os.listdir(path) if not x.endswith('.zip')]

rawDescription: python evaluate bool within a list comprehension

description: Python evaluate bool within a list comprehension


code: yi = np.interp(xi, x, y)

rawDescription: Extraploation with 'nearest' method in Python


rawDescription: Getting the number of iterations of scipy's gmres iterative method


rawDescription: Function being called even though Matplotlib button hasn't been clicked


code:
def img_to_bitmap(image, pixel_value):
    hdc = win32gui.CreateCompatibleDC(0)
    dc = win32gui.GetDC(0)
    hbm = win32gui.CreateCompatibleBitmap(dc, size, size)
    hbm_save = win32gui.SelectObject(hdc, hbm)
    for x in range(size):
        for y in range(size):
            pixel = image.getpixel((x, y))
            v = pixel_value(pixel)
            win32gui.SetPixelV(hdc, x, y, v)
    win32gui.SelectObject(hdc, hbm_save)
    win32gui.ReleaseDC(self.hwnd, hdc)
    win32gui.ReleaseDC(self.hwnd, dc)
    return hbm

rawDescription: Shell_NotifyIcon from RGB data

description: Shell_NotifyIcon from RGB data


code:
fruit_list = ['raspberry', 'apple', 'strawberry']
[ i for i, word in enumerate(fruit_list) if word.endswith('berry') ]

rawDescription: Python: get list indexes using regular expression?


code:
demjson.decode()
import demjson

# from
js_obj = '{x:1, y:2, z:3}'

# to
py_obj = demjson.decode(js_obj)

rawDescription: How to convert raw javascript object to python dictionary?

description: Convert raw javascript object to python dictionary


code:
from lxml import etree
from lxml.builder import E

camera_matrix=[[ 532.80990646 ,0.0,342.49522219],[0.0,532.93344713,233.88792491],[0.0,0.0,1.0]]
dist_coeff = [-2.81325798e-01,2.91150014e-02,1.21234399e-03,-1.40823665e-04,1.54861424e-01]

def triada(itm):
    a, b, c = itm
    return E.Triada(a = str(a), b = str(b), c = str(c))

camera_matrix_xml = E.CameraMatrix(*map(triada, camera_matrix))
dist_coeff_xml = E.DistCoef(*map(E.Coef, map(str, dist_coeff)))

xmldoc = E.CameraData(camera_matrix_xml, dist_coeff_xml)

fname = "data.xml"
with open(fname, "w") as f:
    f.write(etree.tostring(xmldoc, pretty_print=True))

rawDescription: Writing camera matrix into xml/yaml file


code:
DEBUG = True

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'myprojectname/static'),
)

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/

STATIC_URL = '/static/'

rawDescription: Django stylesheet will not load

description: Django stylesheet will not load


code: df.Xi.round(5).reshape(len(df), 1)

rawDescription: I want to take data from CSV file and to put into Two different arrays variables


code:
class FooProvider:
    def foo(self, **kwargs):
        assert not kwargs  # Make sure all kwargs have been stripped

class Bar(FooProvider):
    def foo(self, x, **kwargs):
        self.x = x
        super().foo(**kwargs)

class Baz(FooProvider):
    def foo(self, y, **kwargs):
        self.y = y
        super().foo(**kwargs)

class Qux(Bar, Baz):
    def foo(self, z, **kwargs):
        self.z = z
        super().foo(**kwargs)

rawDescription: Python Multiple Inheritance: Argument passing (**kwargs) and super()


code:
provider = request.POST.get('provider')

order_items = OrderItem.objects.all()
if provider is not None:
    order_items = order_items.filter(provider=provider)

rawDescription: Django wildcard query

description: Django wildcard query


code:
#!/usr/bin/env python3

def write_random_binary_stream(write):
    while True:
        write(getrandbits(32).to_bytes(4, 'big'))

if __name__ == "__main__":
    import sys
    write_random_binary_stream(sys.stdout.buffer.write)

rawDescription: Python Random Function without using random module


code:
SuperClass().print()
Sub1().print()

rawDescription: print all SubClass in a SuperClass and all SuperClass in a SubClass

description: Print all SubClass in a SuperClass and all SuperClass in a SubClass


code:
import sympy
sympy.init_printing(use_unicode=True)

from sympy.printing.pretty.stringpict import prettyForm, stringPict

def newDiv(self, den, slashed=False):
    if slashed:
        raise NotImplementedError("Can't do slashed fraction yet")
    num = self
    if num.binding == prettyForm.DIV:
        num = stringPict(*num.parens())
    if den.binding == prettyForm.DIV:
        den = stringPict(*den.parens())

    return prettyForm(binding=prettyForm.DIV, *stringPict.stack(
        num,
        stringPict.LINE,
        den))

prettyForm.__div__ = newDiv

sympy.pprint(sympy.Mul(-1, sympy.Pow(-5, -1, evaluate=False), evaluate=False))

# Displays properly:
# -1
# ──
# -5

rawDescription: Not aligned Sympy's nice pritting of division


code:
for i in data:
    print(i)               #prints list of characters in a not-so-nice format

rawDescription: Mutation algorithm python

description: Mutation algorithm python


rawDescription: Checking for unique output in Python

description: Checking for unique output in Python


code: np.linspace(0, 2, 9)

rawDescription: Rescale a numpy array

description: Rescale a numpy array


code:
def dehydrate(self, bundle):
     if bundle.request.META['REQUEST_METHOD'] == 'POST':
         bundle.data = dict(my_field1=bundle.obj.my_func1(),
                            my_field2=bundle.obj.my_func2()
                            )
     return bundle

rawDescription: exclude some fields in tastypie post data

description: Exclude some fields in tastypie post data


code:
col={'Car','Car sales','Cars','Sports cars','Sports foo','Car bar','Statistics'}
col={i.lower() for i in col}
s="Find sports car sales statistics in Manhattan."
col.intersection(s.strip('.').split())

rawDescription: Searching for Phrase Keywords in MySQL

description: Searching for Phrase Keywords in MySQL


rawDescription: In python, how can I can I code this sense: "when true for all members of the list, do this." [Solved]


code:
from xml.dom.minidom import Document

doc = Document()
root = doc.createElement('root')
doc.appendChild(root)
for i in range(1,3):
    main = doc.createElement('item')
    main.attributes['class']='memory'
    root.appendChild(main)
    for j in range(1,3):
        p = doc.createElement('p')
        text = doc.createTextNode('DIMM Size'+str(j))
        p.appendChild(text)
        main.appendChild(p)

print (doc.toprettyxml(indent='\t'))

rawDescription: Issue in generating the xml file from python minidom


code: city_found = cities['_find'](cities, state)

rawDescription: python underscores: learn python the hard way exercise 40

description: Python underscores: learn python the hard way exercise 40


code:
from mongoengine import Document
from multilingual_field.fields import MultilingualStringField

class MyDoc(Document):
    name = MultilingualStringField()

doc = MyDoc(name={'en': 'Hermitage', 'ru': u'Эрмитаж'})
doc.translate('en')
doc.name  #  'Hermitage'
doc.translate('ru')
doc.name  #  u'Эрмитаж'
doc.translate('en')
doc.name = 'The Hermitage'
doc.name.translations  # {'en_US.ISO8859-1': 'The Hermitage', 'ru_RU.UTF-8': u'Эрмитаж'}

rawDescription: Is there ready to use multilingual string field for MongoEngine?


rawDescription: Can rectangle be used as a parent class (tkinter)?


code: self.gui.after(2000, self.AI)

rawDescription: How to call a function with delay in tkinter?

description: Call a function with delay in tkinter


code:
relation3 = {'Jerry': ['George', 'Elaine'], 'Elaine':['Kramer']}
dict2pairs(relation3)
[('Jerry', 'George'), ('Jerry', 'Elaine'), ('Elaine', 'Kramer')]

rawDescription: Python dictionary to pairs and check for antisymmetry using dictionary


code:
import scipy.interpolate as interp   #the new one

# assume you have X,Y,Z,levels defined as before

# start resampling stuff
dN = 10 # use every dN'th element of the gridded input data
my_slice = [slice(None,None,dN),slice(None,None,dN)]

# downsampled data
X2,Y2,Z2 = X[my_slice],Y[my_slice],Z[my_slice]
# same as X2 = X[::dN,::dN] etc.

# upsampling with griddata over original mesh
Zsmooth = interp.griddata(np.array([X2.ravel(),Y2.ravel()]).T,Z2.ravel(),(X,Y),method='cubic')

# plot
plt.figure()
CS = plt.contour(X, Y, Zsmooth, colors='b', linewidths=2, levels=levels)

rawDescription: How to remove/omit smaller contour lines using matplotlib

description: Remove/omit smaller contour lines using matplotlib


rawDescription: String to list of list

description: String to list of list


code: l2 = [type(obj)(2) for obj in l]

rawDescription: Creating copy of arbitrary object in Python and calling constructor


rawDescription: pulling min and max values from list of list

description: Pulling min and max values from list of list


code:
setattr(MyObject,"ret", ret)
MyObject().ret()
MyObject().ret().l

rawDescription: Return statement in method that modifies in-place


code:
class Post(db.Model):
  desc = db.StringProperty()

class Comment(db.Model):
  desc = db.TextProperty()

rawDescription: GAE datastore cache keys vs filter

description: GAE datastore cache keys vs filter


rawDescription: Aligning two lists with duplicate keys

description: Aligning two lists with duplicate keys


code:
pat = '"Parcels \([0-9]+-[0-9]+-[0-9]+\)"'
match = re.search(pat, t)
print(match.group())

rawDescription: Python look for pattern in string

description: Python look for pattern in string


code:
import __builtin__
range = __builtin__.range

rawDescription: How to restore a builtin when parameter has same name?

description: Restore a builtin when parameter has same name


code:
r
r.to_dict()

rawDescription: pandas df.loc[z,x]=y how to improve speed?

description: Pandas df.loc[z,x]=y how to improve speed


rawDescription: 2 d interpolation with the arrays with different dimensions in python


code:
def addHandler(self, hdlr):
    """
    Add the specified handler to this logger.
    """
    _acquireLock()
    try:
        if not (hdlr in self.handlers):
            self.handlers.append(hdlr)
    finally:
        _releaseLock()

rawDescription: Is there an easy way to add handlers to the logger object?


code:
import xml.etree.ElementTree as ET
from pprint import pprint

news_sources = {
    source.attrib['source'] : [feed.text for feed in source]
    for source in ET.parse('x.xml').getroot()}

pprint(news_sources)

rawDescription: Generating nested lists from XML doc

description: Generating nested lists from XML doc


code:
url(r'^venue/all/$', 'all_venues', name='all_venues'),
url(r'^venue/(?P<venue_id>\d+)/$', 'venue', name='venue'),

rawDescription: django create profile or page for object

description: Django create profile or page for object


code:
from ctypes import *

class mystruct(Structure):
    _fields_ = [("str", c_char*100),
                ("str_length", c_long),
                ("count", c_long)]

s = b"ABC" * 10
c = 44

a = mystruct(s, len(s), c)

# print byte representation of structure
print(bytes(a))

print(a.str)
print(a.str_length)
print(a.count)

rawDescription: generating a binary buffer with python to be read in C as a struct

description: Generating a binary buffer with python to be read in C as a struct


code:
# Import numpy symbols to scipy name space
import numpy as _num
from numpy import oldnumeric
from numpy import *
from numpy.random import rand, randn
from numpy.fft import fft, ifft
from numpy.lib.scimath import *

rawDescription: Relationship between scipy and numpy

description: Relationship between scipy and numpy


code:
from django.db.models import Count

users = User.objects.annotate(num_followers=Count('to_users')).order_by('-num_followers')

rawDescription: Django - access foreign key data in an annotated query


code: divmod(x.argmin(), x.shape[1])

rawDescription: Numpy: get the column and row index of the minimum value of a 2D array


code:
# Functions to trace
# ==================

def baz():
    pass

def baz2():
    pass

def bar():
    baz()
    baz2()

def log():
    pass

def foo():
    bar()
    log()

def finish():
    pass

def insertVideoEntry():
    foo()
    finish()

# Names to trace
# ==============

names = list(locals())

# Machinery for tracing
# =====================

import os
import sys

def trace(start, *names):
    def tracefunc(frame, event, arg):
        if event == 'call':
            code = frame.f_code
            name = code.co_name
            if name in names:
                level = -start
                while frame:
                    frame = frame.f_back
                    level += 1
                print('{}{}.{}()'.format(
                    '    ' * level,
                    os.path.splitext(os.path.basename(code.co_filename))[0],
                    name))
                return tracefunc
    sys.settrace(tracefunc)

# Demonstration of tracing
# ========================

trace(2, *names)

insertVideoEntry()

rawDescription: How can I step to use the python debugger to break at every function call?

description: Step to use the python debugger to break at every function call


code:
import ctypes

def GetTextDimensions(text, points, font):
    class SIZE(ctypes.Structure):
        _fields_ = [("cx", ctypes.c_long), ("cy", ctypes.c_long)]

    hdc = ctypes.windll.user32.GetDC(0)
    hfont = ctypes.windll.gdi32.CreateFontA(points, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, font)
    hfont_old = ctypes.windll.gdi32.SelectObject(hdc, hfont)

    size = SIZE(0, 0)
    ctypes.windll.gdi32.GetTextExtentPoint32A(hdc, text, len(text), ctypes.byref(size))

    ctypes.windll.gdi32.SelectObject(hdc, hfont_old)
    ctypes.windll.gdi32.DeleteObject(hfont)

    return (size.cx, size.cy)

print(GetTextDimensions("Hello world", 12, "Times New Roman"))
print(GetTextDimensions("Hello world", 12, "Arial"))

rawDescription: How to calculate length of string in pixels for specific font and size?

description: Calculate length of string in pixels for specific font and size


code: d = {'Four': [i for i in range(100) if not i % 4]}

rawDescription: Is it possible to alter the values in a dictionary, keeping the key value constant?


code:
from pandas.io.parsers import read_csv
# this will be printed as dict to screen
read_auto(PATHFILE, inferOnly=True)
{'filepath_or_buffer': PATHFILE, 'skiprows':1, 'sep':',', 'quotechar':'"'}

# Copy and paste the dictionary info into the file, e.g. store it in "info"
info = {'filepath_or_buffer': PATHFILE, 'skiprows':1, 'sep':',', 'quotechar':'"'}
read_csv(**info)

rawDescription: Automatic parsing of data in Python

description: Automatic parsing of data in Python


rawDescription: Most efficient way to populate dictionary keys with dictionary


rawDescription: pandas Subtract Dataframe with a row from another dataframe

description: Pandas Subtract Dataframe with a row from another dataframe


code:
a = np.random.randint(10, size=(5, 5))
a
neighbor_min(a)

rawDescription: Numpy: fast calculations considering items' neighbors and their position inside the array


code:
import xlrd
getattr(xlrd, next(item for item in dir(xlrd) if 'version' in item.lower()))

rawDescription: Cannot find python xlrd version

description: Cannot find python xlrd version


code: pd.concat([get_sumdf(area_tab) for area_tab in areas_tabs])

rawDescription: Create a summary Pandas DataFrame using concat/append via a for loop


code:
now = dt.datetime.utcnow()
datetimes = [now - dt.timedelta(hours=6) * i for i in range(10)]
datetimes

rawDescription: Find Unique Dates in Numpy Datetime Array


code: csv_file.open(file, mode="w")

rawDescription: Modify csv files with Python

description: Modify csv files with Python


code:
import os
userprofile = os.environ['USERPROFILE']
path = os.path.join(userprofile, 'Documents', 'ArcGIS', 'file1.gdb')

rawDescription: Save a file depending on the user Python


rawDescription: Python 2.6.5: Divide timedelta with timedelta


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

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


code:
import shelve

d = shelve.open('filename')

d['name'] = 'path'

d.close()

rawDescription: Efficient way to store hash in a file

description: Efficient way to store hash in a file


code:
def get_union_by_model(self, queryset_or_model, tags):
    """
    Create a ``QuerySet`` containing instances of the specified
    model associated with *any* of the given list of tags.
    """
    tags = get_tag_list(tags)
    tag_count = len(tags)
    queryset, model = get_queryset_and_model(queryset_or_model)

    if not tag_count:
        return model._default_manager.none()

    model_table = qn(model._meta.db_table)
    # This query selects the ids of all objects which have any of
    # the given tags.
    query = """
    SELECT %(model_pk)s
    FROM %(model)s, %(tagged_item)s
    WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
      AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
      AND %(model_pk)s = %(tagged_item)s.object_id
    GROUP BY %(model_pk)s""" % {
        'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
        'model': model_table,
        'tagged_item': qn(self.model._meta.db_table),
        'content_type_id': ContentType.objects.get_for_model(model).pk,
        'tag_id_placeholders': ','.join(['%s'] * tag_count),
    }

    cursor = connection.cursor()
    cursor.execute(query, [tag.pk for tag in tags])
    object_ids = [row[0] for row in cursor.fetchall()]
    if len(object_ids) > 0:
        return queryset.filter(pk__in=object_ids)
    else:
        return model._default_manager.none()

rawDescription: Union and Intersect in Django

description: Union and Intersect in Django


code:
arrays = range(0, 2), range(4, 6), range(8, 10)
list(itertools.product(*arrays))

rawDescription: Dimensionality agnostic (generic) cartesian product


rawDescription: zip, sorted and pandas

description: Zip, sorted and pandas


code:
# parameters
category_id = '1234'

# query-1:
q = Gift.query.join(SubCategory).filter(SubCategory.category_id == category_id)

# query-2:
category = session.query(Category).get(category_id)
q = Gift.query.join(SubCategory).filter(SubCategory.category == category)

rawDescription: How to access child of child from parent in sqlalchemy?

description: Access child of child from parent in sqlalchemy


code:
TEMPLATE_CONTEXT_PROCESSORS = (
   "django.core.context_processors.request",
   "django.core.context_processors.media",
   "django.contrib.messages.context_processors.messages"
)

rawDescription: Django Message framework is not showing message in template


code:
import lxml.etree as etree

string = '''
<data>

1234545667abcde

</data>
'''

tree = etree.fromstring(string)

print(tree.xpath('//p//text()'))

rawDescription: Extract all the text from xml data with python


code:
if user.is_active:
    login(request, user)
    login_dict = {
        'user': user,
        'your_desired_value': desired_value, # your new variable
    }
    max_age = 60 * 60
    response = render(request, 'index.html', login_dict)
    response.set_cookie('logged_in', request.POST['email'], max_age)
    return response

rawDescription: Django: Accessing cookie value set in views.py in html template?


rawDescription: Convert int to raw data in python

description: Convert int to raw data in python


rawDescription: Overwriting (updating) a pandas Series with values from another Series?


rawDescription: reshaping ndarrays versus regular arrays in numpy?

description: Reshaping ndarrays versus regular arrays in numpy


code:
# How to treat negative values?
# 'mask' will treat negative values as invalid
# 'mask' is the default, so the next two lines are equivalent
pyplot.xscale('log')
pyplot.xscale('log', nonposx='mask')

rawDescription: What is the difference between 'log' and 'symlog'?


rawDescription: Getting header row from numpy.genfromtxt


code:
for ele in l:
    ln = len(ele)
    if 7 <= ln > 10:
        out.append(ele)
        continue
    for patt in ["%d/%m/%Y", "%d-%m-%Y"]:
        try:
            p1 = datetime.strptime(ele,patt).strftime("%Y-%m-%d")
            if p1:
                out.append(p1)
                break
        except ValueError as e:
            print(e)
    else:
        out.append(ele)

rawDescription: Python - Regular Expression to find dates in list


code:
class CsvWriter(object):

  def __init__(self, dictList):
    self.maxline = max(dictList, key=len)
    self.dictList = [dict((k,k) for k in self.maxline)]
    self.dictList.extend(dictList)

  def doWrite(self, outfile):
    csv_file=open(outfile,'ab')
    writer = csv.DictWriter(csv_file,
                            fieldnames=self.maxLine.keys(),
                            restval='notScanned',
                            dialect='excel')
    for dataLine in self.dictList:
        writer.writerow(dataLine)
    csv_file.close()

rawDescription: How to create a class from function

description: Create a class from function


code: [ [(label, bars_to_span), ...], ..., [(tick_label, bar_value), ...] ]

rawDescription: How to add group labels for bar charts in matplotlib?

description: Add group labels for bar charts in matplotlib


rawDescription: Common elements between two lists of lists (intersection of nested lists)


code:
import datetime
import dateutil.tz
datetime.datetime(2013, 9, 11, 0, 17, tzinfo=dateutil.tz.tzoffset(None, 9*60*60))
datetime.datetime(2013, 9, 11, 0, 17, tzinfo=dateutil.tz.tzoffset('KST', 9*60*60))

rawDescription: How to set UTC offset for datetime?

description: Set UTC offset for datetime


code: chunks = [format2[chunk] for chunk in start_stop]

rawDescription: Writing python chunking loops with reference to another txt


code:
test_script = """
    log.print("hi")
    func(a, "12345")
    func(a, msg="12345")
    func(a)
    func(k=a)
    """

rawDescription: pattern to match 1-or-2-arg function call for lib2to3

description: Pattern to match 1-or-2-arg function call for lib2to3


code: from __future__ import print_function

rawDescription: Self Modifying Python? How can I redirect all print statements within a function without touching sys.stdout?


code:
import numpy_indexed as npi
idx = np.indices(largearray.shape).reshape(largearray.ndim, largearray.size)
label, mean = npi.group_by(largearray, axis=None).mean(idx, axis=1)

rawDescription: Find center coordinates of regions in a 3d numpy array


code:
z = zipfile.ZipFile(sourceFile, 'r')
info = z.getinfo('fileToTest.ext')
print ("create_system", info.create_system)
print ("external_attr", info.external_attr)
print ("internal_attr", info.internal_attr)

rawDescription: Preserve file attributes in ZipFile

description: Preserve file attributes in ZipFile


code:
import itertools
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)
# flatten the message [[1],[2]] -> [1,2]
message = (item for thing in message for item in thing)

rawDescription: 3x1 Matrix Multiplication with lists[UPDATED]


rawDescription: How to calculate CRC32 with Python to match online results?

description: Calculate CRC32 with Python to match online results


code: quantized = img.convert('P', palette=Image.ADAPTIVE, colors=4)

rawDescription: convert image to value matrix

description: Convert image to value matrix


code:
import re
re.sub('[^\d]', ' ', '12345 hdjhdjf dfdfd "dfd" 12333.')

rawDescription: Replace a blank space followed by text with a blank space using string replace


rawDescription: Use Updated Value In Array

description: Use Updated Value In Array


rawDescription: Python random unique values from two non overlapping ranges


code:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

Base = declarative_base()
class DataBase(object):
    def __init__(self, Base):
        self.Base = Base
        self.engine = create_engine('sqlite:///')
        self.session = sessionmaker()
        self.session.configure(bind=self.engine)
        self.s = self.session()
        self.Base.metadata.create_all(self.engine)

    def Add_Record(self, data):
        record = self.Listing(self.engine, **data)
        self.s.add(record)

    def Commit(self):
        self.s.commit()

    def Close(self):
        self.s.close()

    class Empty_Init():
        def __init__(self, engine, **kwargs):
            #This class and the structure of the table need to be sync'd.
            for k,v in kwargs.items():
                   if hasattr(self, k): #if the class already has the attribute initialized,
                    setattr(self, k, v) # then assign it the new value
                   else: # if it doesn't...
                    if k not in engine.execute("SELECT * FROM `{tbl}`".format(tbl = self.__tablename__))._metadata.keys:
                        engine.execute("ALTER TABLE `{tbl}` ADD COLUMN {col} {typ}".format(
                                    tbl = self.__tablename__,
                                    col = k,
                                    typ = "INT" if type(v) is int else ("DOUBLE" if type(v) is float else "VARCHAR")))
                    setattr(self.__class__, k, Column(k, String))
                    setattr(self, k, v)

    class Listing(Empty_Init, Base):
        __tablename__ = 'Listings'
        __table_args__ = {'sqlite_autoincrement': True}
        id = Column(Integer, primary_key=True, nullable=False)
        make = Column(String)
        model = Column(String)
        year = Column(Integer)

rawDescription: Wrap SQLAlchemy in Classes in Python

description: Wrap SQLAlchemy in Classes in Python


rawDescription: Representing rings of algebraic integers


code: npcs = [Character (name) for name in ['Baldur', 'Lord Never', 'Ashyra'] ]

rawDescription: Python - Compare two lists and find matching values and their positions in the list


code:
some_dict = {key: value for key, value in some_dict.items()
             if value is not value_to_remove}

rawDescription: Best way to remove an item from a Python dictionary?

description: Remove an item from a Python dictionary


rawDescription: Python regex multiline replacement

description: Python regex multiline replacement


code:
ScoreList = []

for key, value in ScoreDict.iteritems():
  temp = []

  temp.append(key)
  temp.extend(value.values())

  ScoreList.append(temp)

rawDescription: (Python) Converting a dictionary to a list?


code:
result = [
  [(value, randomDate(...)) for value in row]
  for row in genenerate_random_matrix(...)
]

rawDescription: Mapping tuple (R, R) into ((R,R),R)?

description: Mapping tuple (R, R) into ((R,R),R)


code: from braintree_python.braintree import TestingGateway

rawDescription: importing TestHelper from braintree

description: Importing TestHelper from braintree


code:
bigstr = 'What are you saying?'
smallstr = 'you'
bigstr.split(smallstr)
words = bigstr.split(smallstr)
len(words[0])
len(words[1])

rawDescription: Distance from str to the end (python)

description: Distance from str to the end (python)


code: g = df.groupby('column_name')

rawDescription: Replace rarely occurring values in a pandas dataframe


code:
dir(my_ast)
my_ast.body
with_stmt = my_ast.body[2]
dir(with_stmt)
with_stmt.lineno
with_stmt.body
assign1 = with_stmt.body[0]
dir(assign1)
assign1.value

rawDescription: Recommended Compiler Parse Tree Data Structure


rawDescription: How do Python methods handle arbitrary parameters?


code:
def addItems(cls):
    cls.items = []
    cls.items.append(1)
    return cls

rawDescription: How to use a decorator to modify mutable class variables?

description: Use a decorator to modify mutable class variables


code:
class TestReader(BufferedReader):
    def close(self):
        self.closed = True

rawDescription: prevent BufferedReader from closing the file for a list of files

description: Prevent BufferedReader from closing the file for a list of files


code:
from urlparse import urlparse
import re
class SvnExternalsLine:
    '''Consult https://subversion.apache.org/docs/release-notes/1.5.html#externals for parsing algorithm.
    The old svn:externals format consists of:
        <local directory> [revision] <absolute remote URL>

    The NEW svn:externals format consists of:
        [revision] <absolute or relative remote URL> <local directory>

    Therefore, "relative" remote paths always come *after* the local path.
    One complication is the possibility of local paths with spaces.
    We just assume that the remote path cannot have spaces, and treat all other
    tokens (except the revision specifier) as part of the local path.
    '''

    REVISION_ARGUMENT_REGEXP = re.compile("-r(\d+)")

    def __init__(self, original_line):
        self.original_line = original_line

        self.pinned_revision_number = None
        self.repo_url = None
        self.local_pathname_components = []

        for token in self.original_line.split():

            revision_match = self.REVISION_ARGUMENT_REGEXP.match(token)
            if revision_match:
                self.pinned_revision_number = int(revision_match.group(1))
            elif urlparse(token).scheme or any(map(lambda p: token.startswith(p), ["^", "//", "/", "../"])):
                self.repo_url = token
            else:
                self.local_pathname_components.append(token)

    # ---------------------------------------------------------------------
    def constructLine(self):
        '''Reconstruct the externals line in the Subversion 1.5+ format'''

        tokens = []

        # Update the revision specifier if one existed
        if self.pinned_revision_number is not None:
            tokens.append( "-r%d" % (self.pinned_revision_number) )

        tokens.append( self.repo_url )
        tokens.extend( self.local_pathname_components )

        if self.repo_url is None:
            raise Exception("Found a bad externals property: %s; Original definition: %s" % (str(tokens), repr(self.original_line)))

        return " ".join(tokens)

rawDescription: Script/utility to rewrite all svn:externals in repository trunk


code:
x = fmin_slsqp(f2, (5,45), f_eqcons=h, f_ieqcons=g)
print(x)

rawDescription: Weight Middle Range for use of scipy.optimize.linprog (Simplex algorithm)


code:
import re
import urlparse

s = '?attr[foo]=1&attr[bar]=2'

def parse(s):
    d = {}
    for key, value in urlparse.parse_qs(s).items():
        match = re.match(r'(?P<key>[^\[]+)\[(?P<value>[^\]]+)\]', key)
        gd = match.groupdict()
        d.setdefault(gd['key'], {})[gd['value']] = value[0]
    return d

print(parse(s[1:]))

rawDescription: Decode bracket-encoded dictionary in query string


code:
import bisect
# your code here
numset2.sort()
L = len(numset2)
numPossibilities = sum([bisect.bisect_right(numset2,n1) < L for n1 in numset1])

rawDescription: Improve performance on Python nested for loop


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

# Create your palette
cmap = sns.diverging_palette(0,255,sep=77, as_cmap=True)

# Some data with a range of 0 to 20
x = np.linspace(0,20,20).reshape(4,5)

# Plot a heatmap (I turned off the cbar here, so I can create it later with ticks spaced every integer)
ax = sns.heatmap(x, cmap=cmap, vmin=0, vmax=20, cbar = False)

# Grab the heatmap from the axes
hmap = ax.collections[0]

# make a colorbar with ticks spaced every integer
cmap = plt.gcf().colorbar(hmap)
cmap.set_ticks(range(21))

plt.show()

rawDescription: Creating a diverging color palette with a "midrange" instead of a "midpoint"


code:
import math

def area_for_polygon(polygon):
    result = 0
    imax = len(polygon) - 1
    for i in range(0,imax):
        result += (polygon[i]['x'] * polygon[i+1]['y']) - (polygon[i+1]['x'] * polygon[i]['y'])
    result += (polygon[imax]['x'] * polygon[0]['y']) - (polygon[0]['x'] * polygon[imax]['y'])
    return result / 2.

def centroid_for_polygon(polygon):
    area = area_for_polygon(polygon)
    imax = len(polygon) - 1

    result_x = 0
    result_y = 0
    for i in range(0,imax):
        result_x += (polygon[i]['x'] + polygon[i+1]['x']) * ((polygon[i]['x'] * polygon[i+1]['y']) - (polygon[i+1]['x'] * polygon[i]['y']))
        result_y += (polygon[i]['y'] + polygon[i+1]['y']) * ((polygon[i]['x'] * polygon[i+1]['y']) - (polygon[i+1]['x'] * polygon[i]['y']))
    result_x += (polygon[imax]['x'] + polygon[0]['x']) * ((polygon[imax]['x'] * polygon[0]['y']) - (polygon[0]['x'] * polygon[imax]['y']))
    result_y += (polygon[imax]['y'] + polygon[0]['y']) * ((polygon[imax]['x'] * polygon[0]['y']) - (polygon[0]['x'] * polygon[imax]['y']))
    result_x /= (area * 6.0)
    result_y /= (area * 6.0)

    return {'x': result_x, 'y': result_y}

def bottommost_index_for_polygon(polygon):
    bottommost_index = 0
    for index, point in enumerate(polygon):
        if (point['y'] < polygon[bottommost_index]['y']):
            bottommost_index = index
    return bottommost_index

def angle_for_vector(start_point, end_point):
    y = end_point['y'] - start_point['y']
    x = end_point['x'] - start_point['x']
    angle = 0

    if (x == 0):
        if (y > 0):
            angle = 90.0
        else:
            angle = 270.0
    elif (y == 0):
        if (x > 0):
            angle = 0.0
        else:
            angle = 180.0
    else:
        angle = math.degrees(math.atan((y+0.0)/x))
        if (x < 0):
            angle += 180
        elif (y < 0):
            angle += 360

    return angle

def convex_hull_for_polygon(polygon):
    starting_point_index = bottommost_index_for_polygon(polygon)
    convex_hull = [polygon[starting_point_index]]
    polygon_length = len(polygon)

    hull_index_candidate = 0 #arbitrary
    previous_hull_index_candidate = starting_point_index
    previous_angle = 0
    while True:
        smallest_angle = 360

        for j in range(0,polygon_length):
            if (previous_hull_index_candidate == j):
                continue
            current_angle = angle_for_vector(polygon[previous_hull_index_candidate], polygon[j])
            if (current_angle < smallest_angle and current_angle > previous_angle):
                hull_index_candidate = j
                smallest_angle = current_angle

        if (hull_index_candidate == starting_point_index): # we've wrapped all the way around
            break
        else:
            convex_hull.append(polygon[hull_index_candidate])
            previous_angle = smallest_angle
            previous_hull_index_candidate = hull_index_candidate

    return convex_hull

rawDescription: Finding centre of a polygon using limited data


code:
_registry = {}

def register(choice_class):
    id = len(_registry) + 1
    choice_class.id = id
    _registry[id] = choice_class

def as_list():
    ret = []
    for id in sorted(_registry):
        ret.append((id, _registry[id].name))
    return ret

def get_choice(id):
    return _registry[id]

class SomeChoice:
    name = u"lorem"

class AnotherChoice:
    name = u"ipsum"

register(SomeChoice)
register(AnotherChoice)

rawDescription: How to store python classes into a database with Django?

description: Store python classes into a database with Django


code:
for a_item, b_item in zip(a, b):
    c.append(a_item + [b_item])

rawDescription: Unpack items and add a new one

description: Unpack items and add a new one


code:
import matplotlib
matplotlib.use("TKAGG")
import matplotlib.pyplot as pyplot
import mpl_toolkits.mplot3d

figure = pyplot.figure(figsize=(8,4), facecolor='w')
ax = figure.gca(projection='3d')

xLabel = ax.set_xlabel('\nXXX xxxxxx xxxx x xx x', linespacing=3.2)
yLabel = ax.set_ylabel('\nYY (y) yyyyyy', linespacing=3.1)
zLabel = ax.set_zlabel('\nZ zzzz zzz (z)', linespacing=3.4)
plot = ax.plot([1,2,3],[1,2,3])
ax.dist = 10

pyplot.show()

rawDescription: Move 3D plot z-axis label right (or left)


code:
result = collection.aggregate([
    # Matchn the documents possible
    { "$match": { "date": { "$gte": startdate } } },

    # Group the documents and "count" via $sum on the values
    { "$group": {
        "_id": {
            "scan_status": "$scan_status",
            "date": {
                "year": { "$year": "$date" },
                "month": { "$month" "$date" },
                "day": { "$dayOfMonth": "$date" }
            }
        },
        "count": { "$sum": 1 }
    }}
])

rawDescription: PyMongo group by multiple keys

description: PyMongo group by multiple keys


code:
#after for loop has finished
if len(h) == 0 and tree.label() == "NP":
    h.append(tree)
return h

rawDescription: Retrieve Graph Lowest Height Node with Filter


code:
def list_n(n):
    if n < 2:
       return False
    list = []
    for x in range(n):
       list.append(random.randrange(1,5))
    return list

rawDescription: Generate Random and Print List on 1 Line


code:
def category(request, category_name):
    template = 'stories/category.html'
    category = Category.objects.get(category_name = category_name)
    return render_to_response(template, {
        'category': category
        })

rawDescription: How do I turn my urls into readable names?

description: Turn my urls into readable names


code:
from datetime import datetime

sz = '2013-07-19T13:02:53.8241899Z' # utc time in rfc3339 format (without offset)

sz = sz.rstrip('Z') # remove ending 'Z' if present
timestr, _, digits = sz.partition('.')
utc_dt = datetime.strptime(timestr, '%Y-%m-%dT%H:%M:%S')
if digits:
   microseconds = int(digits, 10) * 10**(6 - len(digits))
   utc_dt = utc_dt.replace(microsecond=int(microseconds + .5))

rawDescription: python strptime from UTC string to datetime regex re.sub

description: Python strptime from UTC string to datetime regex re.sub


rawDescription: How is the return value of __hash__ used?


code:
import json

...

tv_shows = json.loads(response.read())

rawDescription: searching sickbeard api output and print only keyword line

description: Searching sickbeard api output and print only keyword line


code:
class A(object):

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

    def __add__(self, other):
        return self.__class__(self.x + other.x)

    def __repr__(self):
        return "%s with x=%s" % (self.__class__, self.x)

rawDescription: Output of Python interpreter?

description: Output of Python interpreter


code:
func = np.frompyfunc(f , 2 , 1)

def dostuff(n,f):
    final_array = func.accumulate(np.arange(0,n), dtype=np.object).astype(np.int)
    return np.sum(final_array)

rawDescription: Faster loop operating on two values of an array


code: [i.split('.')[-1] for i in data]

rawDescription: Method in python to obtain the following pattern string


code:
weighted = [ ("a", 3), ("b", 1), ("c", 4) ]
[c for c, count in weighted for _ in range(count)]
from itertools import chain
list(chain.from_iterable([c] * count for c, count in weighted))

rawDescription: Creating multiple copies of list elements


code:
import socket

def fqdn_ip():
    return {
        'fqdn_ip': socket.gethostbyname(socket.getfqdn())
    }

rawDescription: How to get IP address of hostname inside jinja template

description: Get IP address of hostname inside jinja template


code:
import csv

with open("special.csv", "rb") as infile, open("repaired.csv", "wb") as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    conversion = set('_"/.$')
    for row in reader:
        newrow = [''.join('_' if c in conversion else c for c in entry) for entry in row]
        writer.writerow(newrow)

rawDescription: Remove special characters from csv file using python


code: len(set(listA).intersection(listB)) > 0

rawDescription: How to check if any item in a list occurs in another list?

description: Check if any item in a list occurs in another list


code:
def get_songs(requested_username):
    songs = db.GqlQuery('SELECT * FROM Song WHERE username=:1 ORDER BY created DESC', requested_username)
    return songs

rawDescription: Python Queries - Web Apps, etc

description: Python Queries - Web Apps, etc


code: [(u'Remaking', u'O'), (u'The', u'O'), (u'Republican Party', u'ORGANIZATION')]

rawDescription: Chunking Stanford Named Entity Recognizer (NER) outputs from NLTK format


code:
dis.dis('"XYZ" in s')
dis.dis('s.__contains__("XYZ")')

rawDescription: Why is string's startswith slower than in?


code:
ConsomRatio = {
   "DAP_Local": {"Ammonia":"0.229", "Amine":"0.0007"},
   "MAP11_52" : {"Ammonia":"0.138", "Fuel":"0.003"},
}

print(ConsomRatio["DAP_Local"]["Ammonia"])

rawDescription: Dicts in Python

description: Dicts in Python


code:
import x
vel=x.velocity()
vel.u = [1,2,3],[4.5,6,7]
vel.v = [1,2],[3,4,5]
vel.w = [1],[2,3]
vel.u
vel.v
vel.w
x.myfunc(vel)
vel.u
vel.v
vel.w

rawDescription: Return Struct from a C++ function to Python in SWIG


code:
objiter = [repeat(x, obj[x]) for x in sorted(obj.keys())]
objlist = list(roundrobin(*objiter))
objlist
['a1', 'a2', 'a3', 'a1', 'a2', 'a1', 'a2', 'a2', 'a2']

rawDescription: printing dict keys 'value' times and alternatively like round robin scheduling

description: Printing dict keys 'value' times and alternatively like round robin scheduling


code:
def makeValue(highbyte, lowbyte):
    return int(highbyte+lowbyte[2:], 16) # strips leading "0x" from lowbyte be4 concat

rawDescription: Python BCD splitting nibbles and concatenation 2 ints


code: accum_value = function(accum_value, x)

rawDescription: Memory usage: creating one big set vs merging many small sets


code:
import os.path

filename = input("Enter name of input file >")
try:
    infile = open(filename, "r")
except IOError:
    raise Exception("Error opening file '%s', analysis will not continue" % filename)

dogs = 0
yellow_and_violent = 0

for line in infile:
    if line.strip() and line[0]!='#':
        dogs += 1
    if ('yellow' in line) and ('violent' in line):
       yellow_and_violent += 1
print("Total dogs =",dogs)
print("Yellow and violent dogs = ", yellow_and_violent)

rawDescription: How to count how many times two words occur in a text file in Python?

description: Count how many times two words occur in a text file in Python


code: print('%f' % n)

rawDescription: Python float to string, only "dotted notation"?


code:
class TestModel(models.Model):
    _name = 'test.model'

    name = fields.Char('Name', required=1)
    email = fields.Char('Field')
    user_id = fields.Many2one('res.users', 'Related User')

rawDescription: Automatic user creation in odoo8 when custom record created using inheritance by delegation


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

rawDescription: Improve efficiency in Python matching

description: Improve efficiency in Python matching


code:
from inspect import Parameter, signature, Signature

def get_multivar_lambda(expression, variables=["x"]):

    params = [Parameter(v, Parameter.POSITIONAL_OR_KEYWORD) for v in variables]
    sig = Signature(params)

    def to_return(*args, **kwargs):
        values = sig.bind(*args, **kwargs)
        for name, val in values.arguments.items():
            print (name, val)

    to_return.__signature__ = signature(to_return).replace(parameters=params)
    return to_return

rawDescription: Python - Exact Number of Arguments Defined by Variable


rawDescription: How to replace all values in a Pandas Dataframe not in a list?

description: Replace all values in a Pandas Dataframe not in a list


code:
from nose.plugins import Plugin
class UseMySelector(Plugin):
    enabled = True
    def configure(self, options, conf):
        pass # always on
    def prepareTestLoader(self, loader):
        loader.selector = MySelector(loader.config)

rawDescription: Is it possible to filter test files and individual tests with different patterns in python?


code: all(a.get(k, object())==v for k,v in b2.iteritems())

rawDescription: is there a built-in feature to say a dict A contains another dict B?

description: Is there a built-in feature to say a dict A contains another dict B


code: [m[i:i+len(s)] for i in range(len(m)-len(s)+1)]

rawDescription: Method to find substring

description: Method to find substring


code:
class MyModel(Model):
    class Meta:
        db_table = 'mytable' # This tells Django where the SQL table is
        managed = False # Use this if table already exists
                        # and doesn't need to be managed by Django

    field_1 = ...
    field_2 = ...

rawDescription: How to write a Pandas Dataframe to Django model

description: Write a Pandas Dataframe to Django model


code:
def with_regex(data):
    filtered = [x[9:-1] for x in re.findall('"text": "A[^"]+"', data)]
    return sorted(filtered)[:5]

rawDescription: Python beginner: how to reduce execution time of this small program?


rawDescription: python group items in tuple with no duplicates

description: Python group items in tuple with no duplicates


code:
colors = itertools.cycle(["r", "b", "g"])
for y in ys:
    plt.scatter(x, y, color=next(colors))

rawDescription: Setting different color for each series in scatter plot on matplotlib


code:
from re import findall
mystr = '''\
RT @username: Tweet text
RT @abcde: Tweet text
RT @vwxyz: Tweet text
'''
findall('@([^:]+)', mystr)

rawDescription: Everything after/before regex in Python

description: Everything after/before regex in Python


code:
x = np.random.rand(2000, 20)
x[x < 0.3] = np.nan
r = pair_correlation(x)

i, j = 200, 60 # change this
mask = ~(np.isnan(x[i]) | np.isnan(x[j]))
u = x[i, mask]
v = x[j, mask]
assert abs(correlation(u, v) - r[i, j]) < 1e-12

rawDescription: Calculate special correlation distance matrix faster


code:
import ipaddress

ipsub = {"10.10.10.0/24": "Firewall-Denver", "10.10.20.0/25": "Firewall-NewYork"}
iplist = ["10.10.10.1","10.10.10.174","10.10.20.126"]

ipfirewall = {}

for i in ipsub:
    for j in iplist:
        if ipaddress.ip_address(j) in ipaddress.ip_network(i):
            ipfirewall[j] = ipsub[i]

rawDescription: Matching IP addresses to a list of subnets and then returning the firewall


code:
def createprofile(request):

    user_ = User.objects.get(pk=1)
    profile = Profile(user=user_)
    profile.user.first_name = 'Joe'
    profile.user.last_name = 'Soe'
    profile.user.email = 'Joe@Soe.com'
    profile.user.save()
    profile.save()

rawDescription: Connect to User Model in Django

description: Connect to User Model in Django


code:
df.fillna('', inplace=True)
(df.A + '|' + df.B + '|'  + df.C).str.get_dummies()

rawDescription: create binary columns in a dataframe from condition on its value

description: Create binary columns in a dataframe from condition on its value


code:
items = [item[4] for item in main_list]
children = [child.get('value') for child in xml_data]

for item, child in itertools.product(items, children):
    if item == child:
        print(item)

rawDescription: Compare two lists in python and print the output


code:
log1 = [line.replace(',', '').split() for line in open('test1.txt', 'r')][:]
log2 = [line.replace(',', '').split() for line in open('test2.txt', 'r')][1:]
log3 = [] # need for combining.

rawDescription: Parse data from 2 log files in Python

description: Parse data from 2 log files in Python


code: [subtract_score(d) for d in lst]

rawDescription: List of dictionaries - subtract a constant from each dictionary value


rawDescription: Translate reshape from Matlab to Python

description: Translate reshape from Matlab to Python


code:
cities = [
    {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
    {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
    {'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
    {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
    {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
]

rawDescription: Django, template attribute unique

description: Django, template attribute unique


code: new_row = [item.translate(trans) for item in row]

rawDescription: Using multiple (similar) generator expressions


code:
class Solution(object):
    def summaryRanges(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        s = []
        left = 0
        right = 0
        while left < len(nums):
            if left == len(nums) - 1:
                s += [str(nums[left])]
                return s
            elif nums[right + 1] == nums[right] + 1:
                right += 1
            else:
                s += [str(nums[left]) + "->" + str(nums[right])]
                left = right + 1
                right = left

rawDescription: leetcode No 228, runtime error

description: Leetcode No 228, runtime error


code:
class Items(list):
    pass

def items_representer(dumper, data):
    return dumper.represent_sequence('tag:yaml.org,2002:seq', data, flow_style=True)

yaml.representer.SafeRepresenter.add_representer(Items, items_representer)

result = yaml.safe_dump({
    'items': Items(['test', 'test2']),
    'other list': ['1', '2'],
}, default_flow_style=False)

# items: [test, test2]
# other list:
# - '1'
# - '2'
print(result)

rawDescription: How can I print [] without string in Python in YAML file

description: Print [] without string in Python in YAML file


code:
lake
que

rawDescription: Search strings in list containing specific letters in random order


code:
np.random.seed(123)
A = np.random.randint(0, 2, size=(100, 3)).astype(np.float32)
B = np.hstack((A, 100000*np.ones((A.shape[0], 1)))).astype(np.float32)

rawDescription: numpy matrix rank incorrect result

description: Numpy matrix rank incorrect result


code:
line_end = self.OutWidget.index("%s lineend" % line_start)
self.OutWidget.tag_remove("highlight", 1.0, "end")
self.OutWidget.tag_add("highlight", line_start, line_end)

rawDescription: Highlighting a clicked line in an unfocused Tkinter text widget


rawDescription: Growing matrices columnwise in NumPy

description: Growing matrices columnwise in NumPy


code: import b

rawDescription: How do I import other scripts?

description: Import other scripts


code:
import itertools as it

items = it.izip(it.islice(entries, 1, None), entries)
for current, last in items:
    diff = current - last

rawDescription: python for loop, how to find next value(object)?

description: Python for loop, how to find next value(object)


code:
[{'id': 1, 'name': u'Oneeee', 'version': 2},
 {'id': 2, 'name': u'Two', 'version': 1},
 {'id': 3, 'name': u'Threeee', 'version': 3},
 {'id': 4, 'name': u'Four', 'version': 1},
 {'id': 5, 'name': u'Five', 'version': 1},
 {'id': 6, 'name': u'Six', 'version': 2}]

rawDescription: Merging arrays of versioned dictionaries


rawDescription: Python Pandas: Get index of rows which column matches certain value


code:
col_names = [col_name1, col_name2, ...]

data = [
    [val1_col_name1, val2_col_name2, ...]
    [val3_col_name1, val4_col_name2, ...]
    [val1_col_name1, val2_col_name2, ...]
]

rawDescription: how to convert a list into html column in python

description: Convert a list into html column in python


code:
{'roomlist': [{'AmountBeforeTax': u'262.650',
               'RatePlanCode': u'49584IPRTF',
               'RoomTypeCode': u'VW2Q',
               'RoomTypeName': u'PREMIUM VW 2 QEN'},
              {'AmountBeforeTax': u'300.900',
               'RatePlanCode': u'49584IPRTF',
               'RoomTypeCode': u'CLBD',
               'RoomTypeName': u'REG CLUB 2 DOUBLE BEDS'},
              {'AmountBeforeTax': u'449.650',
               'RatePlanCode': u'49584IPRTF',
               'RoomTypeCode': u'JRSQ',
               'RoomTypeName': u'JR SUITE 2 QUEEN BEDS'}]}

rawDescription: Fetch the required details from SOAP xml response


code: sess = Session(expire_on_commit=False)

rawDescription: LOTS of call to the expire method of the SQLAlchemy's InstanceState class


code: int('Strin', 36)

rawDescription: Why is python returning a numbers from a string?


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

rawDescription: Python webdriver from Selenium

description: Python webdriver from Selenium


code:
class FooForm(forms.ModelForm):
    class Meta:
        model = People
        widgets = {
            'name': forms.Textarea(attrs={'placeholder': u'Bla bla'}),
        }

rawDescription: Specifying widget for model form extra field (Django)


code: a, b, c, d = max(a, x), max(b, x), max(c, x), max(d, x)

rawDescription: Is there a simpler way to allocate value to a variable given a if condition - Python?


rawDescription: Python List splitting, sorting by date, then joining


code:
Maxi_date1 = str(df.index.max())
Maxi_date = Maxi_date1[0:10]

rawDescription: How to access first and last timestamp in dataframe

description: Access first and last timestamp in dataframe


code:
from collections import Counter

with open('D:/project/report.txt','r') as fob:
    c = Counter(word for line in fob for word in line.split())

rawDescription: Storing the count of each word occurring in a text file


code: np.in1d(a, b)

rawDescription: Numpy search for elements of an array in a subset


code:
#!env python

import gevent
from gevent import local

def foo():
    print("IN FOO")
    data = local.local()
    #This line of code declares data as a local variable.
    data.numbers = 42

    bar()

def bar():
    print("IN BAR")
    data = local.local()
    #This line of code declares data as an another local variable.
    print(data.numbers)

def main():
    foo_gl = gevent.Greenlet(foo)
    print("starting foo")
    foo_gl.start()
    gevent.joinall([foo_gl])

if __name__ == "__main__":
    main()

rawDescription: how to use gevent local module

description: Use gevent local module


rawDescription: How to use Pandas to create Dictionary from column entries in DataFrame or np.array

description: Use Pandas to create Dictionary from column entries in DataFrame or np.array


code:
def parse_message_to_tree(message):
    buf = StringIO(message)
    return parse_message_to_tree_helper(buf, 0, None)[0]

def parse_message_to_tree_helper(buf, prev, prevline):
    ret = {}
    index = -1
    for line in buf:
        line = line.rstrip()
        index = len(line) - len(line.lstrip())
        print (line + " => " + str(index))
        if index > prev:
            ret[prevline.strip()],prevline,index = parse_message_to_tree_helper(buf, index, line)
            if index < prev:
                return ret,prevline,index
            continue
        elif not prevline:
            ret[line.strip()] = {}
        else:
            ret[prevline.strip()] = {}
        if index < prev:
            return ret,line,index
        prevline = line
    if index == -1:
        ret[prevline.strip()] = {}
        return ret,None,index
    if prev == index:
        ret[prevline.strip()] = {}
    return ret,None,0

rawDescription: converting a string to a tree structure in python

description: Converting a string to a tree structure in python


code:
import re

def to_named_group(match):
    return '(?P<{}>.*)'.format(re.escape(match.group(0)[1:-1]))

def make_regex(key_mask):
    return re.compile(re.sub(r'\{[^}]+\}', to_named_group, key_mask))

def find_matches(key_mask, text):
    return make_regex(key_mask).match(text).groupdict()

rawDescription: python match regular expression

description: Python match regular expression


code: Hello

rawDescription: Supress output in multiprocessing process


code:
def interface(*attributes):
    def decorator(Base):

        def checker(Other):
            return all(hasattr(Other, a) for a in attributes)

        def __subclasshook__(cls, Other):
            if checker(Other):
                return True
            return NotImplemented

        def __instancecheck__(cls, Other):
            return checker(Other)

        Base.__metaclass__.__subclasshook__ = classmethod(__subclasshook__)
        Base.__metaclass__.__instancecheck__ = classmethod(__instancecheck__)
        return Base

    return decorator

rawDescription: Why can `__subclasshook__` be monkeypatched onto the metaclass but `__instancecheck__` cannot?


code:
s = pd.Series(['potatoes are "great"', 'they are'])
s
s.str.replace('"', '')

rawDescription: Remove all quotes within values in Pandas


rawDescription: split a string in python

description: Split a string in python


code:
def filter(self, *args, **kwargs):
    args, kwargs = self.__translate(*args, **kwargs)
    return super(QuerySet, self).filter(args, kwargs)

rawDescription: Django : how could I overload Q in django.db.models.query QuerySet to use for a special purpose in my Manager


rawDescription: make 1 dimensional array of strings with elements seperated by commas from 2 d array in numpy

description: Make 1 dimensional array of strings with elements seperated by commas from 2 d array in numpy


code:
class Generator(object):
    def createsituation(self, stringsituation="situation"):
        return classes[stringsituation]()

rawDescription: python create object from string

description: Python create object from string


code:
df.ix[df['AGE_R'] == 1, 'AGE_R'] = df.ix[df['AGE_R'] == 1].apply(lambda x: np.random.randint(1, 15), axis = 1)
df

rawDescription: Iterating w/ Pandas DataFrame and Changing Values


code:
a = np.random.rand(3, 3)
a
np.linalg.inv(a)
a_sps = scipy.sparse.csc_matrix(a)
lu_obj = scipy.sparse.linalg.splu(a_sps)
lu_obj.solve(np.eye(3))

rawDescription: Inverting large sparse matrices with scipy


code: calc()

rawDescription: Sum of calculation in a variable

description: Sum of calculation in a variable


code:
for key in dictionary.keys():
    print("Key: ", key)
for value in dictionary.values():
    print("Value: ", value)
for k, v in dictionary.items():
    print("Key: ", k)
    print("Value: ", v)

rawDescription: How do I print a key without value from a dictionary that has multiple keys

description: Print a key without value from a dictionary that has multiple keys


code:
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as opt

rawDescription: Getting completely wrong fit from python scipy.optimize.curve_fit


code:
df.sortlevel(axis=1).loc[:, ('foo','B')]
df.sortlevel(axis=1).loc[:, ['foo','B']]

rawDescription: pandas dataframe view vs copy, how do I tell?

description: Pandas dataframe view vs copy, how do I tell


code:
tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
('parrot', ('fresh fruit',))))))))
pp = pprint.PrettyPrinter(depth=6)
pp.pprint(tup)

rawDescription: How to easily display top level of data structure in python

description: Easily display top level of data structure in python


code: json.dump(data, fp, sort_keys=True, indent=4)

rawDescription: Storing Python dictionaries

description: Storing Python dictionaries


code:
import itertools
non_starting_words = list(itertools.chain(*[s[1:] for s in treebank.sents()]))
uppercase_words = [w for w in non_starting_words if w[0].isupper()]

rawDescription: Change from re.findall(regex, text) to nltk.Text.findall(regex)


code:
class DateDialog(QDialog):
    def __init__(self, parent = None):
        super(DateDialog, self).__init__(parent)

        layout = QVBoxLayout(self)

        # nice widget for editing the date
        self.datetime = QDateTimeEdit(self)
        self.datetime.setCalendarPopup(True)
        self.datetime.setDateTime(QDateTime.currentDateTime())
        layout.addWidget(self.datetime)

        # OK and Cancel buttons
        buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
            Qt.Horizontal, self)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons)

    # get current date and time from the dialog
    def dateTime(self):
        return self.datetime.dateTime()

    # static method to create the dialog and return (date, time, accepted)
    @staticmethod
    def getDateTime(parent = None):
        dialog = DateDialog(parent)
        result = dialog.exec_()
        date = dialog.dateTime()
        return (date.date(), date.time(), result == QDialog.Accepted)

rawDescription: How can I show a PyQt modal dialog and get data out of its controls once its closed?

description: Show a PyQt modal dialog and get data out of its controls once its closed


code:
class MyProgram(object):
    def __init__(self):
        # ... lots of initialization ...
        self.myObject = foo.bar.SomeClass(init_variable)

    def usage(self):
        self.myObject.member1

if __name__ == "__main__":
    m = MyProgram()
    m.usage()

rawDescription: Change the type of a global variable in a function initializing it


code:
def CreateText(win, text, x, y,
                         size=12, font="courier", color="black", style="normal"):

    txtObject = Text(Point(x,y), text)
    txtObject.setSize(size)
    txtObject.setFace(font)
    txtObject.setTextColor(color)
    txtObject.setStyle(style)

    return txtObject

rawDescription: "TypeError: CreateText() takes exactly 8 arguments (5 given)" with default arguments


code:
from pprint import pprint
pprint(appledata)

rawDescription: Python lengh of json is incorrect

description: Python lengh of json is incorrect


code: json.dumps(p, default=default)

rawDescription: Retrieve the object from dict to that it can easily be dumped via json.dumps()


code:
mydll = ctypes.CDLL('...')
del mydll
mydll = ctypes.CDLL('...')

rawDescription: How can I unload a DLL using ctypes in Python?

description: Unload a DLL using ctypes in Python


code: newlist = [item+add for item in oldlist for add in ['', ',', '.', '?', '!', ':']]

rawDescription: Extend every single string in a list with punctuation


code:
for related_outer in relation:
    #Create a set using the ID_Number as the key, and the other ID numbers as the values
    for related_inner in relation:
        redis_db.sadd(related_outer.number, related_inner.number)

rawDescription: How do I relate data without one single master or starting point

description: Relate data without one single master or starting point


rawDescription: Ordering items with known pair distances


rawDescription: Pandas Plots: Separate color for weekends, pretty printing times on x axis


code:
def read_words(q):
    words = None
    while True:
        with open('words.txt') as file:
            newwords = file.read().splitlines()
        if words != newwords:
           q.put(newwords)
           words = newwords
        time.sleep(1)

rawDescription: How can I change in real-time filtered words in tweetstream (Python)?

description: Change in real-time filtered words in tweetstream (Python)


code:
import datetime
import time

msdate = time.mktime(datetime.date(2012, 5, 25).timetuple()) * 1000

rawDescription: jquery flot prints dates on the x-axis

description: Jquery flot prints dates on the x-axis


code:
def simPoints(simData):
    x, y = simData[0], simData[1]
    line.set_data(x, y)
    return line,            # added a comma to return a tuple

rawDescription: Python multi-body animation does not work


rawDescription: pandas percentage change with missing data

description: Pandas percentage change with missing data


code:
Output
en

rawDescription: Python - can I detect unicode string language code?


code:
@set_defaults(my_defaults)
def DoSomething(var_of_data, user_input=Default.USER_INPUT):
    ...

rawDescription: Python 2.7: Defining default parameters based on globals?


code: value_returned = self.get_thing()

rawDescription: Using setattr() in python

description: Using setattr() in python


code:
def dates_between(start, end):
    while start <= end:
        yield start
        start += datetime.timedelta(1)

def count_weekday(start, end):
    counter = Counter()
    for date in dates_between(start, end):
        counter[date.strftime('%a')] += 1
    return counter

rawDescription: Number of times each weekday occurs between two dates


code:
if re.findall(r"{0}".format(dia), line):
    pass

rawDescription: use variable inside regex python

description: Use variable inside regex python


code:
for key, value in smaller_dict.iteritems():
    try:
        big_dict[key].update(value)
    except KeyError:
        big_dict[key] = dict(value)

rawDescription: Fastest method in merging of the two: dicts vs lists


code: my_dictionary = {k: f(v) for k, v in my_dictionary.items()}

rawDescription: Mapping over values in a python dictionary


code:
import ast
values = ast.literal_eval(values_str)
values = [json.loads(item) for item in values]

rawDescription: How to convert list of nested dictionaries into string and vice versa

description: Convert list of nested dictionaries into string and vice versa


code: dict2_inverse = {v: k for k, v in dict2.items()}

rawDescription: Remap keys of a recursive dictionary, using another dictionary


code: user2_ids = request.user.user_set.all().values_list('user2', flat=True).distinct()

rawDescription: Get list related objects

description: Get list related objects


code:
from matplotlib import tri, cm
import matplotlib.pyplot as plt

x=[0, 1, 1, 0]
y=[0, 0, 1, 1]
z=[0, 1, 2, 3]

triang=tri.Triangulation(x,y) #Delaunay triangulation of input
refiner=tri.UniformTriRefiner(triang)
interp=tri.LinearTriInterpolator(triang,z) #linear interpolator
new,new_z=refiner.refine_field(z,interp,subdiv=6) #refined mesh; uses 4**subdiv!

fig = plt.figure()
plt.tripcolor(new.x,new.y,new_z,cmap=cm.jet)

rawDescription: MATLABs fill in PyPlot

description: MATLABs fill in PyPlot


rawDescription: Python. One line for loop printer with format


code:
config = Config('my_config_file.cfg')
config.screen_size

rawDescription: Borg Design Pattern

description: Borg Design Pattern


code:
user_func(x, initial_guess_param1, param2, ...)
# Then curve-fit modifies initial_guess_param1, param2, ... and calls it again
user_func(x, initial_guess_param1, param2, ...)
# and again modifies these and calls again
user_func(x, initial_guess_param1, param2, ...)
# ... until it finds a solution

rawDescription: Python: Passing function with arguments to a function


rawDescription: rpy2 (version 2.3.10) - importing data from R package into python

description: Rpy2 (version 2.3.10) - importing data from R package into python


code:
from sqlalchemy import func
company_ids = ['2', '24', '1', '7', '373']
query = Company.query.filter(Company.id.in_(company_ids)).order_by(func.idx(company_ids, Company.id))
following_companies_list_data = query.paginate(page, per_page=10, error_out=False)

rawDescription: Keep the order of list in sql pagination


code: [[(i,j) for i in list1] for j in list2]

rawDescription: Python - Combining two lists of strings to create a matrix/table of their combinations


rawDescription: Creating a file with python using sudo makes its owner root


rawDescription: SQLAlchemy ordering by count on a many to many relationship


code:
from pyspark.sql.functions import col, when
from functools import reduce

c = col("user_agent")
vs = [("Android", "mobile"), ("Linux", "desktop")]
expr = reduce(
    lambda acc, kv: when(c.like(kv[0]), kv[1]).otherwise(acc),
    vs,
    "other_unknown"
).alias("user_agent_type")

df.select("*", expr).show()

## +---+----------+---------------+
## | id|user_agent|user_agent_type|
## +---+----------+---------------+
## |  1|   Android|         mobile|
## |  2|     Linux|        desktop|
## |  3|       Foo|  other_unknown|
## +---+----------+---------------+

rawDescription: How to perform a Switch statement with Apache Spark Dataframes (Python)

description: Perform a Switch statement with Apache Spark Dataframes (Python)


rawDescription: Can a Django Queryset be created to do this complex query?


code:
class Vector(object):
    def __init__(self, arguments):
        object.__setattr__(self, 'contents', list(arguments))

    def __iter__(self):
        return iter(self.contents)

    def __getitem__(self, key):
        return self.contents[key]

    def __setitem__(self, key, value):
        self.contents[key] = value

    def __delitem__(self, key):
        del self.contents[key]

    def __setattr__(self, key, value):
        for node in self.contents:
            setattr(node, key, value)

rawDescription: Python vectorization library?

description: Python vectorization library


rawDescription: How to increase the performance for estimating `Pi`in Python

description: Increase the performance for estimating `Pi`in Python


rawDescription: Merge two lists based on condition

description: Merge two lists based on condition


code:
class BaseHandler(tornado.web.RequestHandler):
    @property
    def db(self):
        return self.application.db

rawDescription: How do I access my database level functions inside other classes/files in Tornado?

description: Access my database level functions inside other classes/files in Tornado


rawDescription: Can someone explain the ^= operator to me?


code:
NOSE_ARGS = [
 '--with-cov',
 '--cov-report', 'html',
]

rawDescription: Disabling nose coverage report to STDOUT when HTML report is enabled?


code:
d = pandas.DataFrame(np.random.randn(12, 3), columns=["X", "Y", "Z"])
d["Group"] = np.repeat([1, 2, 3, 4], 3)
d

rawDescription: Using scipy pdist on pandas data frames (and) lists


code:
from math import sqrt
# elsewhere
sqrt(n)

rawDescription: Is the expression math.sqrt() necessary?

description: Is the expression math.sqrt() necessary


rawDescription: Why is this python if statement not equal to true?


rawDescription: IPython and __doc__

description: IPython and __doc__


code:
abortable_async_result = AbortableAsyncResult(myTaskId)
abortable_async_result.abort()

rawDescription: Abort a running task in Celery within django


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

def generate_x_y(prob_map):
    s = prob_map.shape
    x, y = np.meshgrid(np.arange(s[0]), np.arange(s[1]))
    return x.ravel(), y.ravel()

def heatmap(prob_map):
    x, y = generate_x_y(prob_map)
    plt.figure()
    plt.hexbin(x, y, C=prob_map.ravel())

probs = np.random.rand(200, 200)
heatmap(probs)
plt.show()

rawDescription: Generating Heatmaps in Python

description: Generating Heatmaps in Python


code:
form = VerbTestForm()
form.fields['answer'].widget.attrs['placeholder'] = tip.tip

rawDescription: Setting an example answer in a text input field


code:
with open("secondfile") as f:
    # note: only storing the ids, not the whole line
    valid_ids = set(ln.split(',', 1)[0] for ln in f)

rawDescription: how to make a efficient filter in python

description: Make a efficient filter in python


code: Z.data *= Y[Z.indices]

rawDescription: Multiplying elements in a sparse array with rows in matrix


code:
import re
filetext2 = '''\
john123:
1
2
coconut_rum.zip
bob234513253:
0
jackdaniels.zip
nowater.zip
3
judy88009:
dontdrink.zip
9
tommi54321:
dontdrinkalso.zip
92
'''
results = {}
for name, *data in map(str.splitlines, filetext2.split('\n\n')):
    if re.match('[A-Za-z]*\d{5}:', name):
        results[name[:-1]] = [x for x in data if x.endswith('.zip')]
results

rawDescription: Match all names with exactly 5 digits at the end


code:
aList = []
for i in range(x):
    s = input()
    param_list = s.split(' ')
    aList.append(param_list)

for param_list in aList:
    pracownik = Pracownik(param_list[0], int(param_list[1]))
    print(pracownik)
print(Pracownik.total)

rawDescription: Defining and summing object in Python

description: Defining and summing object in Python


rawDescription: Extracting strings starting with symbols and combining with others from a text using python