code:
df1['time'] = pd.to_datetime(df1['time'].str.replace(".", ":"))
df2['w_time'] = pd.to_datetime(df2['w_time'].str.replace(".", ":"))

rawDescription: merging two pandas dataframes on nearest time stamp

description: Merging two pandas dataframes on nearest time stamp


code:
import yaml
config_file = ''
config = yaml.load(config_file) or {}
print(config)

rawDescription: Loading empty dictionary when YAML file is empty (Python 3.4)


code:
def docstring(docstr, sep="\n"):
    """
    Decorator: Append to a function's docstring.
    """
    def _decorator(func):
        if func.__doc__ == None:
            func.__doc__ = docstr
        else:
            func.__doc__ = sep.join([func.__doc__, docstr])
        return func
    return _decorator

rawDescription: Setting the docstring to an expression inside def


code:
def IsThisProcessRunning( ps_name ):
  ps = subprocess.Popen("ps axf | grep %s  | grep -v grep" % ps_name,
                        shell=True, stdout=subprocess.PIPE)
  output = ps.stdout.read()
  ps.stdout.close()
  ps.wait()

  if re.search(ps_name, output) is None:
      return False
  else:
      return True

IsThisProcessRunning('/usr/sbin/apache2') # True, if Apache2 is running.

rawDescription: SSH Server status in Python

description: SSH Server status in Python


rawDescription: Summarizing dataframe into a dictionary

description: Summarizing dataframe into a dictionary


code:
with nostdout():
    foo()

rawDescription: Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call


code:
file = fd.askopenfile()
if file:
    print(file.name)

rawDescription: Get file path from askopenfilename function in Tkinter


code:
rt = wx.TextCtrl(self, -1,"My Text....",size=(200, 100),style=wx.TE_MULTILINE|wx.TE_RICH2)
rt.SetInsertionPoint(0)
rt.SetStyle(2, 5, wx.TextAttr("red", "blue"))

rawDescription: different foreground colors for each line in wxPython wxTextCtrl

description: Different foreground colors for each line in wxPython wxTextCtrl


code:
def trim_string(data):
    return data[0:20]

rawDescription: Passing a custom python function into a tornado template


code:
def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            return period
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            return 0
        else:
            return period

rawDescription: How can I stop a While loop?

description: Stop a While loop


rawDescription: How to pass args to method in java, like f(*args) in python?

description: Pass args to method in java, like f(*args) in python


code:
def __init__(self, full_name, first_name, last_name, type_of_appeal, county, case_number,
             date_of_filing, link_to_page, race=None, sex=None, dc_number=None,
             hair_color=None, eye_color=None, height=None, weight=None, birth_date=None,
             initial_receipt_date=None, current_facility=None, current_custody=None,
             current_release_date=None):

      # set all arguments as attributes of this instance
      code     = self.__init__.__func__.func_code
      argnames = code.co_varnames[1:code.co_argcount]
      locs     = locals()
      self.__dict__.update((name, locs[name]) for name in argnames)

rawDescription: More Pythonic way of adding attributes to class?


code:
from itertools import groupby
from operator import itemgetter

def fruitfilter(fruits):
    for fruit, group in groupby(fruits, key=itemgetter(0)):
        yield max(group, key=itemgetter(2))

fruits = list(fruitfilter(fruits))

rawDescription: Python Filter List Items Relative to Each Other


code: b = [a[i][s] + a[i+1][s] for i in (0,2) for s in (slice(None,2), slice(2,None))]

rawDescription: adaptable function to slice up nested lists?

description: Adaptable function to slice up nested lists


code:
import unittest

@create_tests('test_url', 'file.txt')
class Test(unittest.TestCase):
    def test_url(self, name, url, expected):
        print(name, url, expected)

if __name__ == "__main__":
    unittest.main(verbosity=2)

rawDescription: How to dynamically create parameterized test from the file (json or yaml) in python

description: Dynamically create parameterized test from the file (json or yaml) in python


code: str(stmt)

rawDescription: How can I get the youngest objects from SQLAlchemy?

description: Get the youngest objects from SQLAlchemy


code: M = np.column_stack([np.random.rand(20,2), np.random.randint(1,4,size=(20,1))])

rawDescription: Scatter plot for a matrix of a given form


code: numbList = [random.randint(2, 5) for _ in range(random.randint(15, 20))]

rawDescription: Using a While loop to generate ints to append?


code:
Y
YY
YYY
YYYY
YYYYY

rawDescription: Using python, How can I make a pyramid using for loops?


code:
df_list=[df1, df2, df3]
for i, df in enumerate(df_list, 1):
    df.columns = [col_name+'_df{}'.format(i) for col_name in df.columns]

rawDescription: Renaming pandas data frame columns using a for loop


code:
r = 0.2
s = 0.02
steps = int(math.ceil(r/s))
lst = [(a*s, 1-(a+b)*s, b*s) for b in range(steps) for a in range(steps)]

rawDescription: Probability list creation

description: Probability list creation


code:
x = 0
y = 0

def someFunc():
  dosomethingwithconstants(x,y)

rawDescription: Constants in python?

description: Constants in python


code:
def get_file_contents(filename):
    with open(filename, 'r') as f:
        return f.read()

def word_count(filename):
    return len(get_file_contents(filename).split())

def line_count(filename):
    return len(get_file_contents(filename).splitlines())

def character_count(filename):
    return len(get_file_contents(filename))

rawDescription: How to use the same line of code in all functions?

description: Use the same line of code in all functions


code:
import re
input = "ABCDEF GABCDEF"
set(re.findall(regex, input))

rawDescription: Faster operation reading file

description: Faster operation reading file


code:
ns = argparse.NameSpace(files = [FileList('dir1'), FileList('dir2')])
# or
ns = argparse.NameSpace(files = ['dir1/file1','dir1/file2','dir2/file1',...])
parser.parse_args(sys.argv, namespace=ns)

rawDescription: Python argparse: type conversion of a list of default arguments


rawDescription: Merge columns and create new column with pandas


code:
if entry['item_id'] in tasks_dict:
    task = tasks_dict[entry['item_id']]
    if task['parent_id'] in folders_dict:
        folder = folders_dict[task['parent_id']]
        if folder in forbidden_folders_set:
            body_of_email += ...

rawDescription: Alternative to nested `for` loops in Python


code:
id_value_dictionary = {'id1': 'name1', 'id2': 'name2'}

if id not in id_value_dictionary:
    id_value_dictionary[id] = some_name

rawDescription: Searching for tuples in python based on the first part


rawDescription: QTableView item selection based on a QStandardItem data attribute


code:
# (nstars, ny, nx) pixel coordinates relative to each centroid
dx = cx[:, None, None] - x[None, ...]
dy = cy[:, None, None] - y[None, ...]

# 2D weighted histogram
bins = np.linspace(-50, 50, 100)
h, xe, ye = np.histogram2d(dx.ravel(), dy.ravel(), bins=bins,
                           weights=stars.ravel())

fig, ax = plt.subplots(1, 1, subplot_kw={'aspect':'equal'})
ax.hold(True)
ax.pcolormesh(xe, ye, h, cmap=plt.cm.hot)
ax.axhline(0, ls='--', lw=2, c='w')
ax.axvline(0, ls='--', lw=2, c='w')
ax.margins(x=0, y=0)

rawDescription: Stacking star PSFs from an Image; aligning sub-pixel centers


code:
bar10_p = partial(foo, b=10)
bar10_p.__doc__ = func.__doc__

rawDescription: Partial function application with the original docstring in Python?


rawDescription: How do I calculate the Euclidean distance between a point and a list of points in Python?

description: Calculate the Euclidean distance between a point and a list of points in Python


rawDescription: Python: change numpy array with NaNs to array with numbers and '--'


code:
import argparse

parser = argparse.ArgumentParser()

subparsers = parser.add_subparsers()

read = subparsers.add_parser('read')
read.add_argument('path')

write = subparsers.add_parser('write')
write.add_argument('path')
write.add_argument('value')

print(parser.parse_args(['read', 'foo']))
print(parser.parse_args(['write', 'foo', 'bar']))

rawDescription: Python argparse - creating subcommands with no labels


code:
import subprocess
from PIL import Image

FFMPEG_BIN = "ffmpeg"
movie_duration_seconds = 2
movie_fps = 24

ffmpeg_command = [ FFMPEG_BIN,
              '-y',
              '-f', 'image2pipe',
              '-vcodec','mjpeg',
              '-s', '480x360', # size of one frame
              '-i', 'pipe:0', # take input from stdin
              '-an', # Tells FFMPEG not to expect any audio
              '-r', str(movie_fps),
              #'-pix_fmt', 'yuvj420p',  # works fine without this
              #'-vcodec', 'mpeg4',  # not sure why this is needed
              #'-qscale', '5',  # works fine without this
              #'-b', '250',  # not sure why this is needed
              './fire.mp4' ]

ffmpeg_process = subprocess.Popen(ffmpeg_command, stdin=subprocess.PIPE)

for i in range(movie_fps * movie_duration_seconds):
   # each image is a shade of red calculated as a function of time
   im = Image.new("RGB",(480,360),(i%255,1,1))
   im.save(ffmpeg_process.stdin, "JPEG")
   ffmpeg_process.stdin.flush()
ffmpeg_process.stdin.close()
#ffmpeg_process.wait()
#ffmpeg_process.terminate()
ffmpeg_process.communicate()  # not sure if is better than wait but
                              # terminate seems not required in any case.

rawDescription: Video created with ffmpeg won't play in video player


code:
pat = re.compile("_(?:%s)_"%"|".join(split_list))
list(itertools.chain(pat.split(line) for line in data))

rawDescription: Splitting a string based on a certain set of words


rawDescription: Replacing things like \t\r using Python

description: Replacing things like \t\r using Python


code: [word for word in data0 if word not in (stopwords.words('english'))]

rawDescription: Stemming process not working in Python

description: Stemming process not working in Python


code:
def makeNewClass(x):
    def init(self,attribute1,attribute2):
        # make sure you call the base class constructor here
        self.attribute2 = attribute2

    globals()[x] = type(x, (MySuperClass,), {'__init__': init})

rawDescription: how to dynamically generate a subclass in a function?

description: Dynamically generate a subclass in a function


code: bgs = [i.attrs.get('href') for i in soup.select("div#rList3 a")]

rawDescription: Best way to get 'hrefs' from CSS selector in BeautifulSoup?

description: Get 'hrefs' from CSS selector in BeautifulSoup


rawDescription: Extract a row in html file without the html tags


code:
text1, text2 | text3
text4 | text5

rawDescription: How to save numpy array of Strings (with commas) to CSV?

description: Save numpy array of Strings (with commas) to CSV


code:
excluded = ('.py', '.py~')
filtered = [x for x in os.listdir('.') if not x.endswith(excluded)]

rawDescription: Python: removing multiple values from a list where using filters is more awkward


code:
import numpy as np

Nbig = 100
Nsmall = 20
big = np.arange(Nbig * Nbig).reshape([Nbig, Nbig]) # 100x100

small = big.reshape([Nsmall, Nbig/Nsmall, Nsmall, Nbig/Nsmall]).mean(3).mean(1)

rawDescription: Grouping 2D numpy array in average

description: Grouping 2D numpy array in average


code:
def sine_func(x, lam, phi, A):
    return A * np.sin(2*np.pi*x/lam + phi)

rawDescription: Python matplotlib sine function with some fixed points


