code:
def power_read(fhandle, identifiers):
    ALL = fhandle.read()
    fhandle.close()
    result = {}
    for i in identifiers:
        findme = ('(?P<timestamp>\d+-\d+-\d+ \d+:\d+:\d+.[\d\+]+)\W%s\W(?P<value>[\d.]+)' %i)
        res = np.empty(shape=(10000, 2), dtype=[('time','datetime64[ns]'), ('value','f4')])
        cnt = 0
        found = re.findall(findme, ALL, flags=re.S)
        for f in found:
            res[cnt] = np.array(f, dtype=[('time','datetime64[ns]'), ('value','f4')])
        result[i] = res[0:cnt,:]
    return result

rawDescription: quick parsing of csv-like file

description: Quick parsing of csv-like file


code:
class HorizontalBoxes(urwid.Columns):
    def __init__(self):
        super(HorizontalBoxes, self).__init__([], dividechars=1)

    def open_box(self, box):
        if self.contents:
            del self.contents[self.focus_position + 1:]
        self.contents.append((urwid.AttrMap(box, 'options', focus_map),
            self.options('given', 40)))
        self.focus_position = len(self.contents) - 1

    def close_box(self):
        if self.contents:
            del self.contents[self.focus_position :]
            self.focus_position = len(self.contents) - 1

rawDescription: Urwid horizontal menu - return to previous state or restart loop


rawDescription: Getting values from file if match found for lines with same id in Python


code:
def getInput():
    userInput = raw_input("Enter the name of the key file: ")

    #you can check to see if the input is valid here

    return userInput

rawDescription: Write a new function that returns value inputted in another function


code:
import argparse

parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--help', action="help")
parser.add_argument('-h', help='My argument')

args = parser.parse_args()
...

rawDescription: Overriding argparse -h behaviour part 2

description: Overriding argparse -h behaviour part 2


rawDescription: How to .write() two items, a zero and an iterator in Python?


rawDescription: Understanding numpy "void" dtype and generic arrays


code:
from flask import Flask, request, g

app = Flask(__name__)

@app.route('/')
def home():
    return g.target + '\n'

@app.before_request
def before_req():
    g.target = request.args.get('target', 'default')

if __name__ == '__main__':
    app.run()

rawDescription: python flask request hook

description: Python flask request hook


code:
levels = []
LAST_EXP = 4
N_LEVELS = 5
for E in range(0,LAST_EXP):
    levels = np.concatenate((levels[:-1],np.linspace(10**E,10**(E+1),N_LEVELS)))

rawDescription: matplotlib contour plot: proportional colorbar levels in logarithmic scale

description: Matplotlib contour plot: proportional colorbar levels in logarithmic scale


code:
def transpose(g):
    return zip(*g)

rawDescription: Creating a 2d Grid in Python

description: Creating a 2d Grid in Python


code:
import operator

bubble_up(my_heap, operator.lt)

rawDescription: how to Pass an inequality into a function as a variable, then evaluate it?


code:
num = pij.transpose().dot(X)
num

rawDescription: pandas apply lambda multiple arguments no query different dataframes

description: Pandas apply lambda multiple arguments no query different dataframes


code:
nC = m.shape[1]  # m is the 2D input array
X = m - m.mean(0)
out = np.dot(X.T, X)/nC

rawDescription: Quickly compute eigenvectors for each element of an array in python


code:
while True:
    if user_input == 'h':
        High=Guess
        Guess= ((High-Low)/2)
    elif user_input == 'l':
        Low=Guess
        Guess= ((High-Low)/2)
    elif user_input == "c":
        # We're done guessing. Awesome.
        break
    else:
        print('Sorry, I did not understand your input.')

rawDescription: Python: Unexpected conditional activation in simple bisection search game


code:
def portfolios():
  for us_bonds in [ 10, 15, 20, 25, 30 ]:
    if us_bonds > 100: break
    for us_equaties in [ 25, 30, 35, 40, 45, 50 ]:
      if us_bonds + us_equaties > 100: break
      for euro_bonds in [ 10, 15, 20 ]:
        if us_bonds + us_equaties + euro_bonds > 100: break
        for euro_equaties in [ 20, 25, 30, 35, 40, 45, 50 ]:
          if us_bonds + us_equaties + euro_bonds + euro_equaties > 100: break
          cash = 100 - (us_bonds + us_equaties + euro_bonds + euro_equaties)
          yield [us_bonds, us_equaties, euro_bonds, euro_equaties, cash]

rawDescription: Python - most efficient way to generate combinations of large sets subject to criteria?


code:
from socket import *
s = socket()

POST = 'searchQuery=N.Y.C&arrivalDate=23+Oct+2013&departureDate=......'

header = ''
header += 'POST /en_US/hi/search/findhotels/index.htm?WT.bid=Home,,,find_button HTTP/1.1\r\n'
header += 'Host: www3.hilton.com\r\n'
header += 'Connection: keep-alive\r\n'
header += 'Content-Length: ' + str(len(POST)) + '\r\n'
header += 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n'
header += 'Origin: http://www3.hilton.com\r\n'
header += 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \r\n'
header += 'Chrome/30.0.1599.101 Safari/537.36\r\n'
header += 'Content-Type: application/x-www-form-urlencoded\r\n'
header += 'Referer: http://www3.hilton.com/en/index.html\r\n'
header += 'Accept-Encoding: gzip,deflate,sdch\r\n'
header += 'Accept-Language: en-US,en;q=0.8\r\n'
header += '\r\n'

s.connect(('www3.hilton.com', 80))
s.send(header+POST)
print(s.recv(8192))

rawDescription: Filling a strange webform in python

description: Filling a strange webform in python


code:
import logging
import unittest

class MyTest(unittest.TestCase):
    def test_print(self):
        logging.info('some output')
        self.assertEqual('', '')

    def test_some_moar(self):
        logging.info('some other cool output')
        self.assertTrue(True)

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    # get the default logger
    logger = logging.getLogger()
    # add a file handler
    logger.addHandler(logging.FileHandler('stdout.txt', mode='w'))
    # set up a stream for all stderr output
    stderr_file = open('stderr.txt', 'w')
    # attach that stream to the testRunner
    unittest.main(testRunner=unittest.TextTestRunner(stream=stderr_file))

rawDescription: Python unittest print logging works on Linux but not on Windows


code:
from storages.backends.s3boto import S3BotoStorage

StaticRootS3BotoStorage = lambda: S3BotoStorage(location='static')
MediaRootS3BotoStorage  = lambda: S3BotoStorage(location='uploads')

rawDescription: Django 1.8 Cache busting + Amazon S3

description: Django 1.8 Cache busting + Amazon S3


code: max_column = heapq.nlargest(len(x)/2, x)

rawDescription: How to classify values in a columns of a pandas data frame according to their value?

description: Classify values in a columns of a pandas data frame according to their value


code:
file_input = driver.find_element_by_id("uploadBtn")
file_input.send_keys("/absolute/path/to/file")

rawDescription: Selenium + Python - After clicking on a button, how to I catch the pop up window (specifically, an upload image pop up)


code:
list(findPaths(graph, 'L0', 3))
list(findPaths(graph, 'L0', 4))
list(findPaths(graph, 'L0', 2))

rawDescription: How to get the list of edge values corresponding to all possible paths of a particular length in a graph in Python?

description: Get the list of edge values corresponding to all possible paths of a particular length in a graph in Python


code:
import sys
while True:
    char = sys.stdin.read(1)
    if not char:
        break
    if char != 'x':
        sys.stdout.write(char)
        sys.stdout.flush()

rawDescription: How do I write a unix filter in python?

description: Write a unix filter in python


code:
description_map = {"AXP":"American Express", "BIDU":"Baidu"}
sign_map = {"LONG": "", "SHORT": "-"}

stock_match = re.compile(r"\s(\S+)\s")
leverage_match = re.compile("[0-9]x|x[0-9]|X[0-9]|[0-9]X")

def f(value):

    f1 = lambda x: description_map[stock_match.findall(x)[0]] if stock_match.findall(x)[0] in description_map else ''
    f2 = lambda x: leverage_match.findall(x)[0] if len(leverage_match.findall(x)) > 0 else ''
    f3 = lambda x: '-' if 'SHORT' in x else ''

    stock = f1(value)
    leverage = f2(value)
    sign = f3(value)

    statement = "Tracks " + stock

    if stock == "":
        if sign == '-':
            return statement + "{}".format('inversely')
        else:
            return "Tracks"

    if leverage[0].replace('X','x') == 'x':
        leverage = leverage[1]+leverage[0].replace('X','x')

    if leverage != '' and sign == '-':
        statement += " {} with {}{} leverage".format('inversely', sign, leverage)
    elif leverage != '' and sign == '':
        statement += " with {} leverage".format(leverage)
    else:
        if sign == '-':
            statement += " {} ".format('Inversely')

    return statement

df["description"] = df["name"].map(lambda x:f(x))

rawDescription: Pandas: Conditionally generate descriptions from column content


rawDescription: pandas multiindex assignment from another dataframe

description: Pandas multiindex assignment from another dataframe


code:
if col in relevanCols:
    event.GetEventObject().SetToolTipString("Hai")
else:
    event.GetEventObject().SetToolTip(None)

rawDescription: How to remove a tooltip in wxpython?

description: Remove a tooltip in wxpython


code:
from operator import attrgetter
L = [Any(-3, 4), Any(-2, 1), Any(0, 2), Any(2, 1), Any(5, 6), Any(6, 3), Any(8, 2), Any(10, 1), Any(13, 5), Any(14, 3)]
x = 6
bisect_left(L, x, key=attrgetter('attr_a'))
L[bisect_left(L, x, key=attrgetter('attr_a'))].attr_b
find_by_x(L, x, key=attrgetter('attr_a')).attr_b
x = 12
find_by_x(L, x, key=attrgetter('attr_a')).attr_b

rawDescription: Searching an attribute_A in a attribute_B-sorted list


rawDescription: calculate mean sales per minute accross 24-hour cycles as per local-time (HH:MM)

description: Calculate mean sales per minute accross 24-hour cycles as per local-time (HH:MM)


code:
t = time.time()
# do stuff
elapsed = time.time() - t

rawDescription: tic, toc functions analog in Python

description: Tic, toc functions analog in Python


code:
import sys; print('%s %s' % (sys.executable or sys.platform, sys.version))
import os;os.chdir([p for p in os.environ['PYTHONPATH'].split(os.pathsep) if p.startswith("D")][0])
pwd()

rawDescription: pydev console path for the active editor

description: Pydev console path for the active editor


rawDescription: ffill not retaining all columns

description: Ffill not retaining all columns


code:
from subprocess import Popen, PIPE

with Popen(["scala"], stdout=PIPE, stdin=PIPE, bufsize=0, universal_newlines=True) as scala:
    for line in scala.stdout:
        print(line)
        if not line.strip():
            break
    while True:
        command = input("Enter scala command >>> \n")
        scala.stdin.write(command+"\n")
        scala.stdin.flush()
        for line in scala.stdout:
            if not line.strip():
                break
            print(line)

rawDescription: input command doesn't seem to work when used with popen python

description: Input command doesn't seem to work when used with popen python


code:
df['Diff'] = abs_diff(df['S1'], df['S2'])
df

rawDescription: Column Differences in Python Pivot-Table


code:
a = {'sd':{},'sdd':'','sadfas':None,'sadfa':'dsf'}
a = dict((k, v) for k, v in a.iteritems() if v != '' and v != {} and v is not None)
a

rawDescription: Removing values from dict in python

description: Removing values from dict in python


code:
from fabric.api import env, run
from fabric.tasks import execute

def serv_foo():
    return ['bla@example.com']

def serv_bar():
    return ['bla@example2.com']

def get_all_servers():
    return {(k, v) for k, v in globals().items() if k.startswith("serv_")}

def get_hostname():
    return run("hostname")