code: arr.reshape(rows//3, 3, cols//3, 3).sum(axis=(1, 3)) / 9

rawDescription: Summing each 3x3 window of a M*N matrix, into a M/3*N/3 matrix with numpy


rawDescription: Join two timelines / list of tuples

description: Join two timelines / list of tuples


rawDescription: How do I read a file to a list in python?

description: Read a file to a list in python


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import matplotlib as mpl

DATA = np.random.rand(5,5)

cmap = plt.cm.jet

cNorm  = colors.Normalize(vmin=np.min(DATA[:,4]), vmax=np.max(DATA[:,4]))

scalarMap = cmx.ScalarMappable(norm=cNorm,cmap=cmap)

fig = plt.figure()
ax  = fig.add_axes([0.1, 0.1, 0.7, 0.85]) # [left, bottom, width, height]
axc = fig.add_axes([0.85, 0.10, 0.05, 0.85])

for idx in range(0,len(DATA[:,1])):
    colorVal = scalarMap.to_rgba(DATA[idx,4])
    ax.arrow(DATA[idx,0],  # x1
             DATA[idx,1],  # y1
             DATA[idx,2]-DATA[idx,0], # x2 - x1
             DATA[idx,3]-DATA[idx,1], # y2 - y1
             color=colorVal)

cb1 = mpl.colorbar.ColorbarBase(axc, cmap=cmap,
                                norm=cNorm,orientation='vertical')

plt.show()

rawDescription: Plotting arrows with different color in matplotlib


code: return r.text

rawDescription: Flask show return data on request

description: Flask show return data on request


code:
with open('command.fort.13', 'wb') as outFile:
    with open('command.info', 'rb') as com, open('fort.13', 'rb') as fort13:
        outFile.write(com.read())
        outFile.write(fort13.read())

rawDescription: Reproduce the unix cat command in python


code:
import fnmatch

def my_function(name, types):
    result = []
    for t in types:
        pattern = "{}*{}.fits".format(name, t)
        for filename in fnmatch.filter(listdir(target), pattern):
            result.append(filename)
    return result

rawDescription: looping through specific files in python

description: Looping through specific files in python


code:
def evaluate(size):
    degs = [1]*size
    inVs = list(xrange(1, size, size/25))
    outVs = list(xrange(5, size, size/25))
    where = numpy.hstack((inVs, outVs)).astype(int)
    start_time = time.time()
    A = scipy.sparse.csc_matrix((size, size))
    M = scipy.sparse.diags([degs], [0]) - A
    csr_rows_set_nz_to_val(M, where)
    return time.time()-start_time

rawDescription: What is most efficient way of setting row to zeros for a sparse scipy matrix?


code:
from Bio import Phylo
newick_path = os.path.join(root_dir, '{}.dnd'.format(filename))
tree = Phylo.read(newick_path, "newick")
Phylo.draw_ascii(tree)

rawDescription: Create a Dendogram from Genome

description: Create a Dendogram from Genome


rawDescription: Efficient algorithm for expanding grouped tabular data


code:
from collections import Counter
cnt = Counter("asbdasdbasdbadaasasdasadsa")
{k:v for k,v in cnt.iteritems() if v > 5}

rawDescription: removing least common elements from Counter

description: Removing least common elements from Counter


code:
d = dict()
for s in mastertup:
    str_list = s.split(',')
    d[str_list[0]] = ','.join(str_list[1:])

# Test
inputstring = '0101AA'
inputstring = d.get(inputstring, inputstring)  # if inputstring not in d, not mapping
print(inputstring)
# Output
MTS,DL

rawDescription: unable to iterate tuple in python 2.7

description: Unable to iterate tuple in python 2.7


code:
files = {}
for filename in os.listdir():
  file_contents = open(filename, 'r').read()
  files[filename] = file_contents

rawDescription: How to loop the files in a directory, and set variables named after the files?

description: Loop the files in a directory, and set variables named after the files


code: s = {lines[i]:[float(k) for k in lines[i+1:i+4]] for i in range(0,len(lines),4)}

rawDescription: Select and sort integers/strings from a text file in Python


code:
from jsonpath_rw import jsonpath, parse

data = {"dogs":[{"tail": True, "properties":{"test":1}}]}

jsonpath_expr = parse("dogs.[0].properties")
jsonpath_expr.find(data)[0].value['test'] = 2
print(data)

rawDescription: Modify an element in a nested dict given a "path" to it


rawDescription: Calculating the gap between pairs of twin primes in python


code:
import bisect

def index_range(n, lst):
    return (bisect.bisect_left(lst, n), bisect.bisect_right(lst, n))

def final_output(rng, lst):
    return [index_range(n, lst) for n in rng]

values = [0,0,1,1,1,1,1,2,2,2,3,3,3,3,3,3,4,4,4,5,5,5,5]
print(final_output(range(0,6), values))

rawDescription: Get the list index range of a list depending on the values


code: the_4th_line = linecache.getline('myfile.txt', 4)

rawDescription: How to read one particular line from .txt file in python?

description: Read one particular line from .txt file in python


rawDescription: How to limit the list comprehension from repeating when inside a loop?

description: Limit the list comprehension from repeating when inside a loop


code:
import collections
with open('path/to/file') as f:
    counts = collections.Counter(f)
    outfile = open('path/to/outfile', 'w')
    for line,occ in counts.iteritems():
        outfile.write("%s repeat %d\n" %(line.strip(), occ))
    outfile.close()

rawDescription: Count lines in a file

description: Count lines in a file


code:
from BeautifulSoup import BeautifulSoup
from pprint import pprint

def parseList(tag):
    if tag.name == 'ul':
        return [parseList(item)
                for item in tag.findAll('li', recursive=False)]
    elif tag.name == 'li':
        if tag.ul is None:
            return tag.text
        else:
            return (tag.contents[0].string.strip(), parseList(tag.ul))

soup = BeautifulSoup(lista)
pprint(parseList(soup.ul))

rawDescription: How to turn a Html nested list into a Python's one

description: Turn a Html nested list into a Python's one


rawDescription: Numerical Differenciation as Matrix-Vector Product


code:
test_array
test_array.item()

rawDescription: get a dict out of an ndarray

description: Get a dict out of an ndarray


code:
words = ['Hello', 'hello', 'world', 'world', 'poland', 'Poland', ]
wordset = set(words)
[item for item in wordset if item.istitle() or item.title() not in wordset]

rawDescription: How to eliminate duplicate list entries in Python while preserving case-sensitivity?

description: Eliminate duplicate list entries in Python while preserving case-sensitivity


code:
from datetime import date, timedelta
l = [date(1976, 8, 4), date(2005, 8, 8), ...] # values_list(flat=True)
today = date.today()
average_age = sum((today - x for x in l), timedelta(0)) / len(l)

rawDescription: Calculating average age in Python

description: Calculating average age in Python


code:
state = State()
print(state.apply('rate'))
print(state.apply('wage'))
print(state.apply('wage'))

rawDescription: Access class variables with same function


rawDescription: get data from server using ajax and put it in a datatable

description: Get data from server using ajax and put it in a datatable


code:
def _get_modules_from_db(dictionary):
    for k, v in dictionary.items():
        if isinstance(v, Mapping) and v.keys() != {'path_to_file', 'sha512sum'}:
            yield from _get_modules_from_db(v)
        else:
            yield v

rawDescription: Recursive function in Python: Best way to get a list of specific nested items


code:
tuples = [(1,2), (3,4), (5,6)]
[item for t in tuples for item in t]

rawDescription: pythonic way to explode a list of tuples

description: Pythonic way to explode a list of tuples


code:
negative = ((bits >> 63) & 1)    # Integer 1 for negative, 0 for positive
exponent = ((bits >> 52) & 0x7FF) - 1023
mantissa = bits & 0xFFFFFFFFFFFFF

rawDescription: Float to Real48

description: Float to Real48


code:
import pandas as pd

tmp= pd.DataFrame({
'A': pd.Series([1,2,3,4,5,6,7,8,9,10], index=range(0,10)),
'B': pd.Series([3,4,1,33,10,9,7,3,10,10], index=range(0,10))
} )

tmp = pd.concat([tmp]*10000).reset_index(drop=True)
t1 = tmp.copy()

print (tmp[tmp.eq(tmp.max(axis=1), axis=0)])

def top(row):
    data = row.tolist()
    return [d if d == max(data) else None for d in data]

def gh(tmp1):
    return tmp1.apply(top, axis=1)

print (gh(t1))

rawDescription: Python: Replace dataframe values row by row


rawDescription: Django: Detect unused templates

description: Django: Detect unused templates


code:
labels[0]
coords[0]

rawDescription: How to group elements of a numpy array with the same value in separate numpy arrays

description: Group elements of a numpy array with the same value in separate numpy arrays


code:
if __name__ == "__main__":
    import sys
    print(sys.argv)

rawDescription: Pycharm and sys.argv arguments

description: Pycharm and sys.argv arguments


code:
import numpy as np

def profile1(seed=0):
    gen = np.random.RandomState(seed)
    baseArray = np.zeros(1000000)
    for i in range(1000):
        baseArray= np.roll(baseArray,1)
        otherArray= gen.rand(1000000)
        baseArray=baseArray+otherArray
    return baseArray

def profile2(seed=0):
    gen = np.random.RandomState(seed)
    baseArray = np.zeros(1000000)
    for i in range(1000):
        otherArray = gen.rand(1000000)
        tmp1 = baseArray[:-1]               # view of the first n-1 elements
        tmp2 = baseArray[-1]                # copy of the last element
        baseArray[1:]=tmp1+otherArray[1:]   # write the last n-1 elements
        baseArray[0]=tmp2+otherArray[0]     # write the first element
    return baseArray

rawDescription: Alternative to numpy roll without copying array


code: result = sum(e.calculate_result(i).real for e in element_list for i in xrange(10000))

rawDescription: Container list in Python: standard list vs numpy array


code:
from timeit import Timer
N = 1000

d = {i:i for i in range(10000)}

def f1():
    for k in d: pass

def f2():
    for k in d.iterkeys(): pass

def f3():
    for v in d.itervalues(): pass

def f4():
    for t in d.iteritems(): pass

print(Timer(stmt='f1()', setup='from __main__ import f1').timeit(number=N))
print(Timer(stmt='f2()', setup='from __main__ import f2').timeit(number=N))
print(Timer(stmt='f3()', setup='from __main__ import f3').timeit(number=N))
print(Timer(stmt='f4()', setup='from __main__ import f4').timeit(number=N))

rawDescription: Understanding performance difference

description: Understanding performance difference


code:
class UniqueConstraint(db.Model):
    @classmethod
    def check(cls, model, **values):
        # Create a pseudo-key for use as an entity group.
        parent = db.Key.from_path(model.kind(), 'unique-values')

        # Build a list of key names to test.
        key_names = []
        for key in values:
            key_names.append('%s:%s' % (key, values[key]))

        def txn():
            result = cls.get_by_key_name(key_names, parent)
            for test in result:
                if test: return False
            for key_name in key_names:
                uc = cls(key_name=key_name, parent=parent)
                uc.put()
            return True

        return db.run_in_transaction(txn)

rawDescription: How do I define a unique property for a Model in Google App Engine?

description: Define a unique property for a Model in Google App Engine


code:
REST_FRAMEWORK = {
    'DEFAULT_METADATA_CLASS': 'my.customize.MyMetadata'
}

rawDescription: Django REST serializer and extra attributes from custom model fields


code:
l = ['first', 'second']
df
df.appl
df.applymap(lambda v: True if v in l else False)

rawDescription: Pandas - Select rows of a dataframe that contains a certain regex in ANY column


code:
def authenticated(handler):
    """
        Decorator for checking if there's a user associated with the current session.
        Will also fail if there's no session present.
    """
    def check_login(self, *args, **kwargs):
        if not self.is_logged_in():
           self.response.write('not logged in')
           return self.error(403)
        else:
           return handler(self, *args, **kwargs)
    return check_login

rawDescription: How to implement a 'before' hook that can output an alternative response?

description: Implement a 'before' hook that can output an alternative response


code:
def create_user(username=None, password=None, email=None, is_superuser=False):
    if username is None:
        username = "user%d" % Static.user_count
        while User.objects.filter(username=username).count() != 0:
            Static.user_count += 1
            username = "user%d" % Static.user_count
    if password is None:
        password = "password"
    if email is None:
        email="user%d@test.com" % Static.user_count

    Static.user_count += 1
    user = User.objects.create_user(username=username, password=password)
    #                   ^^^^^^^^^^^
    user.is_superuser = is_superuser
    user.save()
    return user # <---

rawDescription: Django test client does not log in

description: Django test client does not log in


code:
import  csv
Class_Scores = [['James', 1],['Frank', 2],['Mark', 3]]
with open('Class One Scores.csv','w') as file:
    wr = csv.writer(file,delimiter=",")
    wr.writerows(Class_Scores)

rawDescription: I want to write the 'Class_Scores' to a csv file in rows(Name on one side score on the other), how do I do that?


code: del grid_dict[(x, y)]

rawDescription: Is there something in python i can use to represent any positive whole number


code:
for month in ["January", "February", "March"]:
    print(input("How much snow fell during the month of %s" % month))

rawDescription: Implementation of functions

description: Implementation of functions


code:
def get_face(M, dim, front_side):
    if front_side:
        side = 0
    else:
        side = -1
    index = tuple(side if i == dim else slice(None) for i in range(M.ndim))
    return M[index]

rawDescription: Selecting (n-1)D array from (n)D array in numpy


rawDescription: parsing a python string with floats and ints

description: Parsing a python string with floats and ints


code:
import argparse
import randomized_vigenere as rv

def main():

    #Parse parameters
    parser = argparse.ArgumentParser()
    parser.add_argument("-m", "--mode", dest="mode", default = "encrypt", help="Encrypt or Decrypt")
    parser.add_argument("-i", "--inputfile", dest="inputFile", default = "inputFile.txt", help="Input Name")
    parser.add_argument("-o", "--outputfile", dest="outputFile", default = "outputFile.txt", help="Output Name")
    parser.add_argument("-s", "--seed", dest="seed", default =7487383487438734, help="Integer seed")
    args = parser.parse_args()

    #Set seed and generate keyword
    seed = args.seed

    #Construct Matrix
    f = open(args.inputFile,'r')
    message = f.read()
    Matrix = rv.Vigenere(seed)
    Matrix.setMessage(message)

    if(args.mode == 'encrypt'):
        Matrix.encrypt()
    else:
        Matrix.decrypt()

    o = open(args.outputFile,'w')
    o.write(str(Matrix.ciphertext))

    print("Seed used:",Matrix.seed)
    print("Key Generated:",Matrix.keyWord)
    print("Original Message:",Matrix.message)
    print("Decoded Message:",Matrix.ciphertext)

if __name__ == '__main__':
    main()

rawDescription: Randomized Vigenere Cipher with Python

description: Randomized Vigenere Cipher with Python


code:
userList = []

def main():
    inputList = int(input("Enter a number >= 0. Enter -1 to end input: "))
    while inputList != -1:
        userList.append(inputList)
        inputList = eval(input("Enter a number >= 0. Enter -1 to end input: "))

    return extractList(userList)

def extractList(userList):
    loc = int(input("Enter a starting location: "))
    length = int(input("Enter a lenghth: "))

    selSlice = userList[loc:loc + length]

    if len(selSlice) == 1:
        return selSlice[0]
    if len(selSlice) == 0:
        return 0

    num = sorted(selSlice)[-2]

    print("Second highest value in ", selSlice, "is ", num)

main()

rawDescription: List slicing and finding second highest value python


code:
A().details
A.__old_init = A.__init__
A.__init__ = lambda self, details='test': self.__old_init(details)
A().details

rawDescription: Mocking class constructor default parameters in Python


code:
def callback(t_start, text):
    def inner():
        t_start.insert(INSERT, text)
    return inner # Return the function

listbox.bind("<Return>", callback(t_start, listbox.get(ACTIVE)) )
#                        ^----this call returns a function----^
#                        Be aware that     ^--this parameter-^ is
#                        still evaluated when the interpreter
#                        evaluates the statement

rawDescription: Function called by the control flow, not by tkinter bind


rawDescription: Using Fibonacci Program to Sum Even Elements


code: {RANKS[v]: k for v, k in enumerate(VALUES)}

rawDescription: Sort Python list by dict key,value

description: Sort Python list by dict key,value


rawDescription: Python: How does inheritance of __slots__ in subclasses actually work?


code:
def sequify(type_arg=1):
    def wrapper(func):
        def wrapped(*args, **kwargs):
            it = func(f, seq)
            try:
                len(args[type_arg])
            except:
                return it
            else:
                return type(seq)(it)
        return wrapped
    return wrapper

rawDescription: `map`-like function preserving sequence-type


code:
d = os.dup(f.fileno())
os.lseek(d, 0, 0)
b1 = os.read(d, 1)
b2 = os.read(d, 1)
os.close(d)

rawDescription: Read first bytes of open file in Python

description: Read first bytes of open file in Python


code:
from sys import stdout

with open('file') as f:
    for n,line in enumerate(f):
        if line.startswith('###'):
            stdout.write(('' if not n else '\n')+line.strip('#\n'))
        else:
            stdout.write('\t'+line)

rawDescription: Split a single column into two

description: Split a single column into two


code: x.loc[index1, 3]

rawDescription: Editing values in a pandas dataframe using data from another part of the dataframe


rawDescription: How to print integers as hex strings using json.dumps() in Python

description: Print integers as hex strings using json.dumps() in Python


code:
def draw_circle(win, c=None):
    x=random.randint(0,450)
    y=random.randint(0,450)

    if c is None:
        centa=Point(x,y)
        c = Circle(centa,50)
        c.setFill(color_rgb(200,0,0))
        c.draw(win)
    else:
        p1 = c.p1
        x_dif = (p1.x - x) * -1
        y_dif = (p1.y - y) * -1
        c.move(x_dif, y_dif)
    return (c, x, y)

rawDescription: Circle Clicking game simple python

description: Circle Clicking game simple python


code:
import matplotlib.pyplot as plt

for road in atlas:
    path = [nodesdict[i] for i in road]
    lons, lats = zip(*path)
    plt.plot(lons, lats)

plt.grid()
plt.axis('equal')
plt.show()

rawDescription: Finding connectedness from a list of nodes and a list of edges


rawDescription: Use a variable string to name another variable (Python)


rawDescription: Django self-referential foreign key

description: Django self-referential foreign key


rawDescription: PYTHON: Searching two files for common lines and collecting their contents into set


code: sum(a.lower() in b.lower() for a in ListA for b in ListB)

rawDescription: Given two lists of strings, find the total number of strings in the second list which contains any string in the first list as substring


rawDescription: Convert UTF-8 as string of binary 0 and 1s to code point


code:
window = Tkinter.Tk()
ent1var = Tkinter.StringVar()
ent1 = Tkinter.Entry(window, textvarible=ent1var)
ent1.pack()

rawDescription: How to save entry field values to disk in Tkinter?

description: Save entry field values to disk in Tkinter


rawDescription: What is right way to use cyrillic in python lxml library


rawDescription: Set the name of dictionary in Python

description: Set the name of dictionary in Python


code:
todefine = [AbcClass, ...]
for base in todefine:
    name = "My" + base.__name__
    globals()[name] = type(name, (MyMixin, base), {})

rawDescription: Defining same method override on lots of classes: DRY?


code:
#!python
from ctypes import *

class nestedStru(Structure):
    _fields_ = [
      ("One", c_int),
      ("Two", c_int)
    ]

class mainStru(Structure):
    _fields_ = [
      ("First", c_int),
      ("Poniter", POINTER(nestedStru))
    ]

if __name__ == '__main__':
    obj = mainStru()
    obj.First = 0
    obj.Poniter = (nestedStru * 3)((1, 11), (2, 22), (3, 33))

    func = CDLL('./lib.dll').func
    func.argtypes = [POINTER(mainStru), c_size_t]
    func.restype = None

    func(obj, 3)

rawDescription: ctypes structure arrays in python

description: Ctypes structure arrays in python


code:
def foo(a, b, c=3, d=4, *args, **kwargs):
    e = 5
    f = 6
    g = 7
    for var in foo.__code__.co_varnames:
        print(var, locals()[var])

rawDescription: Retrieve locals() in order of variable declaration - python


code:
from PIL import Image
def image_watermark(request,image_id):
    photo = Photo.objects.get(pk=image_id)

    # Only need to watermark when there's no watermark
    if not photo.watermarked_photo.name:
        photo.watermarked_photo.name = 'watermarked_' + photo.photo.name
        watermark = Image.open('{0}/{1}'.format(settings.MEDIA_ROOT,'wmark.png'))
        img = Image.open(photo.photo.file)
        img.paste(watermark,(img.size[0]-watermark.size[0],img.size[1]- watermark.size[1]),watermark)
        img.save('{0}/{1}'.format(settings.MEDIA_ROOT, photo.watermarked_photo.name), quality=80)
        photo.save()

    wrapper = FileWrapper(open(photo.watermarked_photo.url, 'rb'))
    response = StreamingHttpResponse(wrapper, 'image/jpeg')
    response['Content-Disposition'] = 'attachment; filename=photo.jpg'
    return response

rawDescription: Saving Image in a temporary file in django


rawDescription: How to extract an element's content in HTML?

description: Extract an element's content in HTML


code: dec = str(dec) #Please note this converts to  a string type.

rawDescription: Django modelfield, how do I get the actual value?


code:
class Foo(object):
    @staticmethod
    def duck():
       return 'Quak!'
    @staticmethod
    def person():
       return 'Hello'
a = Foo()
def say_something(thing):
    return getattr(a, thing, None)
print(say_something('duck')())
print(say_something('person')())

rawDescription: How to iterate over class methods

description: Iterate over class methods


rawDescription: Numpy append ones to matrix

description: Numpy append ones to matrix


code:
def f(objects):
    return [("string_x" if isinstance(x[1], list) else "string_y", x[1])
            for x in objects]

rawDescription: python optimize function without looping

description: Python optimize function without looping


code: t1.bind(text=lambda inst, txt: t2.setter('text')(inst, sp_it(txt)))

rawDescription: Bind two TexInput in Kivy through a function


code:
def foo():
    from foo import *

rawDescription: Python import lib analogue to "import * from XXX"


code: len(dict_test) + sum(len(v) for v in dict_test.itervalues() if isinstance(v, dict))

rawDescription: Get the number of all keys in a dictionary of dictionaries in Python


code:
import os
os.environ['COLUMNS'] = "40"

rawDescription: Python argparse.RawTextHelpFormatter with line wrap


code: """%(name)s went to the store.""" % dict(name="John")

rawDescription: Passing kwargs into a python string for rendering rather then using %s/%d...etc


code: command --feature

rawDescription: parsing boolean values with argparse

description: Parsing boolean values with argparse


code:
WRITE = [0x00, 0xD6]
STARTMSB = [0x00] #change to where on the card you would like to write
STARTLSB = [0x00] #same here
MEM_L = [0x01]
DATA = [0x01]

cardservice.connection.connect()
apdu = READ + STARTMSB + STARTLSB + MEM_L + DATA
response1, sw1, sw2 = self.cardservice.connection.transmit( apdu )

rawDescription: How to write smart card with pyscard

description: Write smart card with pyscard


code:
one_rec_per_provider = grouped[cols].sum()
provider_means_over_cols = one_rec_per_provider.mean(axis=1)

rawDescription: Performing multiple calculations on a Python Pandas group from CSV data


rawDescription: Plot multiple y-axis AND colorbar in matplotlib


code:
def cap_sentence(y):
    cap_sentence.caps = "on"

    def func(x):
        if cap_sentence.caps == "on":
            cap_sentence.caps = "off"
            return x.capitalize()
        elif "." in x:
            cap_sentence.caps = "on"

    return tuple(map(func, y))

rawDescription: Changing the local variable of a function from within another function that is defined in said function.. Python


code:
doc = '''<Response>
    <exitCode>1</exitCode>
    <fileName>C:/Something/</fileName>
    <errors>
        <error>Error generating report</error>
    </errors>
</Response>'''

from xml.dom import minidom

something = minidom.parseString( doc )

nodeList = [ ]
for node in something.getElementsByTagName( "Response" ):
    response = { }
    response[ "exit code" ] = node.getElementsByTagName( "exitCode" )[ 0 ].childNodes[ 0 ].nodeValue
    response[ "file name" ] = node.getElementsByTagName( "fileName" )[ 0 ].childNodes[ 0 ].nodeValue
    errors = node.getElementsByTagName( "errors" )[ 0 ].getElementsByTagName( "error" )
    response[ "errors" ] = [ error.childNodes[ 0 ].nodeValue for error in errors ]

    nodeList.append( response )

import pprint
pprint.pprint( nodeList )

rawDescription: Trying to parse an XML file with Python - what am I doing wrong?


code:
# data_miner.py
import pickle

animals = ['Chicken', 'Sheep', 'Cattle', 'Horse']
population = [150, 200, 50, 30]

with open('data_miner.pik', 'wb') as f:
  pickle.dump([animals, population], f, -1)

rawDescription: How do I store then retrieve Python-native data structures into and from a file?

description: Store then retrieve Python-native data structures into and from a file


code:
replaceFunc = multiple_replacer(*replacements) #constructs the function. Do this outside the loop, after the replacements have been gathered.
myString = replaceFunc(myString)

rawDescription: Optimizing excel data collection/reduction using xlrd/xlwt and loop iteration


rawDescription: Perl Regex issue via Python Script

description: Perl Regex issue via Python Script


code:
dx, dy = x.T
tx, ty = t.T
(dx[:, None] - tx)**2 + (dy[:, None] - ty)**2

rawDescription: Optimisation of a simple vector operation (python)


code: for child in self.display_frame.winfo_children(): child.destroy()

rawDescription: TkInter Python: Destroyed widget still shows and covers new widget


rawDescription: Reshaping pandas dataframe, converting values of an existing column into new lower level columns with index ignored


code:
#! /usr/bin/python3

class Tree:
    def __init__ (self, tokens):
        self.children = []
        while tokens:
            self.children.append ( (tokens [1], float (tokens [0] ) ) )
            tokens = tokens [2:]

    def __repr__ (self):
        return '<{}>'.format (self.children)

    def pprint (self, indent = 0):
        prefix = '  ' * indent
        for child, dist in self.children:
            if isinstance (child, Tree):
                print (prefix, dist)
                child.pprint (indent + 1)
            else:
                print (prefix, child, dist)

    def collapse (self, limit):
        self.children = [ (child.collapse (limit) [0], dist)
            if isinstance (child, Tree)
            else (child, dist) for child, dist in self.children]
        avg = sum (dist for _, dist in self.children) / len (self.children)
        if avg > limit:
            return (self, 0)
        else:
            if any (isinstance (child, Tree) for child in self.children):
                print ('Would like to collapse, but cannot, as at least one child is a tree.')
                return (self, 0)
            return (''.join (child for child, _ in self.children), 0)

def parse (tree):
    stack = []
    buff = ''
    while True:
        c = tree [0]
        if c == ';': break
        tree = tree [1:]
        if c == '(':
            stack.insert (0, '(')
            continue
        if c == ')':
            if buff: stack.insert (0, buff)
            buff = ''
            popped = ''
            tokens = []
            while True:
                token = stack [0]
                stack = stack [1:]
                if token == '(': break
                tokens.append (token)
            stack.insert (0, Tree (tokens) )
            continue
        if c in ':,':
            if buff: stack.insert (0, buff)
            buff = ''
            continue
        buff += c
    if buff: stack.insert (0, buff)
    return Tree (stack)

t = parse ('(A:0.556705,(B:0.251059,C:0.251059):0.305646):0.556705;')
t.pprint ()
t.collapse (.3)
print ()
t.pprint ()

rawDescription: Collapse sub-trees in a tree with average distance to tips < x


code:
category_dispatch = {}
for cat, dispatch in categories:
    category_dispatch.update(dict.fromkeys(cat.keys(), dispatch))

rawDescription: Best practices for Python if-elif-elif-elif when dispatching requests


code: contours, hierarchy = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

rawDescription: How to find the shape of an object in an image using python

description: Find the shape of an object in an image using python


code:
def normalize(a):
    a -= a.min(1, keepdims=True).min(2, keepdims=True)
    a /= a.max(1, keepdims=True).max(2, keepdims=True)
    return a

rawDescription: Numpy normalization code is strangely slow


code:
import urllib2
import csv

u = urllib2.urlopen('http://www.ndbc.noaa.gov/data/dart_deployment_realtime/23228.dart')
r = csv.reader(r, delimiter=' ')

# skip the headers
for _ in range(3):
    next(r, None)

rawDescription: How to read Deep-ocean Assessment and Reporting of Tsunamis (DART®) data in python

description: Read Deep-ocean Assessment and Reporting of Tsunamis (DART®) data in python


code:
s1 = '{"priority":"HIGH", "titles":["Brand", "Likes"], values:[["addidas", 130],["nike", 180]]}'

s2 = '{"priority":"HIGH", "titles":["Brand", "Likes"], values:[["iphone", 49],["ipod", 590]]}'

rawDescription: Python - convert strings into json and combine


code:
import subprocess
import re
import math
from optparse import OptionParser

length_regexp = 'Duration: (\d{2}):(\d{2}):(\d{2})\.\d+,'
re_length = re.compile(length_regexp)

def main():

    (filename, split_length) = parse_options()
    if split_length <= 0:
        print("Split length can't be 0")
        raise SystemExit

    output = subprocess.Popen("ffmpeg -i '"+filename+"' 2>&1 | grep 'Duration'",
                            stdout = subprocess.PIPE
                            ).stdout.read()
    print(output)
    matches = re_length.search(output)
    if matches:
        video_length = int(matches.group(1)) * 3600 + \
                        int(matches.group(2)) * 60 + \
                        int(matches.group(3))
        print("Video length in seconds: " + str(video_length))
    else:
        print("Can't determine video length.")
        raise SystemExit

    split_count = math.ceil(video_length/float(split_length))
    if  split_count == 1:
        print("Video length is less then the target split length.")
        raise SystemExit

    split_cmd = "ffmpeg -i '"+filename+"' -vcodec copy "
    for n in range(0, split_count):
        split_str = ""
        if n == 0:
            split_start = 0
        else:
            split_start = split_length * n

        split_str += " -ss "+str(split_start)+" -t "+str(split_length) + \
                    " '"+filename[:-4] + "-" + str(n) + "." + filename[-3:] + \
                    "'"
        print("About to run: " + split_cmd + split_str)
        output = subprocess.Popen(split_cmd+split_str, shell = True, stdout =
                               subprocess.PIPE).stdout.read()

def parse_options():
    parser = OptionParser()

    parser.add_option("-f", "--file",
                        dest = "filename",
                        help = "file to split, for example sample.avi",
                        type = "string",
                        action = "store"
                        )
    parser.add_option("-s", "--split-size",
                        dest = "split_size",
                        help = "split or chunk size in seconds, for example 10",
                        type = "int",
                        action = "store"
                        )
    (options, args) = parser.parse_args()

    if options.filename and options.split_size:

        return (options.filename, options.split_size)

    else:
        parser.print_help()
        raise SystemExit

if __name__ == '__main__':

    try:
        main()
    except Exception as e:
        print("Exception occured running main():")
        print(e)

rawDescription: Using Python script to cut long videos into chunks in FFMPEG


code:
for key in sorted(dict1.iterkeys(), key=lambda x: int(x)):
    writer.writerow([key] + [d[key] for d in dicts])

rawDescription: Writing multiple Python dictionaries to csv file


code:
def inpt():
    word=""
    text1("Please enter your name: ",300,400) #example asking name
    pygame.display.flip()
    done = True
    while done:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a:
                    word+=str(chr(event.key))
                if event.key == pygame.K_b:
                    word+=chr(event.key)
                if event.key == pygame.K_c:
                    word+=chr(event.key)
                if event.key == pygame.K_d:
                    word+=chr(event.key)
                if event.key == pygame.K_RETURN:
                    done=False
                #events...
    return text1(word,700,30)

rawDescription: How to get an input from user in Pygame and save it as a variable?

description: Get an input from user in Pygame and save it as a variable


code:
import Image
import numpy as np

def rgb_to_hsv(rgb):
    # Translated from source of colorsys.rgb_to_hsv
    # r,g,b should be a numpy arrays with values between 0 and 255
    # rgb_to_hsv returns an array of floats between 0.0 and 1.0.
    rgb = rgb.astype('float')
    hsv = np.zeros_like(rgb)
    # in case an RGBA array was passed, just copy the A channel
    hsv[..., 3:] = rgb[..., 3:]
    r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
    maxc = np.max(rgb[..., :3], axis=-1)
    minc = np.min(rgb[..., :3], axis=-1)
    hsv[..., 2] = maxc
    mask = maxc != minc
    hsv[mask, 1] = (maxc - minc)[mask] / maxc[mask]
    rc = np.zeros_like(r)
    gc = np.zeros_like(g)
    bc = np.zeros_like(b)
    rc[mask] = (maxc - r)[mask] / (maxc - minc)[mask]
    gc[mask] = (maxc - g)[mask] / (maxc - minc)[mask]
    bc[mask] = (maxc - b)[mask] / (maxc - minc)[mask]
    hsv[..., 0] = np.select(
        [r == maxc, g == maxc], [bc - gc, 2.0 + rc - bc], default=4.0 + gc - rc)
    hsv[..., 0] = (hsv[..., 0] / 6.0) % 1.0
    return hsv

def hsv_to_rgb(hsv):
    # Translated from source of colorsys.hsv_to_rgb
    # h,s should be a numpy arrays with values between 0.0 and 1.0
    # v should be a numpy array with values between 0.0 and 255.0
    # hsv_to_rgb returns an array of uints between 0 and 255.
    rgb = np.empty_like(hsv)
    rgb[..., 3:] = hsv[..., 3:]
    h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2]
    i = (h * 6.0).astype('uint8')
    f = (h * 6.0) - i
    p = v * (1.0 - s)
    q = v * (1.0 - s * f)
    t = v * (1.0 - s * (1.0 - f))
    i = i % 6
    conditions = [s == 0.0, i == 1, i == 2, i == 3, i == 4, i == 5]
    rgb[..., 0] = np.select(conditions, [v, q, p, p, t, v], default=v)
    rgb[..., 1] = np.select(conditions, [v, v, v, q, p, p], default=t)
    rgb[..., 2] = np.select(conditions, [v, p, t, v, v, q], default=p)
    return rgb.astype('uint8')

def shift_hue(arr,hout):
    hsv=rgb_to_hsv(arr)
    hsv[...,0]=hout
    rgb=hsv_to_rgb(hsv)
    return rgb

img = Image.open('tweeter.png').convert('RGBA')
arr = np.array(img)

if __name__=='__main__':
    green_hue = (180-78)/360.0
    red_hue = (180-180)/360.0

    new_img = Image.fromarray(shift_hue(arr,red_hue), 'RGBA')
    new_img.save('tweeter_red.png')

    new_img = Image.fromarray(shift_hue(arr,green_hue), 'RGBA')
    new_img.save('tweeter_green.png')

rawDescription: Changing image hue with Python PIL

description: Changing image hue with Python PIL


code: #!/usr/bin/env python

rawDescription: How to execute python file in linux

description: Execute python file in linux


code:
functions = [x for x in globals()["functions"]
             if  x.__code__.co_argcount == 0]

rawDescription: Exiting block of code when variable changes in python


rawDescription: Two-Dimensional structured array

description: Two-Dimensional structured array


code:
role = ...  # some role
Session.query(User).filter_by(role_id=role.role_id).all()

rawDescription: SQLAlchemy relationships, when to use which relationship?


code: derive_by_array(stc, W)

rawDescription: python symbolic summation and differentiation of a vector of parametric size