def get_hostnames():
    for serv_name, serv_fptr in get_all_servers():
        print(env.hosts)
        hostname = execute(get_hostname, hosts=serv_fptr())
        print(hostname)

rawDescription: Update hosts within fabric script

description: Update hosts within fabric script


code:
class UserIdRetrieve(RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_object(self):
        queryset = self.filter_queryset(self.get_queryset())

        if 'username' in self.request.query_params:
            filter_kwargs = {'username': self.request.query_params['username']}
        elif 'user_id' in self.request.query_params:
             filter_kwargs = {'id': self.request.query_params['user_id']}
        else:
            raise Http404('Missing required parameters')

        obj = get_object_or_404(queryset, **filter_kwargs)

        # May raise a permission denied
        self.check_object_permissions(self.request, obj)

        return obj

rawDescription: Django Rest required parameters in URL

description: Django Rest required parameters in URL


rawDescription: Python: How to produce only in sequence combinations from a list of string parts, with use being optional


code:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import AxesGrid

# Sample data. You can get yours with np.genfromtxt('/path/to/performance.dat')
data1 = np.random.rand(20,20)*2
data2 = np.random.rand(20,20)*2
data3 = np.random.rand(20,20)*2

fig = plt.figure(figsize=(9,3))

fig.subplots_adjust(bottom=0.2)
plt.viridis()

grid = AxesGrid(fig, 111,
                nrows_ncols=(1, 3),
                axes_pad=0.2,
                share_all=True,
                label_mode="L",
                cbar_location="right",
                cbar_mode="single",
                )

for ax,data in zip(grid,[data1,data2,data3]):
    p=ax.pcolor(data,vmin=0,vmax=2)
    ax.set_xlabel(r"$\log \, \sigma_1$", size=28)

grid[0].set_ylabel(r"$\log \, \sigma_2$", size=28)

grid.cbar_axes[0].colorbar(p)

plt.show()

rawDescription: Creating a heatmap without a colorbar in matplotlib


code:
with open('fileName', 'w') as f:
    f.write(yourString)

rawDescription: Writing a text file using python

description: Writing a text file using python


code:
inFile = open("file.txt","r")
outFile = open("file.out","w")

def convert(text):
    #Change text here.
    return text

for line in inFile:
    outFile.write(convert(line))

rawDescription: Generate html from plain text with formatting markers in Python 3


code:
n_features = X_train.shape[1]
n_desired_features = n_features / 5
buckets = np.random.random_integers(0, n_desired_features-1, size=n_features)
X_new = np.zeros((X_train.shape[0], n_desired_features), dtype=X_train.dtype)
for i in range(n_features):
    X_new[:,buckets[i]] += X_train[:,i]

rawDescription: scikit-learn HashingVectorizer on sparse matrix

description: Scikit-learn HashingVectorizer on sparse matrix


code:
jit.conditional_call(d.resize_counter <= x * 3,
                     _ll_dict_resize_to, d, num_extra)

rawDescription: How do CPython and PyPy decide when to resize a set?


code:
import datetime
class Fecha(datetime.date):
    def __new__(cls, year, month, day, status):
        instance = super(Fecha, cls).__new__(cls, year, month, day)
        instance.status = status
        return instance

dia = Fecha(2014, 7, 14, 'laborable')
dia.status

rawDescription: Extending a class in Python 3 and construct it with __init__


code:
import time
import pytz
import os
from datetime import datetime

myfile = SOMEWHERE

myfile_ctime = os.path.getctime(myfile)

ny = pytz.timezone("America/New_York")
d = datetime.fromtimestamp(myfile_ctime, tz=ny)
mytz = pytz.timezone(MY_TZ_WHATEVER)
myd = d.astimezone(mytz)
final_date = myd.strftime('%Y-%m-%d %H:%M:%S')

rawDescription: Does django mess up with python's datetime?


code: [l==r for l,r in zip('happy','harpy')]

rawDescription: Python- Replace all occurrences of letter at specific position on a string


code:
class SillyWalk(object):
    def is_silly_enough(walk):
        return (False, "It's never silly enough")

    def walk(self, appraisal_function=is_silly_enough):
        self.do_stuff()
        (was_good_enough, reason) = appraisal_function(self)
        if not was_good_enough:
            self.execute_self_modifying_code(reason)
        return appraisal_function
    def do_stuff(self):
        pass
    def execute_self_modifying_code(self, problem):
        deepjuju.kiss_booboo_better(self, problem)

rawDescription: Using class/static methods as default parameter values within methods of the same class


code:
g
g.index = g.index.swaplevel(1, 2)

rawDescription: Multi-Index Sorting in Pandas

description: Multi-Index Sorting in Pandas


code:
from collections import namedtuple

field_names = data[0].replace(" ", "_").lower().split(",")
field_names += ['placeholder_1', 'placeholder_2']
Entry = namedtuple('Entry', field_names)

list_of_named_tuples = []
mock_data = [None, None]
for row in data[1:]:
    row_data = row.split(",") + mock_data
    list_of_named_tuples.append(Entry(*row_data))

rawDescription: Storing data into namedtuples with empty fields to add other stuff


code:
import re

contents = re.sub(r',\s*(?=])', '', contents)

rawDescription: Format of a .json file to be loaded in python


code:
def _auto_reconnect_wrapper(func):
    ''' Tries to reconnects dead connection
    '''

    def inner(self, *args, _retry=True, **kwargs):
        gen = func(self, *args, **kwargs)
        try:
            value = next(gen)
            return itertools.chain([value], gen)
        except StopIteration:
            return gen
        except Mysql.My.OperationalError as e:
            ...
            # Retry
            return inner(self, *args, _retry=False, **kwargs)
    return inner

rawDescription: Generator recovery using decorator

description: Generator recovery using decorator


code:
import bottle
from web.bottleApp import app
from configure.config import configure_app

main = bottle.Bottle()
main.mount("/config/",configure)
main.mount("/",app)

main.run(host = 'localhost', port=8080)

rawDescription: Inserting a folder containing specific routes to a bottle application in Python


code:
num = 5
coll = plt.scatter(rand(num), rand(num), c='k')
# coll = plt.scatter(rand(num), rand(num), c=['b', 'g', 'r', 'y', 'k'])
fig = plt.gcf()
fig.show()

colors = coll.get_facecolor()
if colors.shape[0] == 1:
    newcolors = np.tile(colors, (num, 1))
else:
    newcolors = colors
newcolors[0] = [0, 0.75, 0.75, 1]
coll.set_color(newcolors)

rawDescription: resetting points of an already plotted scatter in matplotlib

description: Resetting points of an already plotted scatter in matplotlib


rawDescription: Recalling/remembering variables after they have been returned within a function in Python


code:
import sys

if __name__ == '__main__':
    filename = sys.argv[1]
    f = open(filename)

rawDescription: Open text files with different names-Python


code:
from collections import namedtuple

Particle = namedtuple('Particle', 'x, y, vx, vy')
c = [Particle._make(group) for group in zip(x, y, vx, vy)]
print(c)

rawDescription: Create python array from first element of array 1, first element of array 2, second element of array 1, second element of array 2, etc


code:
import numpy as np
mask_value = -9999
a = np.array([1, 2, mask_value, 4])
b = np.array([1, mask_value, 3, 4])
c = np.vstack((a,b))

masked_a, masked_b, masked_c = [np.ma.array(x, mask=x==mask_value) for x in (a,b,c)]  # note: testing for equality is a bad idea if you're working with floats. I'm not, these are integers, so it's okay.

result = np.ma.cov(masked_c)
result
np.cov([1,2,4]) # autocovariance when just one element is masked is the same as the previous result[0,0]

rawDescription: Covariance Matrix Python - Omit -9999 Value


code: match = re.match(regex, string)

rawDescription: How do I use regular expressions in Python with placeholder text?

description: Use regular expressions in Python with placeholder text


rawDescription: Assign multiple values of a list

description: Assign multiple values of a list


code:
#!/usr/bin/python

import sys
total = int(sys.argv[1]) +  int(sys.argv[2])
print('Argument List: %s' % str(sys.argv))
print('Total : %d' % total)

rawDescription: Passing variables at runtime

description: Passing variables at runtime


rawDescription: Why does Sympy cut off polynomial terms with small coefficients?


code: sorted([(y, x, index) for (index, (x, y)) in enumerate(zip(array1, array2)) if x < 0])

rawDescription: Python: finding index of an array under several conditions


rawDescription: How can i change the position of substring within a string in Python?

description: Change the position of substring within a string in Python


code: y9 = lambda x: y(x) - 9

rawDescription: Solve for the argument to a function that will produce a particular return value


rawDescription: How to put the wx.grid into a GridBagSizer, with scroll bar

description: Put the wx.grid into a GridBagSizer, with scroll bar


rawDescription: Can someone explain to me what python is doing here?


code:
abundances = {}
with open('abundance', 'r') as f:
    for line in f:
        contig, rest = line.strip().split(maxsplit=1)
        abundances[contig] = rest

with open('contig_numbers', 'r') as f:
   contig_numbers = set(line.strip() for line in f)

annotations = open('annotation', 'r')
for annotation in annotations:
    key = annotation.split(maxsplit=1)[0]
    if key in contig_numbers:
        if key in abundances:
            print (annotation.strip() + "\t" + abundances[key])
        else:
            print(annotation.strip())

rawDescription: Search for a word in two files and print the the two lines with tabular separation


rawDescription: Launch a webpage on a Firefox (win) tab using Python


code:
from pprint import pprint
listA = [["SomeString1", "A", "1"],
         ["SomeString2", "A", "2"],
         ["SomeString3", "B", "1"],
         ["SomeString4", "B", "2"]]
listB = [["OtherString1", "A", "1"],
         ["OtherString2", "A", "2"],
         ["OtherString3", "B", "1"],
         ["OtherString4", "B", "2"]]
listBstrings = {tuple(lst[1:]): lst[0] for lst in listB}
joined = [[lst[0], listBstrings[lst[1], lst[2]]] + lst[1:] for lst in listA]
pprint(joined)

rawDescription: Python join two nested lists

description: Python join two nested lists


code: fixed_names = zip(*names_matrix[1:])

rawDescription: Python For In Loop Matrix for User Input


code: 'Hello world with an em-dash: \u2014\n'.encode('utf8')

rawDescription: String to unicode code point escpe sequences in Python


code:
def view(request):
    ...
    if request.method == 'POST' and form.validate():
        form.populate_obj(student_courses)

rawDescription: How to populate lists of objects with WTForms?

description: Populate lists of objects with WTForms


code:
import pandas as pd
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

np.random.seed(0)
gaussian1 = -6 + 3 * np.random.randn(1700)
gaussian2 = 4 + 1.5 * np.random.randn(300)
gaussian_mixture = np.hstack([gaussian1, gaussian2])

df = pd.DataFrame(gaussian_mixture, columns=['data'])

# non-parametric pdf
nparam_density = stats.kde.gaussian_kde(df.values.ravel())
x = np.linspace(-20, 10, 200)
nparam_density = nparam_density(x)

# parametric fit: assume normal distribution
loc_param, scale_param = stats.norm.fit(df)
param_density = stats.norm.pdf(x, loc=loc_param, scale=scale_param)

fig, ax = plt.subplots(figsize=(10, 6))
ax.hist(df.values, bins=30, normed=True)
ax.plot(x, nparam_density, 'r-', label='non-parametric density (smoothed by Gaussian kernel)')
ax.plot(x, param_density, 'k--', label='parametric density')
ax.set_ylim([0, 0.15])
ax.legend(loc='best')

rawDescription: How to estimate density function and calculate its peaks?

description: Estimate density function and calculate its peaks


code: Table.query.filter("name ~ 'foo'")

rawDescription: SQLAlchemy + PostgreSQL + PG regex

description: SQLAlchemy + PostgreSQL + PG regex


code:
l = [{'name':'Bernard','age':7},{'name':'George','age':4},{'name':'Reginald','age':6}]
d = dict((i['name'], i['age']) for i in l)

rawDescription: Python check if value is in a list of dicts


code:
def do_question(qtypes=[Multiplication, Division, Addition, Subtraction]):
    # pick a random question-type
    #   and create a question of that type
    q = choice(qtypes)()
    # prompt user for their answer
    guess = get_int(q.question())
    # mark their answer
    if guess == q.answer():
        print("Correct!")
        return True
    else:
        print("Sorry, the right answer was {}".format(q.answer()))
        return False

rawDescription: Finding something that checks if a particular Arithmetic answer is correct


code: dummies[['cc_US', 'cc_UK']]

rawDescription: How to generate dummy variables for only specific values in a column?

description: Generate dummy variables for only specific values in a column


code:
entry = po.find('Email address')
if entry:
    entry.msgstr = 'E-Mail-Adresse'
    if 'fuzzy' in entry.flags:
        entry.flags.remove('fuzzy')

rawDescription: Modify/update an entry in a po file with polib in Python


code:
MYSQL_OPTION_MULTI_STATEMENTS_ON = 0
MYSQL_OPTION_MULTI_STATEMENTS_OFF = 1

conn.set_server_option(MYSQL_OPTION_MULTI_STATEMENTS_ON)
# Multiple statement execution here...
conn.set_server_option(MYSQL_OPTION_MULTI_STATEMENTS_OFF)

rawDescription: Execute .sql file in Python with MySQLdb


rawDescription: How to call a self-defined command line function in Python

description: Call a self-defined command line function in Python


code:
def getAnagrams(user):
    lister = [word for word in words if len(word) <= len(user) ]
    for item in lister:
        if isAnAnagram(item, user):
            yield item

rawDescription: Python strings with anagrams

description: Python strings with anagrams


code:
color = df.Group.map({dut_groups[0]: "r", dut_groups[1]: "b"})
plt.scatter(x, y, color=color)

rawDescription: Is there a way to make matplotlib scatter plot marker or color according to a discrete variable in a different column?


rawDescription: Viewing the content of a Spark Dataframe Column


code:
import numpy as np
import pandas as pd
df = pd.read_table('data', sep=r'\s*[|]\s*')
df = df.set_index(['IDX1', 'IDX2', 'IDX3'])
columns = [col for col in df.columns if col[0] not in set(list('XYZ'))]
df.columns = pd.MultiIndex.from_product([columns, list('WXYZ')])
df.columns.names = ['IDX4', 'ValueType']
series = df.stack(['IDX4', 'ValueType'], dropna=False)
print(series.head())

rawDescription: How can I use melt() to reshape a pandas DataFrame to a list, creating an index from a crosstab column and creating a new variable in its place?

description: Use melt() to reshape a pandas DataFrame to a list, creating an index from a crosstab column and creating a new variable in its place


code:
context = zmq.Context()
pub = context.socket(zmq.PUB)
pub.bind(publisher_addr)
# send message to worker-1
pub.send_multipart(['worker-1', 'hello'])

rawDescription: 0mq one-to-many connection

description: 0mq one-to-many connection


code:
table = df[['Qu1', 'Qu2', 'Qu3']].apply(lambda x: x.value_counts())
table
table = table.fillna(0)
table

rawDescription: How to convert pandas dataframe so that index is the unique set of values and data is the count of each value?

description: Convert pandas dataframe so that index is the unique set of values and data is the count of each value


rawDescription: Very basic Q regarding for Loops in Python


code:
from itertools import chain, combinations

def weight(A):
    return sum(weights[x] for x in A)

# Copied from example at http://docs.python.org/library/itertools.html
def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in xrange(len(s) + 1))