description: Python symbolic summation and differentiation of a vector of parametric size


code:
from os.path import basename
data.index = [basename(f)] * len(data)

rawDescription: Using pandas Combining/merging 2 different Excel files/sheets


code:
from functools import partial
def foo(my_num, my_string):
    print(my_num, my_string)

foo2 = partial(foo, my_string="my_string_example")
foo2(10)
foo2(30)

rawDescription: Passing SOME of the parameters to a function in python


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

def reshape1(record):
   (k1, (items, k2)) = record
   return (k2, (k1, items))

def reshape2(record):
   (k1, (items1, (k2, items2))) = record
   return (k1, k2, set(items1) & set(items2))

pairs = sc.textFile(...).map(lambda x: clean_data(...))

n = ... # Number of partitions
lookup_rdd = sc.parallelize(lookup_tbl.items()).partitionBy(n)

lookup_rdd.join(lookup_rdd.join(pairs).map(reshape1)).map(reshape2)

rawDescription: Using Large Lookup Table in Single MultiCore Machine with PySpark


code:
import csv
from collections import defaultdict

d = defaultdict(list) # keep the order
with open('in.csv', 'r') as f1, open("output.csv", "w") as out:
    r = csv.reader(f1,delimiter=",")
    header = next(r) # store header
    writer = csv.writer(out,delimiter=",")
    for row in r:
       d[row[0]].append(row)
    writer.writerow(header) # write header
    for k,v in d.items(): # write updated items
        writer.writerow(min(v,key=lambda x:float(x[2])))