[x for x in powerset({'A', 'B', 'C', 'D', 'E'}) if weight(x) == W]

rawDescription: Combinations of weighted elements in a set where weighted sum equal to fixed integer (in python)


code:
from django.db.models import Q

ob_list = data.objects.filter(reduce(lambda x, y: x | y, [Q(name__contains=word) for word in list]))

rawDescription: How to Query model where name contains any word in python list?


rawDescription: Python: How to get a value of sub key in Hash Table?


code:
@DragDropWidget
class DnDFrame(tk.Frame):
    pass

main = tk.Tk()
notesFrame = DnDFrame(main, bd = 4, bg = "grey")
notesFrame.place(x=10,y=10)
notes = tk.Text(notesFrame)
notes.pack()

rawDescription: Drag and Drop widgets tkinter

description: Drag and Drop widgets tkinter


code:
plain_list = []               # Make a list plain_list
for i in arguments:           # For each i in arguments (which is an iterable)
    for j in i:               # For each j in i (which is also an iterable)
        plain_list.append(j)  # Add j to the end of plain_list

rawDescription: list iteration with 'i for j in' that I never saw

description: List iteration with 'i for j in' that I never saw


rawDescription: Parse hours without leading zeroes by strptime in Python


code: row = coo_matrix(vector)

rawDescription: Adding a sparse vector to a sparse array in python is too slow


rawDescription: Python list looping to output averages - too many records returned


code:
well_ids = list(raw_data["wells"])
ObjList.append(Well.objects.in_bulk(well_ids))

rawDescription: Django using list of primary keys to fetch records


code: oneParserToRuleThemAll = header1 + parser1 | header2 + parser2

rawDescription: choose parser based on previous results

description: Choose parser based on previous results


code:
from contextlib import contextmanager
from functools import wraps

_within_special_context = False

@contextmanager
def flag():
    global _within_special_context
    _within_special_context = True
    try:
        yield
    finally:
        _within_special_context = False

#I'd argue this would be best replaced by just checking the variable, but
#included for completeness.
def within_special_wrapper():
    return _within_special_context

def my_special_wrapper(f):
    @wraps(f)
    def internal(*args, **kwargs):
        if not _within_special_context:
            with flag():
                ...
                f(*args, **kwargs)
        else:
            raise Exception("No nested calls!")
    return internal

@my_special_wrapper
def foo():
    print(within_special_wrapper())
    bar()
    print('Success!')

@my_special_wrapper
def bar():
    pass

foo()

rawDescription: Preventing function (or decorator) from being nested


code:
import time

# suppose you have fig1, fi2, fig 3 etc.

while(True):

   time.sleep(10)
   plt.close(fig1)

   # import the next plot
   time.sleep(10)
   plt.close(fig2)

   # import the next plot

   time.sleep(10)
   plt.close(fig3)

rawDescription: Cycling plots using matplotlib

description: Cycling plots using matplotlib


rawDescription: Star operator (*) applied to lists and integers


code:
frameGroup = []

for i in range(2):

    frameGroup.append([None, None, None])
    frameGroup[i][0] = Frame(root)
    frameGroup[i][1] = Frame(frameGroup[i][0])
    frameGroup[i][2] = Frame(frameGroup[i][0])

    #add some widgets to the frames

    frameGroup[i][0].grid(row=i, column=0)
    frameGroup[i][1].grid(row=0, column=0)
    frameGroup[i][2].grid(row=1, column=0)

rawDescription: Frame list with Tkinter and python

description: Frame list with Tkinter and python


code:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import Clock
import time
from kivy.uix.label import Label
from kivy.lang import Builder

Builder.load_string('''
<MyApp>:
    MyScreen:
<MyScreen>: #
    timeb:time_box
    BoxLayout:
        orientation: "horizontal"
        pos_hint: {'top':1}
        height: "40dp"
        size_hint_y: None
        Label:
            id:time_box
            text:root.update()
            size_hint_x: 6
            font_size:30
''')
class MyScreen(Screen):
   def update(self, *args):
        self.timeb.text = time.asctime()
        return time.asctime()
class MyApp(App):
   def build(self):
        x=MyScreen()
        root = ScreenManager()
        Clock.schedule_interval(x.update, 1)
        root.add_widget(MyScreen(name='Screen1'))
        s=[x,root]
        for i in s:
            return i
if __name__ == '__main__':
    MyApp().run()

rawDescription: Not displaying Time in label in kivy

description: Not displaying Time in label in kivy


rawDescription: What is the pythonic way to sort a list with multiple attributes, such that the first is sorted reversely but the second is not?


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

class PolygonHandler:
    # Constructor
    def __init__(self):
        self.X = []
        self.Y = []
        self.numberPoints = 0
        self.fig , ax = plt.subplots()
        self.sc = ax.scatter(self.X,self.Y)
        ax.set_xlim(0,3)
        ax.set_ylim(0,3)

    # Print the polygon
    def update(self,_):
        for i in range(self.numberPoints):
            self.X[i] += np.random.normal()*0.01
            self.Y[i] += np.random.normal()*0.01
        self.sc.set_offsets(np.column_stack((self.X,self.Y)))
        return self.sc,

    # append a point
    def add(self,x,y):
        self.numberPoints += 1
        self.X.append(x)
        self.Y.append(y)

rawDescription: Real time dynamic plotting

description: Real time dynamic plotting


code:
text_0 = links[0].findNextSibling(text=True)
pprint(text_0)

rawDescription: How would I get the text AFTER a link in Python with BeautifulSoup?


code:
from collections import defaultdict
color_dict = defaultdict(int)

rawDescription: Python: reading line from file with different types of variables


rawDescription: How can I print many significant figures in Python?

description: Print many significant figures in Python


code:
import pandas as pd
import numpy as np

df = pd.DataFrame({'a':[1,3,5], 'b':[2,5,5], 'data':np.random.randn(3)})

### Create all possible combinations of a,b
newindex = [(b,a) for b in range(1,df.b.max()+1) for a in range(1,df.a.max()+1)]

### Set the index as a,b and reindex
df.set_index(['a','b']).reindex(newindex)

rawDescription: converting sparse dataframe to dense dataframe

description: Converting sparse dataframe to dense dataframe


code:
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Addres(models.Model):
    content_type = models.ForeignKey(ContentType, related_name='addresses')
    object_id = models.IntegerField()
    content_object = generic.GenericForeignKey( )

    address = models.CharField()
    city = models.ForeignKey(City)

class Client(models.Model):
    addresses = generic.GenericRelation( Addres )
    email = models.EmailField()
    name = models.CharField()

rawDescription: Django creating relation one-to-many

description: Django creating relation one-to-many


rawDescription: Python 3 List: How do I sort [('NJ', 81), ('CA', 81), ('DC', 52)] base on number and then letters?


code:
class ProfileMetaByClass(type):
    def __init__(cls, name, bases, dct):
        for method_name, method in dct.items():
            if method_name.startswith('decorate_this_'):
                setattr(cls, key, my_decorator(value))
        type.__init__(cls, name, bases, dct)

rawDescription: How to decorate a parent class and make child classes use it? python

description: Decorate a parent class and make child classes use it? python


code:
import matplotlib.pyplot as plt
fig = plt.figure()

rawDescription: What is an idiomatic way to specify a matplotlib figure and axes to a function?


code:
cond = (df['C2'] < 8) | (df['C2'] > 9)
df['F2'] = df[cond].groupby('Key')['C1'].transform(np.sum)
df

rawDescription: Pandas: conditional group-specific computations


code:
from datetime import datetime
import pytz
from tzlocal import get_localzone # $ pip install tzlocal

utc_dt = datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=pytz.utc)
print(utc_dt.astimezone(get_localzone())) # print local time
# -> 2009-07-10 14:44:59.193982-04:00

rawDescription: How do I print a Python datetime in the local timezone?

description: Print a Python datetime in the local timezone


code:
def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

rawDescription: Way to iterate two items at a time in a list?


code: {a.strip(): b.strip() for a, b in vars}

rawDescription: Parse a config-file with Python having more then one variable with the same name


code:
import textwrap

KEYWORD_LIST  = ['STUFF:', 'THINGS:', 'JUNK:']
KEYWORD_LIST1 = ['CRAP:']

def text_to_message(text):
    result=[]
    for word in text.split():
        if word in KEYWORD_LIST or word in KEYWORD_LIST1:
            if result:
                yield ' '.join(result)
                result=[]
            yield word
        else:
            result.append(word)
    if result:
        yield ' '.join(result)

def format_messages(messages):
    title='TEXT1'
    num=1
    for message in messages:
        if message in KEYWORD_LIST:
            title='TEXT1'
        elif message in KEYWORD_LIST1:
            title='NEWTEXT'
        for line in textwrap.wrap(message,width=65):
            yield 'DATA|{n}|{t}|{l}'.format(n=num,t=title,l=line)
            num+=1

TEXT='''STUFF: some random text THINGS: some random text and some more random text and stuff JUNK: crazy randomness CRAP: such random stuff I cant believe how random'''

for line in format_messages(text_to_message(TEXT)):
    print(line)

rawDescription: Grab a keyword and the text between keywords in Python


code: filter(lambda s: sorted(sum(s,[])) == sorted(lis1), powerset(lis2))

rawDescription: return combinations having all element present

description: Return combinations having all element present


code:
mydict = [{"red":6}, {"blue":5}, {"red":12}]
sum(d.get('red', 0) for d in mydict)

rawDescription: How to sum values of the same key in a dictionary?

description: Sum values of the same key in a dictionary


code:
class soapProdAPI(models.Model):
    soap_id = models.PositiveIntegerField(unique=True, null=False)
    soap_host = models.CharField(max_length=20)
    soap_ip = models.GenericIPAddressField(default='0.0.0.0')
    soap_asset = models.CharField(max_length=20)
    soap_state = models.CharField(max_length=20)

rawDescription: Skipping a field on save (Django models, Insert and Update)


code:
def hotel_change(self, cr, uid, ids, hotel, context = None):
   other_field_value = get_other_field_value(hotel)
   return {'value': {'other_field': other_field_value,},}

rawDescription: Can I populate a field on an onChange event?

description: Populate a field on an onChange event


rawDescription: Can anyone explain why this sorting won't work?


code:
from scipy import interpolate
# same as above ...
yfill_spline = interpolate.spline(xdata, ydata, xfill) #note the different args ordering from np.interp
plt.fill_between(xfill, 0, yfill_spline, color='g')

rawDescription: Matplotlib fill_between() workaround

description: Matplotlib fill_between() workaround


code:
class MasterSerializer(serializers.ModelSerializer):
    skills_ids = serializers.PrimaryKeyRelatedField(many=True, read_only=False, queryset=Skill.objects.all(), source='skills')

rawDescription: Django Rest update many to many by id

description: Django Rest update many to many by id


code:
for k in features:
    results[k] = dict()
    for m in classifiers:
        print(len(features[k]))
        classifier = Classifier(*classifiers[m])
        results[k][m] = classifier.fit(features[k], 'species', iris)

rawDescription: What's wrong here? accidentally referencing an existing instance instead of making a new one


code:
def process_record(record):
    mw = record[1]
    if mw <= 100:
        output = (record[1], "valueA", record[4], "moreItems")
    elif 100 < mw <= 300:
        output = (record[1], "valueB", record[4], "moreItems")
    elif 300 < mw <= 600:
        output = (record[1], "valueC", record[4], "moreItems")
    elif 600 < mw:
        output = (record[1], "valueD", record[4], "moreItems")
    else:
        raise ValueError("Illegal record: %s" % repr(record))
    return output

rawDescription: Combine multiple variable results into a single list in Python


code: content2[:] = [float(x) if x else None for x in content2]

rawDescription: python changing integers/ floats to None in list

description: Python changing integers/ floats to None in list


code: document.getElementById("test").mydata = "Whats up";

rawDescription: Pass values from backend to frontend in polymer


rawDescription: Python list of dicts: how to manipulate dynamically?


code:
class User(object):
    def __init__(self, name, bd, phone, address):
        self.name = name
        self.bd = bd
        self.phone = phone
        self.address = address

    def to_document(self):
        return dict(
            name = self.name,
            bd = self.bd,
            phone = self.phone,
            address = self.address,
        )

    @classmethod
    def from_document(cls, doc):
        return cls(
            name = doc['name'],
            bd = doc['bd'],
            phone = doc['phone'],
            address = doc['address'],
        )

rawDescription: python convert object into json for mongodb

description: Python convert object into json for mongodb


code:
import win32api

# set these to whatever you want
xMin = 300
xMax = 800

running = True
while running:
        x, y = win32api.GetCursorPos()
        if x < xMin:
                win32api.SetCursorPos((xMin,y))
        elif x > xMax:
                win32api.SetCursorPos((xMax,y))

rawDescription: How to confine mouse to a specific monitor on a multi-monitor system?

description: Confine mouse to a specific monitor on a multi-monitor system


code:
import os
import random
import time

def print_grid(li):
    grid = [word_list[i:i+3] for i in range(0, len(word_list), 3)]
    for l in grid:
        print(''.join('{:23}'.format(i) for i in l))

if __name__ == "__main__":
    # get words
    with open('/usr/share/dict/words') as f:
        words = f.read().splitlines()

    # get nine random words, the word to replace, and a new word to replace it
    word_list = [random.choice(words) for _ in range(9)]
    replace_word = random.choice(word_list)
    new_word = random.choice(words)

    # print words in a grid, wait 5 seconds, and clear the screen
    print_grid(word_list)
    time.sleep(5)
    os.system('clear')

    # replace word, and print modified list in a grid
    word_list[word_list.index(replace_word)] = new_word
    print_grid(word_list)

    # prompt user to guess
    guess = input("Which word has been replaced? ")

    # compare the guess to the replaced word
    if guess == replace_word:
        print("That's right!")
    else:
        print("Incorrect, {} had been replaced.".format(replace_word))

rawDescription: Store and Replace the Word from a List (Python)


code:
class MyCreditNoteAuth(TokenAuthBase):
   def check_auth(self, token, allowed_roles, resource, method):
        account = app.data.driver.db['users'].find_one({'api_access_token': token})

rawDescription: User dependend resource filter in Python-eve RestApi Framework


code: dict(i=i, j=j, **function(i, j))

rawDescription: How can I improve this Pandas DataFrame construction?

description: Improve this Pandas DataFrame construction


code:
import numpy as np

first = np.array([1,2,3])
second = np.array([0.2, 0.5, 0.97])
third = np.array([0.3, 0.45, .98])

sqdist = (second-0.5)**2 + (third-0.5)**2
idx = np.argsort(sqdist)
first = first[idx]
print(first)

rawDescription: Sort array in Python (numpy) by two other lists


code: Foo.immutable_attr = True

rawDescription: Mutating objects referenced by class attributes through instance methods


code:
df['window_end'] = df.time + pd.Timedelta('1H')

def get_windows(data):
    window_end = data.iloc[0].window_end
    for index, row in data.iloc[1:].iterrows():
        if window_end > row.time:
            df.loc[index, 'window_end'] = window_end
        else:
            window_end = row.window_end

df.groupby('item').apply(lambda x: get_windows(x))

rawDescription: How to group rows within a time period using Python

description: Group rows within a time period using Python


code:
{
    "keys": ["up"],
    "command": "up_arrow_in_auto_complete",
    "context": [{
        "key": "auto_complete_visible",
        "operator": "equal",
        "operand": true
    }]
}, {
    "keys": ["down"],
    "command": "auto_complete",
    "context": [{
        "key": "auto_complete_visible"
    }]
}

rawDescription: Sublime Text autocomplete window closes when scrolling off the list


code: [i.value for i in d]

rawDescription: Access float value from astropy Distance object


code:
f = Foo()
f.do_quit()
f.do_exit()
f.do_go_bye_bye()

rawDescription: elegant way of setting multiple methods to equal another method

description: Elegant way of setting multiple methods to equal another method


rawDescription: Using list as a data type in a column (SQLAlchemy)


code:
import requests
import json
import re
response = requests.get('http://static.eska.pl/m/playlist/channel-999.jsonp')
json_data = re.match('jsonp\((.*?)\);', response.content).group(1)
songs = json.loads(json_data)
current_song = songs[0]
[artist['name'] for artist in current_song['artists']]
current_song['name']

rawDescription: xpath does not work with this site, pls verify

description: Xpath does not work with this site, pls verify


code:
class Sttlmnt_typ_Master(models.Model):
    stt_typ_code = models.CharField(max_length=10, primary_key=True)
    stt_typ_name =  models.CharField(max_length=35)

    def __unicode__(self):
        return self.stt_typ_name

class DLVR(models.Model):
      sett_type = models.ForeignKey(Sttlmnt_typ_Master)
      sett_num = models.CharField(max_length=7)

rawDescription: How can implement foreign key in admin and model


code:
import tempfile
from sys import argv

run, filename = argv

with open(filename) as fin, tempfile.NamedTemporaryFile(delete=False) as fout:
    for line in fin:
        fout.write(line[1:])
    os.rename(fout.name, filename)

rawDescription: remove first char from each line in a text file

description: Remove first char from each line in a text file


code:
import win32gui
win32gui.SetWindowPos(hWnd, win32con.HWND_TOPMOST, 0,0,0,0,
win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)

rawDescription: How to keep a python window on top of all others (python 3.1)

description: Keep a python window on top of all others (python 3.1)


rawDescription: Testing all Letters?

description: Testing all Letters


code:
def foo():
    print('foo')
foo = onEvent(eventSpecificArgument)(foo)

rawDescription: Is this possible with decorators?

description: Is this possible with decorators


rawDescription: date extraction through regex

description: Date extraction through regex


rawDescription: python string split based on "\"

description: Python string split based on "\"


code:
data = [1, 2, 5, 10, -1]
[x for x in data if x < 3]

rawDescription: Python lambda with if but without else

description: Python lambda with if but without else


code:
valid_forms = filter(lambda fm: fm.is_val(),
                     map(ArticleForm, some_list_of_dictionaries))

rawDescription: Django: validating forms declared on client side with angularjs


code:
from timeit import timeit
timeit("'hij_1_1'.split('_')")
timeit("'hij_1_1'.partition('_')")

rawDescription: How to group similar items in a list?

description: Group similar items in a list


code: nd_a = np.array([[x for x in y] for y in a])

rawDescription: How to generate 2d numpy array?

description: Generate 2d numpy array


code:
some_dict = {"firstname":"Albert","nickname":"Albert","surname":"Likins","username":"Angel"}
rev_multidict = {}
for key, value in some_dict.items():
    rev_multidict.setdefault(value, set()).add(key)

rawDescription: Find dictionary keys with duplicate values


code:
def __init__(self, **kw):
   super(SomeFilter, self).__init__(**kw)
   self.filters['provider'].extra['queryset'] = Provider.objects.filter(foo__in=self.queryset)

rawDescription: Hide filter items that produce zero results in django-filter


code:
my_key = 1
a = session.query(Animal).get(my_key)
# sqlalchemy will figure out the type automatically and will return object of proper class
assert type(a) in (Cat, Dog,)

rawDescription: Instantiating a subclass from a superclass


code:
from scipy.io import netcdf
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

rawDescription: Read .nc (netcdf) files using python

description: Read .nc (netcdf) files using python


code:
pos = f.find('torrents.humblebundle.com', pos+1)
end = f.find('.torrent', end+1)

rawDescription: Finding links in file, keeps repeating same link


code: array([0, 3], dtype=int32)

rawDescription: Python Numpy get 2 Indexes which are not in a Blacklist


code:
def floodfill (chars, x, y):
        try:
                if chars [y] [x] == 'x': return
                chars [y] [x] = 'x'
                floodfill (chars, x + 1, y)
                floodfill (chars, x - 1, y)
                floodfill (chars, x, y + 1)
                floodfill (chars, x, y - 1)
        except: pass

rawDescription: Recursive Function to change both <x and y> in a matrix?


rawDescription: Python create list of objects from list of 2 elements lists


code: np.array([np.trace(np.flipud(array),offset=k) for k in range(-1,3)])

rawDescription: numpy sum antidiagonals of array

description: Numpy sum antidiagonals of array