rawDescription: Keep duplicated item with lowest price in csv file


code:
def keyfun(word, wordorder):
    try:
        return wordorder.index(word)
    except ValueError:
        return len(wordorder)

sorted(list1, key=lambda x: keyfun(x.split('-')[1], list2))

rawDescription: Python: How to order a list based on another list


code:
import matplotlib
matplotlib.use('TkAgg')  # this has to go before the other imports
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import Tkinter as Tk
import visa

# set up a PyVISA instrument and a list for the data
data = []
keithley = visa.instrument('GPIB0::whatever')

# make a Tkinter window
root = Tk.Tk()

# add a matplotlib figure to the Tk window
fig = Figure()
ax = fig.add_subplot(111)
canv = FigureCanvasTkAgg(fig, master=root)
canv.show()
canv.get_tk_widget().pack(fill='both', expand=True)

# a function that is called periodically by the event loop
def plot_update():
    # add a new number to the data
    data.append(keithley.ask('SCPI:COMM:AND?'))

    # replot the data in the Tk window
    ax.clear()
    ax.plot(data)
    fig.tight_layout()
    canv.draw()

    # wait a second before the next plot
    root.after(1000, plot_update)

root.after(1000, plot_update)
root.mainloop()

rawDescription: PyVisa and Printing New Data

description: PyVisa and Printing New Data


code:
from __future__ import print_function
import sys
from itertools import chain

class circ_vec(object):
    """A circular fixed vector.
    """
    # The use of slots drastically reduces memory footprint of Python classes -
    # it removes the need for a hash table for every object
    __slots__ = ['end', 'elems', 'capacity']
    # end will keep track of where the next element is to be added
    # elems holds the last X elemenst that were added
    # capacity is how many elements we will hold

    def __init__(self, capacity):
        # we only need to specify the capacity up front
        # elems is empty
        self.end = 0
        self.elems = []
        self.capacity = capacity

    def add(self, e):
        new_index = self.end
        if new_index < len(self.elems):
            self.elems[new_index] = e
        else:
            # If we haven't seen capacity # of elements yet just append
            self.elems.append(e)
        self.end = (self.end + 1) % self.capacity

    def __len__(self):
        return len(self.elems)

    # This magic method allows brace [ ] indexing
    def __getitem__(self, index):
        if index >= len(self.elems):
            print("MY RAISE")
            raise IndexError
        first = self.capacity - self.end - 1
        index = (index + first) % self.capacity
        # index = (self.end + key ) % self.capacity
        # print("LEN = ", len(self.elems))
        # print("INDEX = ", index)
        return self.elems[index]

    # This magic method allows iteration
    def __iter__(self):
        if not self.elems:
            return iter([])
        elif len(self.elems) < self.capacity:
            first = 0
        else:
            first = self.end
        # Iterate from the oldest element to the newest
        return chain( iter(self.elems[first:]), iter(self.elems[:first]) )

string_group_last_four = { k : circ_vec(4) for k in ['A', 'B'] }
with open(sys.argv[1], 'r') as f:
    string_group_context = None
    # We will manually iterate through the file.  Get an iterator using iter().
    it = iter(f)
    # As per the example, the file we're reading groups lines in twos.
    buf = circ_vec(2)
    try:
        while(True):
            line = next(it)
            buf.add(line.strip())
            # The lines beginning with 'String Group' should be recorded in case we need them later.
            if line.startswith('String Group'):
                # Here is the benefit of manual iteration.  We can call next() more than once per loop iteration.
                # Sometimes once we've read a line, we just want to immediately get the next line.
                # strip() removes whitespace and the newline characters
                buf.add(next(it).strip())
                # How exactly you will parse your lines depends on your needs. Here, I assume that the last word in
                # the current line is an identifier that we are interested in.
                string_group = line.strip().split()[-1]
                # Add the lines in the buffer to the circular vector belonging to the identifier.
                string_group_last_four[string_group].add( list(l for l in buf) )
                buf = circ_vec(2)
            # For lines beginning with 'Other Main String for', we need to
            # remember the identifier but there's no other information to
            # record.
            elif line.startswith('Other Main String for'):
                string_group_context = line.strip().split()[-1]
            # Use find() instead of startswith() because the
            # 'test1(OK) # test2(OK)' lines begin with whitespace. startswith()
            # would depend on the specific whitespace characters which could
            # be confusing.
            elif line.find('test1(OK) test2(OK)') != -1:
                print('String group' + string_group_context + ' has a test hit!')
                # Print out the test lines.
                for l in buf: print(l)
                print('Four most recent "String Group ' + string_group_context + '" lines:')
                # Use the identifier dict to get the last 4 relevant groups of lines
                for cv in string_group_last_four[string_group_context]:
                    for l in cv: print(l)
    # Manual iteration is terminated by an exception in Python.  Catch and swallow it
    except StopIteration: pass
print("Done!")

rawDescription: Tricky multiple string searching in txt file using Python


code:
a = (not (letter.lower() in word) or not(letter.lower() in guessed_letters))
not_space = letter != ' '
result = a and not_space

rawDescription: if statement syntax - different than taught

description: If statement syntax - different than taught


code: s = 'ABCD' + u''.join(unichr(ch) for ch in range(0x2713, 0x271d))

rawDescription: How to iterate a Unicode string in Python?

description: Iterate a Unicode string in Python


rawDescription: How to generate ODIN-1 in Python

description: Generate ODIN-1 in Python


code: pygame.draw.circle(self.surface, pygame.Color("black"), (self.x, self.y), self.r)

rawDescription: why I'm getting a square instead of a circle in pygame?

description: Why I'm getting a square instead of a circle in pygame


code:
__author__ = 'charlie'

in_filename = "in_file.txt"
out_filename = "out_file.txt"
delimiter = "  "

def main():

    with open(in_filename, "r") as infile:
        with open(out_filename, "w") as outfile:
            for line in infile:

                ldata = line.split(delimiter)

                ldata[4] = str(int(ldata[4]) + 15)

                outfile.write(delimiter.join(ldata))

if __name__ == "__main__":
    main()

rawDescription: Adding a number to a column with python

description: Adding a number to a column with python


code:
foo = operator.itemgetter('user__id')
foo = lambda x: x['user__id']

rawDescription: Merge/join lists of dictionaries based on a common value in Python


code:
class MyThing(object):
    _local= threading.local()
    _local.reprs= set()

    def __repr__(self):
        reprs= MyThing._local.reprs
        sid= id(self)
        if sid in reprs:
            return 'MyThing(...)'
        try:
            reprs.add(sid)
            return 'MyThing(%r)' % self.something
        finally:
            reprs.remove(sid)

rawDescription: How do I handle recursive repr()'s in Python?

description: Handle recursive repr()'s in Python


code:
l2 = []

for element in l:
    l2.append(element.name)

rawDescription: Python convert list of objects to list of one object parameters


code:
combined = reduce(DataFrame.unionAll, transformed_dfs)
exprs = [max(c).alias(c) for c in combined.columns[1:]]
result = combined.repartition(col("Key")).groupBy(col("Key")).agg(*exprs)

rawDescription: What's the most efficient way to accumulate dataframes in pyspark?


code:
num_charges = 4
charges = np.random.random_integers(-5,5,(num_charges,1,1))
charges[charges==0] = 5  # only for clarity
positions = np.random.random((2, num_charges,1,1))

y,x = np.mgrid[0:1:40j, 0:1:40j]
M,N = y.shape
xy = np.array([x,y]).reshape(2,1, M,N)
rad_dist = xy - positions
denom = np.linalg.norm(rad_dist, axis=(0))**3

elec_fields = charges * rad_dist / denom
Ex, Ey = elec_fields.sum(axis=1)

rawDescription: Most Pythonic way to plot a vector function


code:
maxuserid = 7255
result_liked = []
for i in range(maxuserid): # this loop iterates through all users files
    with open('source/to/file/user_id%d.csv' % (i+1),'r') as fin:
        for row in csv.reader(fin, delimiter='\t'):
            if int(row[2]) >= 1:
                result_liked.append(row)

rawDescription: Loop through csv rows and check for a specific value


code:
from collections import defaultdict

scores = defaultdict(list)

rawDescription: Python - Highest with alphabetical order from text file


rawDescription: Reshape for array multiplication/division in python


rawDescription: python combinators list with constraints without itertools

description: Python combinators list with constraints without itertools


code:
def getem(x):
  d = {}
  for x in x.__class__.__mro__:
    d.update(x.__dict__.get('d', ()))
  return d

x = Leaf()
getem(x)

rawDescription: How to aggregate all attributes of a hierarchy of classes?

description: Aggregate all attributes of a hierarchy of classes


code:
import re
def pyglatin3(word):
    # Get the first index of one of these: a, e, i, o, u
    start = re.search("[aeiou]", word).start()

    # Split the word
    return word[start:] + "-" + word[0:start] + "ay"

rawDescription: Python skipping my if statement

description: Python skipping my if statement


code:
from django import forms

class MyForm(forms.Form):
    current_century_field = forms.DateField(validators=[validate_current_century])

rawDescription: How to restrict user to select date between range of years in django?

description: Restrict user to select date between range of years in django


code:
import numpy as np