code:
import demjson
demjson.decode('{javascript_style:"Look ma, no quotes!"}')
demjson.decode('{javascript_style:"Look ma, no quotes!"}', strict=True)

rawDescription: Python: Bad JSON - Keys are not quoted

description: Python: Bad JSON - Keys are not quoted


code:
value = dct[key]
# 'D' is the value for (8, 9)

rawDescription: Loop through dictionary with a math function


code:
class HTTPConnection:
    # ...
    def send(self, data): # line 820
        """Send `data' to the server.
        ``data`` can be a string object, a bytes object, an array object, a
        file-like object that supports a .read() method, or an iterable object.
        """

rawDescription: Python - HTTP multipart/form-data POST request


code:
def comments_to_dicts(comments):
    results = []  # create list for results
    for comment in comments:  # iterate over comments
        item = {
            "id": comment.id,
            "author": comment.author,
        }  # create dict from comment

        if len(comment._replies) > 0:
            item["replies"] = comments_to_dicts(comment._replies)  # convert replies using the same function

        results.append(item)  # add converted item to results
    return results  # return all converted comments

rawDescription: Retrieving a threaded comment list recursively


code:
juvenile_population, adult_population, senile_population, total_population = (adult_population * birth_rate,
                                                                             juvenile_population * juvenile_survival,
                                                                             (adult_population * adult_survival) (senile_population * senile_survival),
                                                                             juvenile_population + adult_population + senile_population)

rawDescription: Setting new variables in a while loop with calculations PYTHON


cmd: echo $file_name

rawDescription: In Sublime Text 2 how can I pass the current file path to a command called by a key binding


code:
results = []
counter = 0
for iteration in xrange(10 ** 6):  # 1 million times
    counter += 1
    roll = random.randint(1, 6), random.randint(1, 6), random.randint(1, 6)
    if roll == (6, 6, 6):
        results.append(counter)
        counter = 0

sum(results, 0.0) / len(results)
len(results)

rawDescription: Python nested loops issues

description: Python nested loops issues


code:
commands = {
    'ping': ping
}

rawDescription: Skype4py !command with arguments

description: Skype4py !command with arguments


code:
np.where(Full_Names_Test_2['MarketCap'] == 'n/a', 7)
# should be
np.where(Full_Names_Test_2['MarketCap'] == 'n/a', Full_Names_Test_2['MarketCap'], 7)

rawDescription: np.where Not Working in my Pandas

description: Np.where Not Working in my Pandas


code:
def application(environ, start_response):
    write = start_response(status, headers)
    write('content block 1')
    write('content block 2')
    write('content block 3')
    return None

rawDescription: WSGI: what's the purpose of start_response function


rawDescription: cast from list to numpy array problems in python

description: Cast from list to numpy array problems in python


code:
def wrapper(fn, params):
    return fn(*params)

def myfunc(a):
    return 2*a

wrapper(myfunc, 2)
# TypeError: myfunc() argument after * must be a sequence, not int

wrapper(myfunc, (2,))  # Package the argument in a single-element tuple
# 4

rawDescription: How do I call a function with arbitrary parameters from another function?

description: Call a function with arbitrary parameters from another function


code:
hours = time_subtraction(self)
pay_calculation(self, hours)

rawDescription: Passing a variable from one function to another function


code:
from requests import Request
url = "https://stream-fxpractice.oanda.com/v1/prices"
pairs_oanda = ["EUR_USD", "GBP_USD"]
params = {'instruments': ','.join(pairs_oanda), 'accountId': 'foobarbaz'}
r = Request('GET', url, params=params)
r.prepare().url

rawDescription: Python Requests: Using lists when specifying parameters


code:
XlDirectionDown = 4
last = wb.Range("A:A").End(XlDirectionDown)
range = wb.Range("A1:A"+str(last))

rawDescription: Specify range as only selecting filled cells/ending at empty cell Python


code:
class ModelOutputList(APIView):
    def get(self, request):
        obj = self.get_objects()
        serializer = ModelOutputSerializer(obj)

        return Response(serializer.data)

    def get_objects(self):
        model1 = Model1.objects.all()
        model2 = Model2.objects.all()

        obj = {'model1': model1, 'model2': model2}

        return obj

rawDescription: Django-rest-framework serializing multiple queries without a related field


code:
RE = r'''
    (?:(\d) \s day.*?)?   # this should match "n day" if it's there
    \s(\d{1,2}):(\d{1,2}) # this should match a space followed by "hh:mm"
'''

rawDescription: Regular Expressions in Python - strange behaviour


rawDescription: Pandas Dataframe column with both Strings and Floats


code:
vector1 = (int(l[0][0]), int(l[0][1]), int(l[0][2]))

for a in range(1, nat):
    vector2 = (int(l[a][0]), int(l[a][1]), int(l[a][2]))
    dotProduct = reduce(operator.add, map(operator.mul, vector1, vector2))
    print(dotProduct)

rawDescription: How to apply parameters/for loop

description: Apply parameters/for loop


code:
fo = open("abc.txt", "r+")
a = fo.read()

rawDescription: Make a variable from what's in a text file


rawDescription: How do I return the index of a group of values from a list for a specific value in the group?

description: Return the index of a group of values from a list for a specific value in the group


code:
def LetterChanges(s):
    orig = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    new = 'bcdEfghIjklmnOpqrstUvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZA'
    result = ''
    for c in s:
        if c in orig:
            c = new[orig.index(c)]
        result += c
    return result

rawDescription: How to solve this Python puzzle in a much more elegant manner?

description: Solve this Python puzzle in a much more elegant manner


code:
import logging
logger = logging.getLogger(__name__)

def func1(*params):
    logger.debug("BEGIN func1(%s)", (params,))
    session = Session()

    try:
        do_something_with(params)

    except Exception as e:
        logger.exception("FAILED func1(%s)", (params,))

        logger.debug("ROLLINGBACK func1(%s)", (params,))
        session.rollback()
        logger.debug("ROLLEDBACK func1(%s)", (params,))

        # if you don't handle exceptions let them propagate, thanks
        raise

    else:
        logger.debug("SUCCEEDED func1(%s)", (params,))
        # don't you need a session.commit() somewhere ???

    finally:
        logger.debug("CLOSING func1(%s)", (params,))
        session.close()
        logger.debug("CLOSED func1(%s)", (params,))

rawDescription: Decorator to store function name to file and delete if there is no error


code: extra = len(s) % 16

rawDescription: How to make sure the input is a multiple of 16, and if not add padding to it

description: Make sure the input is a multiple of 16, and if not add padding to it


code:
category=''
step=0

menu = open("menuTextFormat.txt", 'r')
xml = open('menuTextXML.txt', 'w')

xml.write("<recipe>\n")

while 1:
    line = menu.readline()
    if not line:
        break

    #after checking for EOF, remove \n
    line = line.rstrip()

    #category
    if ":" in line:
        #set category as next line
        category = menu.readline().rstrip()
        step=1
        continue

    #name & servings
    if step == 1 and line:
        #write category
        xml.write("\t<category>\n\t\t" + category + "\n\t</category>\n")
        #write name
        xml.write("\t<name>\n\t\t" + line + "\n\t</name>\n")

        #check for serving size
        servings = menu.readline().rstrip()
        if not servings:
            xml.write("\t<servings>\n\t\tno serving size listed\n\t</servings>\n")
        else:
            xml.write("\t<servings>\n\t\t" + servings + "\n\t</servings>\n")

        step=2
        continue

    #ingredients
    if step == 2 and line:
        #write first ingredient, then loop for rest
        xml.write("\t<qty>\n\t\t" + line + "\n\t</qty>\n")
        xml.write("\t<ingredient>\n\t\t" + menu.readline().rstrip() + "\n\t</ingredient>\n")

        #loop for incredients
        while 1:
            qty = menu.readline().rstrip()
            #no more incredients, break loop
            if not qty:
                break

            xml.write("\t<qty>\n\t\t" + qty + "\n\t</qty>\n")
            xml.write("\t<ingredient>\n\t\t" + menu.readline().rstrip() + "\n\t</ingredient>\n")

        step=3
        continue

    #procedure
    if step == 3 and line:
        #write first step, then loop for rest
        xml.write("\t<procedure>\n")
        xml.write("\t\t<step>\n\t\t\t" + line + "\n\t\t</step>\n")

        #loop for steps
        while 1:
            step = menu.readline().rstrip()
            #no more steps, break loop
            if not step:
                break

            xml.write("\t\t<step>\n\t\t\t" + step + "\n\t\t</step>\n")

        xml.write("\t</procedure>\n")

        step=1
        continue

xml.write("</recipe>")
menu.close()
xml.close()

rawDescription: Python, unknown skip when reading/write document


code: savePlace = 'D:/Workspace/python{}.txt'

rawDescription: print number in some digits in python

description: Print number in some digits in python


code:
from flask import abort, render_template
import os.path

@cache.cached(timeout=86400)
@app.route('/programme/<prog_id>')
def programme(prog_id):
    path = os.path.join(my_location, "static/data/bandsdaily/")
    prog_ids = [os.path.splitext(filename)[0] for filename in os.listdir(path)]
    if prog_id not in prog_ids:
        # no such file, return a not-found status
        abort(404)

    daily_bands = os.path.join(my_location, prog_id  + ".json")
    with open(daily_bands) as f:
        event_details = [json.loads(l) for l in f]

    return render_template('index.html', data=event_details, prog_ids=prog_ids)

rawDescription: Get list of routes of a Flask function

description: Get list of routes of a Flask function


code:
letters = [letter for letter in string_lower_as_list(argv[1])
            if "a" <= letter <= "z"]

rawDescription: Rm duplication in list comprehension

description: Rm duplication in list comprehension


code:
from operator import itemgetter

...

l3 = sorted(d.values(), key=itemgetter("index"))

rawDescription: join two lists of dictionaries on a single key

description: Join two lists of dictionaries on a single key


code:
for i in reversed(data): ...     # generators aren't reversible

s[i], s[j] = s[j], s[i]          # generators aren't indexable

rawDescription: When is not a good time to use python generators?


code:
create.argtypes = [POINTER(POINTER(List)),]
create.restype = POINTER(List)
control = POINTER(List)()
newlist = create(byref(control))

rawDescription: Python ctypes pointer to pointer to structure


code: url = serviceurl + urllib.urlencode({'sensor':'false', 'address':  address})

rawDescription: Calling a JSON API

description: Calling a JSON API


code:
import sys, inspect
def print_classes():
    for name, obj in inspect.getmembers(sys.modules[__name__]):
        if inspect.isclass(obj):
            print(obj)

rawDescription: How can I get a list of all classes within current module in Python?

description: Get a list of all classes within current module in Python


rawDescription: Pandas: speed up df.loc based on repeat index values


rawDescription: Adding an array in numpy at a specified location


rawDescription: How to cluster (or group) the data from a CSV file?

description: Cluster (or group) the data from a CSV file


code:
def in_interval(intervals):
    if len(intervals) == 0:
        return False, None, None
    min_t = min(intervals[0])
    max_t = max(intervals[0])
    for interval in intervals[1:]:
        min_t = max(min_t, min(interval))
        max_t = min(max_t, max(interval))
    if min_t > max_t:
        return False, None, None
    else:
        return True, min_t, max_t

rawDescription: overlapping of 3 intervals: what is the fastest way

description: Overlapping of 3 intervals: what is the fastest way


code:
texts = brown.words()[:10000]
word_counts = Counter(texts)
word_counts['hits']
word_counts['hit']
word_counts['needs']
word_counts['need']

rawDescription: How to check if a word is more common in its plural form rather than in it's singular form in an array of words (with Python/NLTK)?

description: Check if a word is more common in its plural form rather than in it's singular form in an array of words (with Python/NLTK)


code: string = ''.join('[%s]' % x for x in self.obj.itervalues())

rawDescription: Simplification of iterating

description: Simplification of iterating