def hist_norm(x, bin_edges, quantiles, inplace=False):
    """
    Linearly transforms the histogram of an image such that the pixel values
    specified in `bin_edges` are mapped to the corresponding set of `quantiles`

    Arguments:
    -----------
        x: np.ndarray
            Input image; the histogram is computed over the flattened array
        bin_edges: array-like
            Pixel values; must be monotonically increasing
        quantiles: array-like
            Corresponding quantiles between 0 and 1. Must have same length as
            bin_edges, and must be monotonically increasing
        inplace: bool
            If True, x is modified in place (faster/more memory-efficient)

    Returns:
    -----------
        x_normed: np.ndarray
            The normalized array
    """

    bin_edges = np.atleast_1d(bin_edges)
    quantiles = np.atleast_1d(quantiles)

    if bin_edges.shape[0] != quantiles.shape[0]:
        raise ValueError('# bin edges does not match number of quantiles')

    if not inplace:
        x = x.copy()
    oldshape = x.shape
    pix = x.ravel()

    # get the set of unique pixel values, the corresponding indices for each
    # unique value, and the counts for each unique value
    pix_vals, bin_idx, counts = np.unique(pix, return_inverse=True,
                                          return_counts=True)

    # take the cumsum of the counts and normalize by the number of pixels to
    # get the empirical cumulative distribution function (which maps pixel
    # values to quantiles)
    ecdf = np.cumsum(counts).astype(np.float64)
    ecdf /= ecdf[-1]

    # get the current pixel value corresponding to each quantile
    curr_edges = pix_vals[ecdf.searchsorted(quantiles)]

    # how much do we need to add/subtract to map the current values to the
    # desired values for each quantile?
    diff = bin_edges - curr_edges

    # interpolate linearly across the bin edges to get the delta for each pixel
    # value within each bin
    pix_delta = np.interp(pix_vals, curr_edges, diff)

    # add these deltas to the corresponding pixel values
    pix += pix_delta[bin_idx]

    return pix.reshape(oldshape)

rawDescription: How can I transform the histograms of grayscale images to enforce a particular ratio of highlights/midtones/shadows?

description: Transform the histograms of grayscale images to enforce a particular ratio of highlights/midtones/shadows


code: out

rawDescription: Relocate zeros to the end of the last dimension in multidimensional numpy array


code:
one.many_set.clear()
one.delete()

rawDescription: How do I delete an object in a django relation (While keeping all related objects)?

description: Delete an object in a django relation (While keeping all related objects)


code:
for c in map(int, '100124'):
    c

rawDescription: Iterate over digits of number

description: Iterate over digits of number


code:
if user.is_active:
    login(request, user)
    return redirect('home')

rawDescription: Django HttpResponseRedirect vs render_to_response - how to get a login form to behave the way I need it to


code: return doc

rawDescription: Python unittest, how to display TestCase's methods' docstring in report?


rawDescription: Remove all occurrences of several chars from a string


code: [[y[0] for y  in lst].count(z) for z in sorted(set([t[0] for t in lst]))]

rawDescription: Running through a list of tuples

description: Running through a list of tuples


code:
import re
assert re.findall('[^/]+', '/abra/1234fd/kadabra/2314') == ['abra', '1234fd', 'kadabra', '2314']
assert re.findall('[^/]+', '/abra/1234fd/kadabra') == ['abra', '1234fd', 'kadabra']
assert re.findall('[^/]+', '/abra/1234fd') == ['abra', '1234fd']

rawDescription: Regex for capturing URL path in groups separated by a forward slash


code:
p0, p1, p2 = Point(0, 0), Point(1, 1), Point(2, 2)
seg0 = Segment(p0, p1)
seg1 = Segment(p0, p2)
seg0.p0.x = 6

rawDescription: Setting the property of a property

description: Setting the property of a property


code: s = 'Hello. ' + str(var)

rawDescription: Python print_r which returns value instead of printing it


code:
def f(group):
    v = group['v']
    group['v2'] = (v - v.min()) / (v.max() - v.min())
    return group

rawDescription: Calculate within categories: Equivalent of R's ddply in Python?


code: df.sort(["L1", "L3"], ascending=[True, False])

rawDescription: New cumulative value col derived from existing col in a Pandas dataframe


code:
list(filter(None,
    re.split(r'(month|year|day|hour|minute|second|[^\w\s]+)', text)
))

rawDescription: parsing dates and times

description: Parsing dates and times


code:
scipy.sparse.dok_matrix.__array__ = scipy.sparse.dok_matrix.toarray
a[:] = s

rawDescription: How to assign scipy.sparse matrix to NumPy array via indexing?

description: Assign scipy.sparse matrix to NumPy array via indexing


code: bytes(array)

rawDescription: How to convert bytearray with non-ASCII bytes to string in python?

description: Convert bytearray with non-ASCII bytes to string in python


rawDescription: Hex code using Python

description: Hex code using Python


code:
# mainmodule
import sys
from PyQt5 import QtWidgets
import uifile