code:
class CustomThread(QtCore.QThread):
    def __init__(self, target, slotOnFinished=None):
        super(CustomThread, self).__init__()
        self.target = target
        if slotOnFinished:
            self.finished.connect(slotOnFinished)

    def run(self, *args, **kwargs):
        self.target(*args, **kwargs)

rawDescription: Start a new thread in Python with a callback method in Main Thread for PyQT application


code:
__a = 3

l = [__a]

class B:
    def __init__(self):
        self.a = l[0]
b = B()

rawDescription: How to access private variable of Python module from class

description: Access private variable of Python module from class


code:
class Dummy(object) :
    def __init__(self, price) :
        self._price = price
    def getPrice(self) :
        return self._price

...

sortedElements = sorted(elements, key = Dummy.getPrice)

rawDescription: How to sort by a particular attribute of a class?

description: Sort by a particular attribute of a class


code:
# Near the top of views.py
from datetime import datetime

# ...
currentMonth = datetime.now().strftime('%B')
return render_to_response('showroom.html',{'currentMonth':currentMonth,} , context_instance=RequestContext(request))

rawDescription: convert month numeric form into their name?

description: Convert month numeric form into their name


code:
import urllib.parse
urllib.parse.unquote('J%c3%a2nis', encoding='utf-8')

rawDescription: Type Unicode code points into Python CLI


code: os.system("python {} {} {}".format(code, input_file, output_file)) # Python 3.x

rawDescription: passing variable defined as files to os.system()

description: Passing variable defined as files to os.system()


code:
import pandas as pd

df = pd.DataFrame([['2015-07-07','2016-09-22'],['2012-02-03','2013-02-19'],['2013-02-17','2013-03-22']],columns = ['start','end'])

#change strings to date format
df['start'] = [pd.to_datetime(x) for x in df['start']]
df['end'] = [pd.to_datetime(x) for x in df['end']]

df['range'] = df['end']-df['start']

df

rawDescription: date range in csv using pandas in python

description: Date range in csv using pandas in python


rawDescription: wxpython auinotebook close tab event

description: Wxpython auinotebook close tab event


code:
soup.find('div', {'class': ''}).string
soup.find('div', {'class': ''}).string.strip()

rawDescription: How to extract values with BeautifulSoup with no class

description: Extract values with BeautifulSoup with no class


rawDescription: python, dictionary value is object, can that object access its own key value from a function within itself?

description: Python, dictionary value is object, can that object access its own key value from a function within itself


rawDescription: Pandas: index data by a histogram result


code:
mylist = [(a, b), (c, d), (e, f)]
for args in mylist:
    myfunc(*args)

rawDescription: How do I pass tuples elements to a function as arguments in python?

description: Pass tuples elements to a function as arguments in python


code:
contents = []
for document in documents:
    with open(document+'.txt', 'r') as f:
        contents.append(f)

rawDescription: Python: How to read a directory of texts into a list


code:
from mpl_toolkits.mplot3d import axes3d
import numpy as np
import matplotlib
from matplotlib import cm
import matplotlib.pyplot as plt
from matplotlib.mlab import griddata
import math
f=open(filedir+'/'+'temp_1.txt','r')
for line in f:
    line=line.strip()
    temp=line.split(',')
    temp1=float(temp[0])
    temp2=float(temp[1])
    temp3=float(temp[2])
    #num_z=math.log(temp3)
    num_x=temp1
    num_y=temp2
    num_z=temp3
    x.append(num_x)
    y.append(num_y)
    z.append(num_z)
for num in range(len(z)):
      if z[num] != 0:
        z1.append(math.log(z[num]))
      else:
        z1.append(0)
xi=np.linspace(min(x),max(x))
yi=np.linspace(min(y),max(y))

min_x=min(x)-2
max_x=max(x)+2
min_y=min(y)-2
max_y=max(y)+20
min_z=min(z1)-2
max_z=max(z1)+2
pi=3.14
fig = plt.figure()
ax = fig.add_subplot(1,1,1, projection='3d')
ax.set_xlabel('Frequency')
ax.set_ylabel('Distance')
ax.set_zlabel('Sound_Pressure Level')
X,Y=np.meshgrid(xi,yi)
Z=griddata(x,y,z1,xi,yi)
surf=ax.plot_surface(X,Y,Z,rstride=5,cstride=5,cmap=cm.jet,linewidth=1,antialiased=True)
#ax.view_init(90, -90)
cset = ax.contour(X, Y, Z, zdir='z', offset=min_z, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=min_x, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=max_y, cmap=cm.coolwarm)

ax.set_xlim3d(min_x, max_x)
ax.set_ylim3d(min_y,max_y)
ax.set_zlim3d(min_z,max_z)
plt.show()

rawDescription: plot a 3d surface plot using matplotlib

description: Plot a 3d surface plot using matplotlib


code:
import cv2
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# contours = [array([[[x1,  y1]], ..., [[xn,  yn]]]), array([[[x1,  y1]], ..., [[xn,  yn]]])]
contour = contours[0] # contours[i], where i = index of the contour
# contour = [[[x1,  y1]], [[x2,  y2]], ..., [[xn,  yn]]]
# contour[0] = [[x1,  y1]]
# contour[0][0] = [x1,  y1]
# contour[0][0][0] = x1
# contour[0][0][1] = y1

rawDescription: How to access opencv contour point indexes in python?

description: Access opencv contour point indexes in python


code:
def process_request(self, request):

    if self.is_language_prefix_patterns_used():
        lang_code = (get_language_from_path(request.path_info) or
                     request.session.get('django_language', settings.LANGUAGE_CODE))

        activate(lang_code)
        request.session['django_language'] = lang_code
        request.LANGUAGE_CODE = get_language()

rawDescription: Django i18n pattern

description: Django i18n pattern


rawDescription: How do I remove identical items from a list and sort it in Python?

description: Remove identical items from a list and sort it in Python


code: ok2split = set('properties', 'foo', 'blah')

rawDescription: Convert a colon separated string to a list - within a list of dictionaries... (Python)


code:
# first read the file to determine the min/max
data={'max':{}, 'min':{}}
with open(fn_in, 'rb') as fin:
    reader=csv.reader(fin, delimiter='\t')
    for row in reader:
        key=row[-1]
        data['max'].setdefault(key, -sys.maxint-1)
        data['min'].setdefault(key, sys.maxint)
        li=[conv(row[2]), conv(row[3])]
        data['max'][key]=max([max(li), data['max'][key]])
        data['min'][key]=min(min(li), data['min'][key])

# now change the values by name:
with open(fn_out, 'wb') as fout, open(fn_in, 'r') as fin:
    reader=csv.reader(fin, delimiter='\t')
    writer=csv.writer(fout, delimiter='\t')
    for row in reader:
        key=row[-1]
        tr=[conv(row[2]), conv(row[3])]
        if data['max'][key] in tr:
            tgt=max(tr)
            row[2:4]=[e+10 if e==tgt else e for e in tr]
            tr=row[2:4]
        if data['min'][key] in tr:
            tgt=min(tr)
            row[2:4]=[e-20 if e==tgt else e for e in tr]

        writer.writerow(row)

rawDescription: Finding min() and max() of Python dictionary key-value pair complexes


code:
seq = [x['the_key'] for x in dict_list]
min(seq)
max(seq)

rawDescription: In List of Dicts, find min() value of a common Dict field


code:
import operator
sorted(rows, key=operator.itemgetter(0))

rawDescription: custom sort a list of list of numbers in ascending order

description: Custom sort a list of list of numbers in ascending order


code:
def test():
    assert some_actions(1,2) == 10

@pytest.fixture()
def some_fixture():
     return some_actions(1,2)

rawDescription: unittest Vs pytest

description: Unittest Vs pytest


code:
from timeit import timeit
MAX_NUM = 3*10**3
def bar():
    i = MAX_NUM + sys.maxsize
    while i > sys.maxsize:
        i -= 1

rawDescription: Why is Python 3 is considerably slower than Python 2?


code:
root = Tk()
root.geometry("400x400")

rawDescription: Arranging size of a frame in tkinter

description: Arranging size of a frame in tkinter


code:
def add_nan(DF, T):
    start = DF.time[len(DF)-1]
    stop = DF.time[0]
    rng = pd.date_range(start, stop, freq=T)
    DF = DF.drop_duplicates('time').set_index('time').reindex(rng)
    return DF.ffill(limit=True)

rawDescription: How to limit NaN filling in pandas dataframe

description: Limit NaN filling in pandas dataframe


code: z = dict(d2.items() + d1.items())

rawDescription: Python: Dictionary merge by updating but not overwriting if value exists


code: numpy.searchsorted(a, b, side='right')

rawDescription: Check between which floats in a list a given float falls


code: pair_elem = ','.join('%s%s' % (x, y) for y in to for x in fro)

rawDescription: How to add two odd lists into one list in python?

description: Add two odd lists into one list in python


code:
import logging

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='logger.log',
                    filemode='w', )
logtool = logging.getLogger('MainLogs')
logtool.setLevel(logging.INFO)
fh = logging.FileHandler('logger.log')
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
logtool.addHandler(ch)

rawDescription: define python logger in one script and use it in all other scripts

description: Define python logger in one script and use it in all other scripts


code:
from collections import namedtuple
from pandas import DataFrame
import numpy as np

df = DataFrame({'variable_1':np.arange(5),'variable_2':np.arange(5)})

rawDescription: IPython Notebook and Pandas autocomplete


code:
string_to_insert = sys.argv[1]
file_to_put_string_in = sys.argv[2]

rawDescription: Put an argument into a string

description: Put an argument into a string


code:
import matplotlib.pyplot as plt

plt.plot([0,10], [0,10])
plt.axis()

rawDescription: Matplotlib continuing line into infinity


rawDescription: Understanding the syntax of numpy.r_() concatenation


code:
x = np.linspace(-1,1, 9)
y = np.linspace(-1,1, 9)

rawDescription: Matplotlib- meshgrid

description: Matplotlib- meshgrid


code:
data = []
for row in reader:
    data.append([1 if entry=='X' else 0 for entry in row[1:]])

rawDescription: How to parse of a simple csv file?

description: Parse of a simple csv file


code:
import dis
dis.dis(test1)
dis.dis(test5)

rawDescription: Why is taking the mod of a number in python faster with exponents?


rawDescription: Elasticsearch relative time range query in Python


code:
def foo(li, func, num_params):
    chunks = (li[i:i+num_params] for i in range(0, len(li), num_params))
    def function(t, *args):
        result = 0
        iter_args = iter(args)
        for chunk in chunks:
            actual_params = [next(iter_args) if x is None else x for x in chunk]
            result += func(t, *actual_params)
        return result
    return function

rawDescription: List defining the list of variable of function in Python


code:
import lib

METADATA = 'metadata_example'

class Monolith(object):

    def foo(self, raw_event):
        action =  'action_example' # ... Parse Event
        # Middle of function
        lib.event.Event(METADATA, action)
        # Continue on to use the build event.

rawDescription: Python unit test mock, get mocked function's input arguments


code:
import win32security
import ntsecuritycon as con
import sys

# List of all file masks that are interesting
ACCESS_MASKS = ['FILE_READ_DATA', 'FILE_LIST_DIRECTORY', 'FILE_WRITE_DATA', 'FILE_ADD_FILE',
                     'FILE_APPEND_DATA', 'FILE_ADD_SUBDIRECTORY', 'FILE_CREATE_PIPE_INSTANCE', 'FILE_READ_EA',
                     'FILE_WRITE_EA', 'FILE_EXECUTE', 'FILE_TRAVERSE', 'FILE_DELETE_CHILD',
                     'FILE_READ_ATTRIBUTES', 'FILE_WRITE_ATTRIBUTES', 'FILE_ALL_ACCESS', 'FILE_GENERIC_READ',
                     'FILE_GENERIC_WRITE', 'FILE_GENERIC_EXECUTE']

# List of all inheritance flags
ACE_FLAGS = ['OBJECT_INHERIT_ACE', 'CONTAINER_INHERIT_ACE', 'NO_PROPAGATE_INHERIT_ACE', 'INHERIT_ONLY_ACE']

# List of all ACE types
ACE_TYPES = ['ACCESS_MIN_MS_ACE_TYPE', 'ACCESS_ALLOWED_ACE_TYPE', 'ACCESS_DENIED_ACE_TYPE', 'SYSTEM_AUDIT_ACE_TYPE',
             'SYSTEM_ALARM_ACE_TYPE', 'ACCESS_MAX_MS_V2_ACE_TYPE', 'ACCESS_ALLOWED_COMPOUND_ACE_TYPE',
             'ACCESS_MAX_MS_V3_ACE_TYPE', 'ACCESS_MIN_MS_OBJECT_ACE_TYPE', 'ACCESS_ALLOWED_OBJECT_ACE_TYPE',
             'ACCESS_DENIED_OBJECT_ACE_TYPE', 'SYSTEM_AUDIT_OBJECT_ACE_TYPE', 'SYSTEM_ALARM_OBJECT_ACE_TYPE',
             'ACCESS_MAX_MS_OBJECT_ACE_TYPE', 'ACCESS_MAX_MS_V4_ACE_TYPE', 'ACCESS_MAX_MS_ACE_TYPE',
             'ACCESS_ALLOWED_CALLBACK_ACE_TYPE', 'ACCESS_DENIED_CALLBACK_ACE_TYPE', 'ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE',
             'ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE', 'SYSTEM_AUDIT_CALLBACK_ACE_TYPE', 'SYSTEM_ALARM_CALLBACK_ACE_TYPE',
             'SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE', 'SYSTEM_ALARM_CALLBACK_OBJECT_ACE_TYPE', 'SYSTEM_MANDATORY_LABEL_ACE_TYPE',
             'ACCESS_MAX_MS_V5_ACE_TYPE']

################################################################################
def get_ace_types_str(ace_type):
    ''' Yields all matching ACE types as strings
    '''
    for t in ACE_TYPES:
        if getattr(con, t) == ace_type:
            yield t

################################################################################
def get_ace_flags_str(ace_flag):
    ''' Yields all matching ACE flags as strings
    '''
    for t in ACE_FLAGS:
        attr = getattr(con, t)
        if (attr & ace_flag) == attr:
            yield t

################################################################################
def get_access_mask_str(access_mask):
    ''' Yields all matching ACE flags as strings
    '''
    for t in ACCESS_MASKS:
        attr = getattr(con, t)
        if (attr & access_mask) == attr:
            yield t

################################################################################
def list_file_ace(filename):
    ''' Method for listing of file ACEs
    '''

    # Load data
    sd = win32security.GetFileSecurity(filename, win32security.DACL_SECURITY_INFORMATION)
    dacl = sd.GetSecurityDescriptorDacl()

    # Print ACE count
    ace_count = dacl.GetAceCount()
    print('File', filename, 'has', ace_count, 'ACEs')

    # Go trough individual ACEs
    for i in range(0, ace_count):
        (ace_type, ace_flag), access_mask, usersid = dacl.GetAce(i)
        user, group, usertype = win32security.LookupAccountSid('', usersid)

        print('\tUser: {}\\{}'.format(group, user))
        print('\t\tACE Type ({}):'.format(ace_type), '; '.join(get_ace_types_str(ace_type)))
        print('\t\tACE Flags ({}):'.format(ace_flag), ' | '.join(get_ace_flags_str(ace_flag)))
        print('\t\tAccess Mask ({}):'.format(access_mask), ' | '.join(get_access_mask_str(access_mask)))
        print()

################################################################################
# Execute with some defaults
if __name__ == '__main__':
    for filename in sys.argv[1:]:
        list_file_ace(filename)
        print()

rawDescription: How to authorize/deny write access to a directory on Windows using Python?

description: Authorize/deny write access to a directory on Windows using Python


code: firsWithPath = fileWithPath.replace('"', '')

rawDescription: Python: Splitting a path string containing double quotes


code:
def read_only_lazyprop(fn):
    attr_name = '_lazy_' + fn.__name__
    @property
    def _lazyprop(self):
        if not hasattr(self, attr_name):
            setattr(self, attr_name, fn(self))
        return getattr(self, attr_name)
    @_lazyprop.setter
    def _lazyprop(self,value):
        raise AttributeError("This property is read-only")
    return _lazyprop

rawDescription: How to create decorator for lazy initialization of a property

description: Create decorator for lazy initialization of a property


code:
std_delete = raw_input("Student To Delete")
students = filter(lambda x: x.studentID != std_delete, students)

rawDescription: OOP - creating class adding to list then deleting


code:
for line in ins:
    row = line.split()[:5]
    row.extend([None] * (5 - len(row)))
    parseTable.append(row)

rawDescription: transfer textfile contents into database python

description: Transfer textfile contents into database python


rawDescription: Displaying unicode characters in Python 3


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