class App(QtWidgets.QMainWindow, uifile.Ui_MyWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.btn_clickMe.clicked.connect(self.some_function)
    def some_function(self):
        import othermodule
        othermodule.print_user()
    def input_user(self):
        user = self.lineEdit_username.text()
        return user

form = None

def main_window():
    return form

def main():
    global form
    app = QtWidgets.QApplication(sys.argv)
    form = App()
    form.show()
    app.exec_()

rawDescription: PyQt lineEdit is empty when called from another script


code:
@app.before_request
def set_domain_session():
    session['domain'] = request.headers['Host']

rawDescription: Flask: Set session cookie based on domain name


code:
prev = None
for something in an_iterator:
    # do something with prev
    prev = something

rawDescription: Is there a counterpart of next()?

description: Is there a counterpart of next()


code:
def expand_singles(item):
    if isinstance(item, list):
        if len(item) == 1:
            return expand_singles(item[0])
        return [expand_singles(i) for i in item]
    return item

rawDescription: Clean nested lists in Python

description: Clean nested lists in Python


code: oddsum - evensum == (b - a + 1) // 2

rawDescription: Efficient way to find sum of digits of an entire sequence


code:
#!/usr/bin/env python2
# coding: utf-8
# Veni Sancte Spiritus

# This code is under public domain.

import os
import argparse
import logging
import re
import openpyxl

logging.basicConfig(
    format="[%(levelname)s]: %(message)s", level=logging.INFO)

try:
    import openpyxl
except ImportError:
    logging.error("Install openpyxl; pip install openpyxl")
    exit(1)

parser = argparse.ArgumentParser(description="get plugins used by Jenkins job")
parser.add_argument("--excel", metavar="dir/output1.xslx",
                    help="Output to excel file")

parser.add_argument("--jenkinshome", metavar="/var/lib/jenkins",
                    help="Jenkins home location (default: {})".format(
                        os.getcwd()), default=os.getcwd())

arguments = parser.parse_args()

alreadyadded = []
pluginsalreadyadded = {}

if arguments.excel:
    workbook = openpyxl.Workbook(optimized_write=True)
    worksheet1 = workbook.create_sheet(0, "Output")
    worksheet1.append(["Job name", "Jenkins-CI plugin"])
    worksheet2 = workbook.create_sheet(1, "Output grouping jobs by plugin")
    worksheet2.append(["Jobs", "Jenkins-CI plugin"])
    worksheet3 = workbook.create_sheet(2, "Plugins installed on Jenkins")
    worksheet3.append(["Plugin name", "Plugin version"])

for root, subFolders, files in os.walk(os.path.join(
        arguments.jenkinshome, "jobs")):
    if 'config.xml' in files:
        with open(os.path.join(root, 'config.xml'), 'r') as fin:
            for lines in fin:
                if 'plugin=' in lines:
                    before_keyword, keyword, after_keyword = lines.partition(
                        'plugin=')
                    jobname = os.path.basename(root)
                    plugin = re.sub(r'"(.+)@([0-9.]+)"/?>\n?',
                                    r'\1 ver. \2', after_keyword)

                    if [jobname, plugin] not in alreadyadded:
                        logging.info("{}: {}".format(jobname, plugin))

                        if arguments.excel:
                            worksheet1.append([jobname, plugin])

                            if plugin not in pluginsalreadyadded:
                                pluginsalreadyadded[plugin] = []

                            pluginsalreadyadded[plugin].append(jobname)

                        alreadyadded.append([jobname, plugin])

for root, subFolder, files in os.walk(os.path.join(
        arguments.jenkinshome, "plugins")):
    if "MANIFEST.MF" in files:
        with open(os.path.join(root, "MANIFEST.MF")) as fon:
            name = None
            version = None
            for line in fon:
                if "Extension-Name: " in line:
                    beforekyw, kyw, name = line.partition("Extension-Name: ")
                    # clean the string
                    name = re.search(r'(\w+)', name).group(0)
                elif "Plugin-Version: " in line:
                    beforekyw, kyw, version = line.partition(
                        "Plugin-Version: ")
                    version = re.sub(r'\n', '', version)
                    # clean the string
                    version = re.search(r'(.+)', version).group(0)
            logging.info("{} ver. {}".format(name, version))

            if arguments.excel:
                worksheet3.append([name, version])

if arguments.excel:
    filedest = os.path.expanduser(arguments.excel)
    filedest = os.path.abspath(filedest)
    path = os.path.dirname(filedest)
    if not os.path.isdir(path):
        os.makedirs(path)

    # write output for worksheet2
    for plugin, jobs in pluginsalreadyadded.iteritems():
        worksheet2.append([" | ".join(jobs), plugin])

    # save the file
    workbook.save(filedest)

rawDescription: get plugins used by Jenkins job

description: Get plugins used by Jenkins job


code:
lowest_dirs = list()

for root,dirs,files in os.walk(starting_directory):
    if not dirs:
        lowest_dirs.append(root)

rawDescription: Get a list of the lowest subdirectories in a tree


code:
class B(A):
    def __init__(self, value):
        super(B, self).__init__(value)

    @property
    def value(self):
        return super(B, self).value

    @value.setter
    def value(self, value):
        cls, method = who_called()
        if cls in B.__mro__ and method in A.__dict__:
            self._value = value
        else:
            raise AttributeError("can't set attribute")

rawDescription: Discriminate between callers inside and outside class hierarchy


code:
import mathutils
from math import radians

b_empty = bpy.context.scene.active_object
num_steps = 9
stepsize = 360/num_steps
for i in range(0, num_steps):
    mat_rot = mathutils.Matrix.Rotation(radians(step), 4, 'X')
    b_empty.matrix_local *= mat_rot

    print("Rotation %01d" % (radians(stepsize)))
    image = 'images/' + sys.argv[-1] + str(i) + '.' + filetype
    render_thumb(image,gl=False)

rawDescription: Blender camera rotation with python - not planar?


rawDescription: Python split a string at an underscore

description: Python split a string at an underscore


rawDescription: Some Basic Python Questions

description: Some Basic Python Questions


code:
numbers = ','.join(str(i) for i in range(number_1, number_2 + 1))
print(numbers)

rawDescription: Print user inputted number with commas and the numbers in between


code:
class AttributeBase(models.Model):
    label = models.CharField(max_length=255) # e.g. color, size, shape, etc.
    ...

class Attribute(models.Model):
    base = models.ForeignKey('AttributeBase', related_name='attributes')
    value = models.CharField(max_length=255) # e.g. red, L, round, etc.
    internal_value = models.CharField(max_length=255, null=True, blank=True) # other values you may need e.g. #ff0000, etc.
    ...

class ProductAttribute(Attribute):
    product = models.ForeignKey('Product', related_name='attributes')

rawDescription: Embed product-variance logic into Django models


code:
from tkinter import *
import sqlite3
from tkinter.ttk import Combobox,Treeview,Scrollbar

class test(Frame):
    'this runs when prgram first runs'
    def __init__(self, master):
        self.modefunction = 1
        """ Initialize the frame. """
        super(test,self).__init__(master)
        self.grid()
        self.student_input_frm = LabelFrame(self, width=100, height=30, text = "entering stdent details")
        self.student_input_frm.grid(row = 0, column = 0)
        self.clear_databse_frm = LabelFrame(self, width=100, height=30, text = "clearing database")
        self.clear_databse_frm.grid(row = 1, column = 0)
        self.score_input_frm = LabelFrame(self, width=100, height=30, text = "adding scores")
        self.score_input_frm.grid(row = 2, column = 0)
        #these forms are used to group objects ogether
        self.create_GUI()

    def create_GUI(self):
        self.create_clear_datbase()
        self.create_student_input()
        self.create_score_input()

    def create_clear_datbase(self):
        self.cleardb = StringVar()
        self.cleardb.set("clearing datbase will cause all datba to be lost")
        self.recreatedb_btn = Button(self.clear_databse_frm, text = "re create database", command = self.recreatedb)
        self.recreatedb_btn.grid(row = 0,column = 0)
        self.cleardb_message_lbl = Label(self.clear_databse_frm, textvariable = self.cleardb)
        self.cleardb_message_lbl.grid(row = 0, column = 1)

    def recreatedb(self):
        sql = """CREATE TABLE `tbl_Students` (
    `StudentID` INTEGER PRIMARY KEY AUTOINCREMENT,
    `FirstName` TEXT,
    `LastName`  TEXT
         )"""
        #this is the sql that will be run
        with sqlite3.connect("studentscores.db") as db:
            cursor = db.cursor()
            cursor.execute("select name from sqlite_master where name=?",("tbl_Students",))
            result = cursor.fetchall()
            cursor.execute("drop table if exists {0}".format("tbl_Students")) #if table exist delete it
            cursor.execute(sql)
            db.commit()

        #this is the sql that will be run
        sql = """CREATE TABLE `tbl_scores` (
    `StudentID` INTEGER,
    `DateOfScore`   INTEGER,
    `Score` INTEGER
        )"""
        with sqlite3.connect("studentscores.db") as db:
            cursor = db.cursor()
            cursor.execute("select name from sqlite_master where name=?",("tbl_scores",))
            result = cursor.fetchall()
            cursor.execute("drop table if exists {0}".format("tbl_scores"))#if table exist delete it
            cursor.execute(sql)
            db.commit()
        self.cleardb.set("database cleared")

    def create_student_input(self):
        self.student_input = StringVar()
        self.student_input.set("click add student button to add student")

        self.nfirst_name_lbl = Label(self.student_input_frm, text = "students first name:")
        self.nfirst_name_lbl.grid(row = 0,column = 0)
        self.nfirst_name_txt = Entry(self.student_input_frm)
        self.nfirst_name_txt.grid(row = 0,column = 1)

        self.nlast_name_lbl = Label(self.student_input_frm, text = "students last name:")
        self.nlast_name_lbl.grid(row = 1,column = 0)
        self.nlast_name_txt = Entry(self.student_input_frm)
        self.nlast_name_txt.grid(row = 1,column = 1)

        self.nstudent_btn = Button(self.student_input_frm, text = "enter new student", command = self.nstudent)
        self.nstudent_btn.grid(row = 0,column = 3)
        self.nstudent_message_lbl = Label(self.student_input_frm, textvariable = self.student_input)
        self.nstudent_message_lbl.grid(row = 1, column = 3)

    def nstudent(self): #adds new record to studdent table
        firstname = self.nfirst_name_txt.get()
        lastname = self.nlast_name_txt.get()
        with sqlite3.connect("studentscores.db") as db:
            cursor=db.cursor()
            sql = "insert into tbl_Students (FirstName, Lastname) values (?,?)"
            cursor.execute(sql,(firstname,lastname))
            db.commit()
            self.student_input.set("new student added")

    def create_score_input(self):
        self.first_name_lbl = Label(self.score_input_frm, text = "students first name:")
        self.first_name_lbl.grid(row = 0,column = 0)
        self.first_name_txt = Entry(self.score_input_frm)
        self.first_name_txt.grid(row = 0,column = 1)

        self.last_name_lbl = Label(self.score_input_frm, text = "students last name:")
        self.last_name_lbl.grid(row = 1,column = 0)
        self.last_name_txt = Entry(self.score_input_frm)
        self.last_name_txt.grid(row = 1,column = 1)

        self.search_students_adding_score_btn = Button(self.score_input_frm, command = lambda : self.search_students_adding_score(),text = "search students")
        self.search_students_adding_score_btn.grid(row = 2, column = 0)

        self.tree = Treeview(self.score_input_frm) #tree is good way of presenting reults froim sql
        self.tree["columns"] = ("StudentID","First Name","Last Name")
        self.tree.column("StudentID",width = 100)
        self.tree.column("First Name",width = 100)
        self.tree.column("Last Name", width = 100)
        self.tree.heading("StudentID",text="StudentID")
        self.tree.heading("First Name",text="First Name")
        self.tree.heading("Last Name",text="Last Name")
        self.tree["show"] = "headings"
        yscrollbar = Scrollbar(self.score_input_frm, orient='vertical', command=self.tree.yview)
        xscrollbar = Scrollbar(self.score_input_frm, orient='horizontal', command=self.tree.xview)
        self.tree.configure(yscroll=yscrollbar.set, xscroll=xscrollbar.set)
        yscrollbar.grid(row=3, column=4,sticky=NS)
        self.tree.grid(row=3,column=0, columnspan = 3)
        self.tree.bind("<Double-1>",lambda event :self.OnDoubleClick_input_scores(event))

    def search_students_adding_score(self):
        FirstName = self.first_name_txt.get()
        LastName = self.last_name_txt.get()
        with sqlite3.connect("studentscores.db") as db:
            cursor = db.cursor()
            cursor.row_factory = sqlite3.Row
            sql = "select StudentID,FirstName,LastName"\
                  " from tbl_Students"\
                  " where FirstName like ?"\
                  " and LastName like ?"
            cursor.execute(sql,("%"+FirstName+"%","%"+LastName+"%",))
            StudentList = cursor.fetchall() #results of sql put into this array
        self.loadStudents_inputing_score(StudentList)

    def loadStudents_inputing_score(self,StudentList):
        for i in self.tree.get_children():
            self.tree.delete(i)

        for student in StudentList:
            self.tree.insert("" , 0,values=(student[0],student[1],student[2]))

    def OnDoubleClick_input_scores(self,event):
        curItem = self.tree.focus()
        contents =(self.tree.item(curItem))
        StudentDetails = contents['values']
        self.nStudentID = int(StudentDetails[0])
        self.score_input_message = StringVar()
        self.score_input_message.set(" ")

        self.date_score_lbl = Label(self.score_input_frm, text = "date")
        self.date_score_lbl.grid(row = 4,column = 0)
        self.date_score_txt = Entry(self.score_input_frm)
        self.date_score_txt.grid(row = 4,column = 1)

        self.score_lbl = Label(self.score_input_frm, text = "score")
        self.score_lbl.grid(row = 5,column = 0)
        self.score_txt = Entry(self.score_input_frm)
        self.score_txt.grid(row = 5,column = 1)

        self.nstudent_btn = Button(self.score_input_frm, text = "enter new score for the selected student", command = self.nscore)
        self.nstudent_btn.grid(row = 6,column = 0)
        self.date_score_lbl = Label(self.score_input_frm, textvariable = self.score_input_message)
        self.date_score_lbl.grid(row = 6,column = 1)

    def nscore(self): #adds new record intop score table the student id indicates which student that score is for
        self.nDateOfScore = self.date_score_txt.get()
        self.nScore = self.score_txt.get()
        print(self.nStudentID)
        print(self.nDateOfScore)
        with sqlite3.connect("studentscores.db") as db:
            cursor=db.cursor()
            sql = "insert into tbl_scores (StudentID, DateOfScore, Score) values (?,?, ?)"
            cursor.execute(sql,(self.nStudentID,self.nDateOfScore,self.nScore))
            db.commit()
            self.score_input_message.set("new student added")

root = Tk()
root.title("booking system")
root.geometry("500x500")
root.configure(bg="white")
app = test(root)

root.mainloop()

rawDescription: Is it possible to write a python program that will enable you to sort the content of a text file in python


code:
M = np.matrix([
        [-1,-2,-3],
        [-4,-5,-6]
    ])
M[1,:] *= 2          # multiply all elements in second row by 2
M
M[:,1] *= 2          # multiply all elements in second column by 2
M

rawDescription: How to multiply a given row `i` or column `j` with a scalar?

description: Multiply a given row `i` or column `j` with a scalar


code:
array_pointer = ctypes.cast(Data, ctypes.POINTER(ArrayType))
a = np.frombuffer(array_pointer.contents)

rawDescription: How to convert pointer to c array to python array

description: Convert pointer to c array to python array


code:
import pandas as pd
import datetime as DT

df = pd.DataFrame({
    'Trader': 'Carl Mark Carl Joe Mark Carl Max Max'.split(),
    'Quantity': [5, 2, 5, 10, 1, 5, 2, 1],
    'Date': [
        DT.datetime(2013, 1, 1, 13, 0),
        DT.datetime(2013, 1, 1, 13, 5),
        DT.datetime(2013, 2, 5, 20, 0),
        DT.datetime(2013, 2, 6, 10, 0),
        DT.datetime(2013, 2, 8, 12, 0),
        DT.datetime(2013, 3, 7, 14, 0),
        DT.datetime(2013, 6, 4, 14, 0),
        DT.datetime(2013, 7, 4, 14, 0),
        ]})

df.index = [df.Date, df.Trader]
df2 = df.unstack('Trader').resample('1W', how='mean').fillna(0)
print(pd.ewma(df2, span=7))

rawDescription: Pandas: Exponential smoothing function for column


rawDescription: Python inspect module: keyword only args


code:
def takes_any_args(*args, **kwargs):
    pass

rawDescription: Python equivalent of ActionScript's apply()/call() methods?


code:
try:
    from my_package import server
except ImportError:
    from ..my_package import server

rawDescription: Scripts in python package

description: Scripts in python package


code:
for li in soup.select("#profile-experience li.position"):
    print(li.get_text())

rawDescription: Navigating DOM in BeautifulSoup

description: Navigating DOM in BeautifulSoup


code:
from itertools import compress
list_a = [1, 2, 4, 6]
fil = [True, False, True, False]
list(compress(list_a, fil))

rawDescription: Filtering a list based on a list of booleans


code:
regex = re.compile(r"""
(
    ([,(])              # boundary
    ([A-Z0-9_\-\.]+)    # label
    (:)?                # optional colon
    (\[.+?\])?          # optional comment chunk
    (\d+\.\d+)?         # optional branchlengths
    (?=[),])            # end!
)
""", re.IGNORECASE + re.VERBOSE + re.DOTALL)
regex.findall("((A:[c1]0.1,B:[c2]0.2),C:[c2]0.3);")

rawDescription: Unable to get regex to capture last group


code: probs = map(float, probs)

rawDescription: Python: separate results of re.findall

description: Python: separate results of re.findall


code:
from django.views.generic import ListView

class IndexView(ListView):
    template_name = 'xxx/ganttChart.html'
    context_object_name = 'projects'
    model = Project

    def get_queryset(self):
        return Project.objects.filter(
            pk__in=self.request.GET.get('ids','').split(','),
        ).order_by('projectName')
index = IndexView.as_view()

rawDescription: Django - Custom admin action

description: Django - Custom admin action


code:
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

rawDescription: python syntax: how to return 0 instead of False when evaluating 0

description: Python syntax: how to return 0 instead of False when evaluating 0


code:
from flask import Flask
app = Flask(__name__)

@app.route('/')
def serve_csv():
    return app.send_static_file('test.csv')

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

rawDescription: Python web app setup

description: Python web app setup


code: ls = [(key, value) for key, value in globals().items() if isinstance(value, tuple) and len(value) == 3]

rawDescription: Get all objects of a given structure, and their global names


code: subprocess.call( ["python", "file.py"] )

rawDescription: Python - Run multiple python scripts from main file


code:
def active_users():
    return User.select(lambda user: not user.disabled)

rawDescription: Writing select functions for customized Pony


code:
data_str = '''

{
    "follows": [{
        "created_at": "2016-01-15T22:43:35Z",
        "_links": {
            "self": "https://api.twitch.tv/kraken/users/user/follows/channels/syndicate"
        },
        "notifications": false,
        "channel": {
            "_links": {
                "self": "https://api.twitch.tv/kraken/channels/syndicate",
                "follows": "https://api.twitch.tv/kraken/channels/syndicate/follows",
                "commercial": "https://api.twitch.tv/kraken/channels/syndicate/commercial",
                "stream_key": "https://api.twitch.tv/kraken/channels/syndicate/stream_key",
                "chat": "https://api.twitch.tv/kraken/chat/syndicate",
                "features": "https://api.twitch.tv/kraken/channels/syndicate/features",
                "subscriptions": "https://api.twitch.tv/kraken/channels/syndicate/subscriptions",
                "editors": "https://api.twitch.tv/kraken/channels/syndicate/editors",
                "videos": "https://api.twitch.tv/kraken/channels/syndicate/videos",
                "teams": "https://api.twitch.tv/kraken/channels/syndicate/teams"
            },
            "background": null,
            "banner": null,
            "broadcaster_language": "en",
            "display_name": "Syndicate",
            "game": "Counter-Strike: Global Offensive",
            "logo": "https://static-cdn.jtvnw.net/jtv_user_pictures/syndicate-profile_image-03bf1d6ad0025f86-300x300.png",
            "mature": false,
            "status": "Road To MLG! (CS:GO Competiive) ",
            "partner": true,
            "url": "http://www.twitch.tv/syndicate",
            "video_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/syndicate-channel_offline_image-a15fc19d9828b9c7-640x360.png",
            "_id": 16764225,
            "name": "syndicate",
            "created_at": "2010-10-17T23:19:43Z",
            "updated_at": "2016-01-22T22:17:33Z",
            "delay": null,
            "followers": 2353424,
            "profile_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/syndicate-profile_banner-5f912a83f7e9bafe-480.png",
            "profile_banner_background_color": null,
            "views": 38140282,
            "language": "en"
        }
    }, {
        "created_at": "2016-01-12T21:01:49Z",
        "_links": {
            "self": "https://api.twitch.tv/kraken/users/pandaswede/follows/channels/gem28daz2012"
        },
        "notifications": false,
        "channel": {
            "_links": {
                "self": "http://api.twitch.tv/kraken/channels/gem28daz2012",
                "follows": "http://api.twitch.tv/kraken/channels/gem28daz2012/follows",
                "commercial": "http://api.twitch.tv/kraken/channels/gem28daz2012/commercial",
                "stream_key": "http://api.twitch.tv/kraken/channels/gem28daz2012/stream_key",
                "chat": "http://api.twitch.tv/kraken/chat/gem28daz2012",
                "features": "http://api.twitch.tv/kraken/channels/gem28daz2012/features",
                "subscriptions": "http://api.twitch.tv/kraken/channels/gem28daz2012/subscriptions",
                "editors": "http://api.twitch.tv/kraken/channels/gem28daz2012/editors",
                "videos": "http://api.twitch.tv/kraken/channels/gem28daz2012/videos",
                "teams": "http://api.twitch.tv/kraken/channels/gem28daz2012/teams"
            },
            "background": null,
            "banner": null,
            "broadcaster_language": null,
            "display_name": "Gem28daz2012",
            "game": "Minecraft",
            "logo": null,
            "mature": null,
            "status": "Playing minecraft",
            "partner": false,
            "url": "http://www.twitch.tv/gem28daz2012",
            "video_banner": null,
            "_id": 93338000,
            "name": "gem28daz2012",
            "created_at": "2015-06-12T19:51:58Z",
            "updated_at": "2016-01-12T21:16:07Z",
            "delay": null,
            "followers": 8,
            "profile_banner": null,
            "profile_banner_background_color": null,
            "views": 4,
            "language": "en"
        }
    }],
"_total": 2,
"_links": {
    "self": "https://api.twitch.tv/kraken/users/pandaswede/follows/channels?direction=DESC&limit=25&offset=0&sortby=created_at",
    "next": "https://api.twitch.tv/kraken/users/pandaswede/follows/channels?direction=DESC&limit=25&offset=25&sortby=created_at"
}
}

'''

import json
data = json.loads(data_str)
display_names = [f['channel']['display_name'] for f in data['follows']]
print(display_names) # ['Syndicate', 'Gem28daz2012']

rawDescription: Parsing JSON data Python

description: Parsing JSON data Python


code: 0 in multidimensional_array

rawDescription: Determine if there is at least one zero in a multidimensional numpy array


rawDescription: Keep CSV commas inside fields with Python


code:
dfs = ()
for file in myFiles:
    df = pd.read_csv(file, index_col='lang')
    dfs = dfs + tuple((df,))

rawDescription: pandas read dataframes in a loop and get the mean

description: Pandas read dataframes in a loop and get the mean


code:
from mpmath import nsum, exp, inf
nsum(lambda x: exp(-x**2), [-inf, inf])

rawDescription: How to perform infinite sum numerically in python

description: Perform infinite sum numerically in python


code:
dis.dis(a)
dis.dis(f)

rawDescription: Python: lambda function behavior with and without keyword arguments?


code:
import requests_cache

requests_cache.install_cache(
    'cache_name', backend='some_backend', expire_after=180,
    session_factory=FallbackCachedSession)

rawDescription: Does requests_cache automatically update cache on update of info?


code: tree = ET.parse('Test.xml')

rawDescription: Python: In an xml, How to delete nodes within a parent node


code:
# see python's struct documentation, this defines the format of data you want
data = struct.Struct('>i')
# this produces an object from the socket that acts more like a file
socket_file = conn.makefile()
# read the data and unpack it
# NOTE: this will fail if the connection is lost midway through the bytes
# dealing with that is left as an exercise to the reader
value, = data.unpack(socket_file.read(data.size))

rawDescription: Is int in C# and Python the same thing?

description: Is int in C# and Python the same thing


rawDescription: Issue sorting lots of files in python

description: Issue sorting lots of files in python


code:
import re
re.S
text1 = 'this is a test\n with newline'
re.sub(r']*>(.*?)', r'\1', text1, re.S)
re.sub(r']*>(.*?)', r'\1', text1, flags=re.S)

rawDescription: python re.sub non-greed substitute fails with a newline in the string

description: Python re.sub non-greed substitute fails with a newline in the string


code: f1.func is f2.func

rawDescription: How to test that functools.partial produces the expected function object

description: Test that functools.partial produces the expected function object


code:
for i, row in enumerate(BOARD):
    ...
    ...
    for j, column in enumerate(row):
        ...
        BOARD[i][j] = userInput
        ...

rawDescription: How to edit the elements of a 2d array and display the edited 2d array?

description: Edit the elements of a 2d array and display the edited 2d array


code: df['Data'].resample('5Min', how='mean')

rawDescription: averaging every five minutes data as one datapoint in pandas dataframe

description: Averaging every five minutes data as one datapoint in pandas dataframe


code: crc32('the quick brown fox')

rawDescription: Why does python's zlib.crc32 need a bitwise AND to be considered "stable"?


code:
from itertools import combinations
f = open('combinations.txt', 'w')
for comb in combinations(range(1,50), 6):
    f.write(str(comb))
    f.write('\n')
f.close()

rawDescription: Python - all lottery combinations - no duplicates, in order


rawDescription: Image analysis in R

description: Image analysis in R


code:
from time import time
import re

data = "ULFFunH8ni" # the password

def benchmark(method): # benchmark method, loops 1000000 times and prints how much it took
    start = time()
    for _ in range(1000000): method(data)
    print(time() - start)

def checkio_kasra(data): # Kasra's answer
    return len(data) >= 10 and all([any(i.isdigit() for i in data),any(i.islower() for i in data),any(i.isupper() for i in data)])

def checkio_andreysabitov(data): # Andrey Sabitov's regex-based answer
    if len(data) < 10:
        return False

    digital = re.compile('[0-9]+')
    capital = re.compile('[A-Z]+')
    lower = re.compile('[a-z]+')

    return (digital.search(data) is not None) and (capital.search(data) is not None)  and (lower.search(data) is not None)

def checkio_andredaniel(data): # My answer
    return len(data) >= 10 and any(char.isdigit() for char in data) and any(char.islower() for char in data) and any(char.isupper() for char in data)

def checkio_shashank_bitmask(data):
    if len(data) < 10: return False
    lud_bitmask = 0
    for ch in data:
        if ch.islower():
            lud_bitmask |= 4
            if lud_bitmask == 7: return True
        elif ch.isupper():
            lud_bitmask |= 2
            if lud_bitmask == 7: return True
        elif ch.isdigit():
            lud_bitmask |= 1
            if lud_bitmask == 7: return True
    return False

def checkio_shashank_pure_regex(data):
    return bool(re.match(r'(?=.*?[0-9])(?=.*?[A-Z])(?=.*?[a-z]).{10}', data))

def checkio_shashank_impure_regex(data):
    return len(data) >= 10 and re.match(r'(?=.*?[0-9])(?=.*?[A-Z])(?=.*?[a-z])', data)

benchmark(checkio_kasra)
benchmark(checkio_andreysabitov)
benchmark(checkio_andredaniel)
benchmark(checkio_shashank_bitmask)
benchmark(checkio_shashank_pure_regex)
benchmark(checkio_shashank_impure_regex)

rawDescription: python password rules validation

description: Python password rules validation


code:
BRACKETS = ("()", "[]", "{}")
def check_brackets(s):
    counter = []
    for chr in s:
        for br in BRACKETS:
            open = br[0]
            close = br[1]
            if chr == open:
                counter.append(open)
                break
            elif chr == close:
                try:
                    last_br = counter.pop()
                except IndexError:
                    return False
                if last_br != open: # ensures that the end matches the beginnig
                    return False
    return not bool(counter)

rawDescription: Find bracket which are not closed without using regex in python


code:
for key in self.bok.iterkeys():
    for subkey in key:
        w.write("{};{};\n".format(self.bok[key], subkey))
w.close()

rawDescription: Python Tuple save to file

description: Python Tuple save to file


code:
def proj11_1_a():
    n = eval(input("Enter the size of the square matrix: "))
    matrix = []
    tempArray = []

    for i in range(1, (n**2) + 1):
        val = eval(input("Enter a value to go into the matrix: "))

        if i % n == 0:
            tempArray.append(val)
            matrix.append(tempArray)
            tempArray = [] #del tempArray[:]
        else:
            tempArray.append(val)
    print(matrix)
proj11_1_a()

rawDescription: Creating a matrix using lists Python

description: Creating a matrix using lists Python


rawDescription: organizing numbers in numpy

description: Organizing numbers in numpy


code:
from urllib import request
# access request directly.
mine = request()

import urllib.request
# used as urllib.request
mine = urllib.request()

rawDescription: `from ... import` vs `import .`

description: `from ... import` vs `import .`


rawDescription: How to parse a collection of lists returned from cypher?

description: Parse a collection of lists returned from cypher


code:
def permutations(iterable, r=None):
    # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # permutations(range(3)) --> 012 021 102 120 201 210
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = range(n)
    cycles = range(n, n-r, -1)
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

rawDescription: Recursive Permutation Generator, swapping list items not working


code: res = [int(x in (1, 3)) for x in xrange(1, 4)]

rawDescription: Shortest way to write the program in Python


code:
from collections import Counter
def eliminate_duplicates(lst):
    return list(Counter(lst))

rawDescription: Inquiry about removing duplicates

description: Inquiry about removing duplicates


code:
idx = pd.Index(np.ravel(frame.values)).unique()
idx

rawDescription: Dummy variables from levels of other data frame


rawDescription: How can I remove the duplicates in a column of a 2D list and return the result as another list?

description: Remove the duplicates in a column of a 2D list and return the result as another list