<text>Hello world!</text>
''')
soup.div.text
soup.div.find('text')

rawDescription: Python Beatifulsoup tag name and attribute conflict


code: a, b, c = map(None,*l)

rawDescription: Pass each nested list as an arg to map

description: Pass each nested list as an arg to map


code:
def place_submatrix(M, A, i, j):
    """Place submatrix A in M wit top left corner (i, j)"""

    for ii in range(len(A)):
        for jj in range(len(A)):
            M[i + ii][j + jj] = A[ii][jj]

rawDescription: Matrix in Python Changing some Values

description: Matrix in Python Changing some Values


code: result = newline + '\n' #or '\r\n' depending on your newline format.

rawDescription: Replace a whole line in a file

description: Replace a whole line in a file


code: sorted(['Bear', 'bear', 'Apple', 'apple'], key=lambda x: (x.casefold(), x.swapcase()))

rawDescription: How to sort a list in python to make lowercase precede uppercase?

description: Sort a list in python to make lowercase precede uppercase


code: replaced = re.subn('(<pre[^>]*)', '\\1 class="prettyprint"', markup)

rawDescription: Wrap markdown code blocks with prettyprint classes in Python


code: [f for f in fileURLS if 'Weekly' not in f]

rawDescription: Python Downloading Data File from Web-Scraped URL


code: lines = [line.rstrip("\n") for infile in infiles for line in open(infile)]

rawDescription: From files to list of lines

description: From files to list of lines


rawDescription: Boolean indexing to find character

description: Boolean indexing to find character


code:
def get_by_id(lst, id):
    for d in lst:
        if d.get('id') == str(id):
            return d
    return None

rawDescription: How do i select row json with the id

description: Select row json with the id


rawDescription: Python Counter alternative for Java

description: Python Counter alternative for Java


code:
x = [1, 2, 3, 4, 2, 3, 3]
y = [0, 0, 0, 0, 1, 1, 2]
z = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] # in your case, this is data
dx = [x[1]-x[0]]*len(x)   # assuming equally spaced data-points

# you can use the colormap like this in your case:
# cmap = plt.cm.hot

fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
ax.axis([min(x)-1., max(x)+1., min(y)-1., max(y)+1.])

for x, y, c, h in zip(x, y, z, dx):
    ax.add_artist(Rectangle(xy=(x-h/2., y-h/2.),
                  color=c,             # or, in your case: color=cmap(c)
                  width=h, height=h))  # Gives a square of area h*h

fig.savefig('test.png')

rawDescription: Choosing marker size in Matplotlib

description: Choosing marker size in Matplotlib


code:
def factors(n):
    l = []
    append = l.append
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            append(i)
            append(n//i)
    return l

rawDescription: list comprehension with multiple assignments

description: List comprehension with multiple assignments


rawDescription: Converting daily data in to weekly in Pandas


rawDescription: Selecting items from an array

description: Selecting items from an array


code:
import datetime
orig = datetime.datetime.fromtimestamp(1425917335)
new = orig + datetime.timedelta(days=90)
print(new.timestamp())

rawDescription: Python add days in epoch time

description: Python add days in epoch time


code:
for _ in range(6):  # loop 6 times
    if guess < number:
        print('Your guess is too low.')
    elif guess > number:
        print('Your guess is too high.')
    else:
        break

    guess = int(input('Try again: '))

rawDescription: Radius guessing game loop going wrong

description: Radius guessing game loop going wrong


code:
if a[0] is None:
   start = next(ele for ele in a if ele is not None)
for ind, ele in enumerate(a):
    if ele is None:
        a[ind] = start
    else:
        start = ele
print(a)

rawDescription: Replace None in list with leftmost non none value


rawDescription: Interpret "plain text" as utf-8 text in python


rawDescription: Efficiently comparing data across rows in a Pandas Dataframe


code:
paths = os.environ['MY_IRONPYTHON_EXTRA_PATH'].split(';')
sys.path.extend(paths)

rawDescription: Importing Python Librarys over C#?

description: Importing Python Librarys over C#


code:
if set(user_string.split('*')).issubset(viable_entries):
     ...

rawDescription: How to check whether a string is a concatenation of other strings with a character inserted between each string in python

description: Check whether a string is a concatenation of other strings with a character inserted between each string in python


code:
class FixedPointContext(Context):

    def __init__(self, prec=None, rounding=None, Emin=None, Emax=None,
                       capitals=None, clamp=None, flags=None, traps=None,
                       _ignored_flags=None, decimal_places=None):
        super().__init__(prec, rounding, Emin, Emax, capitals, clamp, flags,
                traps, _ignored_flags)
        try:
            dc = DefaultContext
        except NameError:
            pass
        self.decimal_places = decimal_places if decimal_places is not None else dc.decimal_places

    def __setattr__(self, name, value):
        if name == "decimal_places":
            object.__setattr__(self, name, value)
        else:
            super().__setattr__(name, value)

    def __reduce__(self):
        flags = [sig for sig, v in self.flags.items() if v]
        traps = [sig for sig, v in self.traps.items() if v]
        return (self.__class__,
                (self.prec, self.rounding, self.Emin, self.Emax,
                 self.capitals, self.clamp, flags, traps, self._ignored_flags,
                 self.decimal_places))

    def __repr__(self):
        """Show the current context."""
        s = []
        s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
                 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, '
                 'clamp=%(clamp)d, decimal_places=%(decimal_places)d'
                 % vars(self))
        names = [f.__name__ for f, v in self.flags.items() if v]
        s.append('flags=[' + ', '.join(names) + ']')
        names = [t.__name__ for t, v in self.traps.items() if v]
        s.append('traps=[' + ', '.join(names) + ']')
        return ', '.join(s) + ')'

    def _shallow_copy(self):
        """Returns a shallow copy from self."""
        nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
                     self.capitals, self.clamp, self.flags, self.traps,
                     self._ignored_flags, self.decimal_places)
        return nc

    def copy(self):
        """Returns a deep copy from self."""
        nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
                     self.capitals, self.clamp,
                     self.flags.copy(), self.traps.copy(),
                     self._ignored_flags, self.decimal_places)
        return nc
    __copy__ = copy

# reinitialise default context
DefaultContext = FixedPointContext(decimal_places=2)

# copy changes over to decimal module
decimal.Context = FixedPointContext
decimal.DefaultContext = DefaultContext
Context = FixedPointContext

# test
decimal.getcontext().decimal_places = 1
decimal.getcontext().prec = 5
decimal.getcontext().Emax = 2
a = Decimal("0.34")
b = Decimal("0.20")
assert a * b == Decimal("0.1")

rawDescription: Python decimal context for fixed point

description: Python decimal context for fixed point


code: uEmail =  str(email['email']).strip()

rawDescription: Python Validate_Email Doesn't work when pulling from MongoDB


code:
from datetime import datetime
def yearsago(years, from_date=None):
    if from_date is None:
        from_date = datetime.now()
    try:
        return from_date.replace(year=from_date.year - years)
    except ValueError:
        # Must be 2/29!
        assert from_date.month == 2 and from_date.day == 29 # can be removed
        return from_date.replace(month=2, day=28,
                                 year=from_date.year-years)

rawDescription: Python timedelta in years

description: Python timedelta in years


rawDescription: How to quickly determine if a matrix is a permutation matrix

description: Quickly determine if a matrix is a permutation matrix


code:
profitorloss = (amountstocksoldfor - amountofcommissiontobroker) - (amountpaidforstocks + amountpaidtobroker)
totalprofit += profitorloss

rawDescription: Python Loops Complication

description: Python Loops Complication


code:
with open('story.txt', 'r') as infile:
    data = infile.read()
data = data.translate(None, ';:.,!?')
words = data.split()

rawDescription: File I/O isolating a word in a text file


code:
# Python 3.4+
from abc import ABC, abstractmethod
class Abstract(ABC):
    @abstractmethod
    def foo(self):
        pass

rawDescription: Is it possible to make abstract classes in python?


code: plot(g, layout=layout, margin=0, bbox=(800,400))

rawDescription: How to set the coordinates of nodes in Python Igraph

description: Set the coordinates of nodes in Python Igraph


code:
import sys
from setuptools import setup

extra_install_requires = []
if sys.version_info < (2, 7):
    extra_install_requires.append('ordereddict>=1.1')

setup(
    # ...
    install_requires = [...] + extra_install_requires,
    # ...
)

rawDescription: What is the best way to handle dependencies based on the Python version?


rawDescription: Splitting strings at multiple delimiters in python


code:
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ListProperty

kv = '''
<ColoredLabel>:
    size: (100,100)

    background_color:
    canvas.before:
        Color:
            rgba: self.background_color
        Rectangle:
            pos: self.pos
            size: self.size
    '''

Builder.load_string(kv)

class ColoredLabel(Label):
    background_color = ListProperty((0,0,0,1))

class MyApp(App):
    def build(self):
        f = FloatLayout()
        layout = BoxLayout(size_hint=(1, None), height=50, pos_hint={'top': 1})

        label1 = ColoredLabel(text="jenkins", background_color=(160,160,160,.5))
        layout.add_widget(label1)

        label2 = ColoredLabel(text="git", background_color=(160,160,160,.5))
        layout.add_widget(label2)

        label3 = ColoredLabel(text="portal", background_color=(160,160,160,.5))
        layout.add_widget(label3)

        f.add_widget(layout)

        return f

if __name__ == "__main__":
    MyApp().run()

rawDescription: python kivy boxlayout set position

description: Python kivy boxlayout set position


rawDescription: Python float formatting - like "g", but with more digits


code:
class RecipeForm(forms.Form):
    Recipebase_id = forms.ModelChoiceField(queryset=Recipebase.objects.none())

    def __init__(self, user, *args, **kwargs):
        super(RecipeForm, self).__init__(*args, **kwargs)
        qs = Recipebase.objects.filter(user=user)
        self.fields['Recipebase_id'].queryset = qs

rawDescription: How to filter model choice field options based on user in django?

description: Filter model choice field options based on user in django


rawDescription: How to extract tags from HTML using Beautifulsoup in Python

description: Extract tags from HTML using Beautifulsoup in Python


code: [list(group) for k, group in groupby(l, bool) if k]

rawDescription: Python split for lists

description: Python split for lists


code:
import multiprocessing

pool = multiprocessing.Pool(processes=6)  # Create a pool with 6 workers.
A=list_100_a #list of 100 different a values

# Use the workers in the pool to call repeat on each value of a in A.  We
# throw away the result of calling map, since it looks like the point of calling
# repeat(a) is for the side effects (files created, etc).
pool.map(repeat, A)

# Close the pool so no more jobs can be submitted to it, then wait for
# all workers to exit.
pool.close()
pool.join()

rawDescription: Memory issue in parallel Python

description: Memory issue in parallel Python


code:
import re
myUserInput = re.sub('(?:\r\n|\r|\n)', '<br />', myUserInput)

rawDescription: Process whitespaces from user input

description: Process whitespaces from user input


code:
result = []
query_array = query[0].toarray()
for row in tfidf_matrix:
    result = result + [cosine(row.toarray(), query_array)]

rawDescription: Better way to map a function (cosine similarity) to each row in scipy.csr_matrix


rawDescription: What's the meaning of '@' in python code?


code:
decoded_data = json.loads(data)
return render(request, 'my-template.html',
                       {'objects': decoded_data['objects']})

rawDescription: Django : Parsing Json data to template

description: Django : Parsing Json data to template


code:
import itertools

def chunks(it):
    while True:
        it = itertools.dropwhile(lambda x: 'BEGIN_DB' not in x, it)
        it = itertools.dropwhile(lambda x: x.strip(), it)
        next(it)
        yield itertools.takewhile(lambda x: 'END_DB' not in x, it)

rawDescription: Lazy parse a stateful, multiline per record data stream in Python?


code:
cmyk = lut[rgb[0], rgb[1], rgb[2]]
cmyk = cmyk.swapaxes(2, 1).swapaxes(1, 0).copy()

rawDescription: Fancier Fancy Indexing in NumPy?

description: Fancier Fancy Indexing in NumPy


code:
def new_function():
    return bar(2, 3)

rawDescription: Passing function returns as method parameters in Python


code:
dt0 = np.dtype(('u1',(3,)))
dt1 = np.dtype(('u1',(4,)))
dtb = np.dtype({'names':['rgb','rgba'],
                'offsets':[0,0],
                'formats':[dt0, dt1]})
X = np.arange(n*m*3,dtype='u1').reshape(n,m,3)
X1 = np.zeros((n,m), dtype=dtb)
X1['rgb'][:] = X

rawDescription: Change stride of numpy array (altering data)


code:
result = {}
for name, qty in zip(populate_name, populate_qty):
    result[name] = result.get(name, 0) + int(qty)

name, qty = sorted(result.items(), key=lambda o: o[1])[-1]

rawDescription: Add the elements value in a list

description: Add the elements value in a list


code:
import math
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.animation as animation

class Queue:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def enqueue(self, item):
        self.items.insert(0,item)

    def dequeue(self):
        return self.items.pop()

    def size(self):
        return len(self.items)

def euclideanDistance(pos1, pos2):
    return math.sqrt(math.pow((pos2[0]-pos1[0]),2) + math.pow((pos2[1]-pos1[1]),2))

def getChildren(node, maze):
    children = []
    y = node[0]
    x = node[1]
    i = 0
    if y-1 != -1 and maze[y-1][x] != 1 and maze[y-1][x] != 2:
        children.append([])
        children[i].append(y-1)
        children[i].append(x)
        i += 1
    if y-1 != -1 and x+1 != 12 and maze[y-1][x+1] != 1 and maze[y-1][x+1] != 2:
        children.append([])
        children[i].append(y-1)
        children[i].append(x+1)
        i += 1
    if x+1 != 12 and maze[y][x+1] != 1 and maze[y][x+1] != '.':
        children.append([])
        children[i].append(y)
        children[i].append(x+1)
        i += 1
    if y+1 != 12 and x-1 != -1 and maze[y+1][x-1] != 1 and maze[y+1][x-1] != 2:
        children.append([])
        children[i].append(y+1)
        children[i].append(x-1)
        i += 1
    if y+1 != 12 and maze[y+1][x] != 1 and maze[y+1][x] != '.':
        children.append([])
        children[i].append(y+1)
        children[i].append(x)
        i += 1
    if y+1 != 12 and x+1 != 12 and maze[y+1][x+1] != 1 and maze[y+1][x+1] != 2:
        children.append([])
        children[i].append(y+1)
        children[i].append(x+1)
        i += 1
    if x-1 != -1 and maze[y][x-1] != 1 and maze[y][x-1] != 2:
        children.append([])
        children[i].append(y)
        children[i].append(x-1)
        i += 1
    if y-1 != -1 and x-1 != -1 and maze[y-1][x-1] != 1 and maze[y-1][x-1] != 2:
        children.append([])
        children[i].append(y-1)
        children[i].append(x-1)
        i += 1
    return children

def step():
    seen = set()
    q = Queue()
    path = maze
    root.append(0)
    q.enqueue(root)
    while not q.isEmpty():
        temp = q.dequeue()
        frozen = tuple(map(tuple, path))
        if frozen not in seen:
            seen.add(frozen)
            yield path
        path[temp[0]][temp[1]] = 2
        if temp[0] == goal[0] and temp[1] == goal[1]:
            return path
        else:
            children = getChildren(temp, path)
            cArray = []
            if len(children) != 0:
                for child in children:
                    child.append(temp[2]+euclideanDistance(temp, child))
                    cArray.append(child)
                cArray.sort(key=lambda x:x[2])
                for child in cArray:
                    q.enqueue(child)

def animate(data, quadmesh):
    quadmesh.set_array(data.ravel())
    return [quadmesh]

maze = np.array([[0,0,0,0,0,0,0,0,0,0,0,0],
                 [0,1,1,1,1,1,1,1,1,1,1,0],
                 [0,1,1,1,1,1,1,1,0,3,1,0],
                 [0,0,0,0,0,0,1,1,0,0,1,0],
                 [0,1,1,0,0,0,1,1,0,0,1,0],
                 [0,1,1,0,0,0,1,1,0,0,1,0],
                 [0,1,0,0,0,0,1,1,0,0,1,0],
                 [0,0,0,0,0,1,1,1,0,0,1,0],
                 [0,0,0,0,1,1,1,1,0,0,1,0],
                 [0,0,0,1,1,1,1,1,0,0,1,0],
                 [0,0,1,1,1,1,1,1,0,0,0,0],
                 [0,0,0,0,0,0,0,0,0,0,0,0]])
root = [11, 0]
goal = [2, 9]

fig, ax = plt.subplots()
x = np.arange(13)
y = x[::-1]
X, Y = np.meshgrid(x, y)
plt.xticks([0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5,10.5,11.5], [0,1,2,3,4,5,6,7,8,9,10,11])
plt.yticks([0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5,10.5,11.5], [0,1,2,3,4,5,6,7,8,9,10,11])

cmap = mcolors.ListedColormap(['w','grey','green','red'])
quadmesh = ax.pcolormesh(X, Y, maze, edgecolor='k',cmap=cmap)

ani = animation.FuncAnimation(
    fig, animate, step,
    interval=10, fargs=[quadmesh], repeat=False, blit=True)
plt.show()

rawDescription: Python - matplotlib.pyplot ion() slow

description: Python - matplotlib.pyplot ion() slow


code: u'áéíóú'

rawDescription: Accents/special characters (e.g., ñ) in verbose_name or help_text ?


code: simpleObject = jvm.com.example.SimpleClass(ssqlContext, jdf, "v")

rawDescription: How to use a Scala class inside Pyspark

description: Use a Scala class inside Pyspark


code: float(your_string.rstrip('%')) / 100.0

rawDescription: Pythonic way to get .03 from 3%

description: Pythonic way to get .03 from 3%


code:
urls = (
    '/', 'Index',
    '/search/text=(.*)', 'Search',
)

rawDescription: Webpy doesn't validates form

description: Webpy doesn't validates form


code: x,y = list(x), list(y)

rawDescription: how to parse column data to arrays?

description: Parse column data to arrays


code:
sender.py
delim = "\x00"
ser.write(msg+delim)

rawDescription: pySerial : Can't read data more than 8 characters

description: PySerial : Can't read data more than 8 characters


code:
def check(fld1,fld2,cnxn_sub):
    rowpair = ''.join((fld1,fld2))
    return cnxn_sub[rowpair]

rawDescription: Conditionally and interatively calculate column based on value of three columns


code:
def __init__(self, items=None):
    if items is None: items = []
    self.l = items

rawDescription: How to allow __init__ to allow 1 or no parameters in python

description: Allow __init__ to allow 1 or no parameters in python


code:
from timeit import timeit
timeit("a=range(10000000);print sorted(set(a))[-2]", number=10)
# This is NPE's answer
timeit("a=range(10000000);maxa = max(a);print max(val for val in a if val != maxa)", number=10)

rawDescription: Find second largest element in list with repeated elements