code:
import threading
import time
import logging

logger=logging.getLogger(__name__)

def f(resume,is_waiting,name):
    while True:
        if not resume.is_set():
            is_waiting.set()
            logger.debug('{n} pausing...'.format(n=name))
            resume.wait()
            is_waiting.clear()
        logger.info(name)
        time.sleep(1)

def h(resume,waiters):
    while True:
        logger.debug('halt')
        resume.clear()
        for i,w in enumerate(waiters):
            logger.debug('{i}: wait for worker to pause'.format(i=i))
            w.wait()
        logger.info('h begin')
        time.sleep(2)
        logger.info('h end')
        logger.debug('resume')
        resume.set()
        time.sleep(5)

logging.basicConfig(level=logging.DEBUG,
                    format='[%(asctime)s %(threadName)s] %(message)s',
                    datefmt='%H:%M:%S')

# set means resume; clear means halt
resume = threading.Event()
resume.set()

waiters=[]
for name in 'fg':
    is_waiting=threading.Event()
    waiters.append(is_waiting)
    threading.Thread(target=f,args=(resume,is_waiting,name)).start()
threading.Thread(target=h,args=(resume,waiters)).start()

rawDescription: Pausing two Python threads while a third one does stuff (with locks?)


code:
@register.simple_tag
def foo(bar):
    return "something something " + bar

rawDescription: Own {% trans %} tag for Django

description: Own {% trans %} tag for Django


code:
from django.db import connection
sql=connection.queries

rawDescription: customize django runserver output

description: Customize django runserver output


rawDescription: value counts of a Database chunk by chunk using pandas

description: Value counts of a Database chunk by chunk using pandas


code:
def padZeros(x):
    return str(x).zfill(8)

df = pd.read_csv(path, sep='\s+', dtype = {'constype': str,
                     'delta': np.float16}, parse_dates=[1],
                     converters={'caseid':padZeros,
                                 'consid':padZeros,
                                 'employid':padZeros})

rawDescription: How to properly read csv with dates and omitted leading zeros in pandas?

description: Properly read csv with dates and omitted leading zeros in pandas


code:
import unicodecsv
import os
import codecs

with open('test.csv') as infile, \
     codecs.open('test-write.csv', 'w', 'utf-8') as outfile:

    reader = unicodecsv.DictReader(infile)
    fieldnames = 'Indv,AttrName,AttrValue,Start,End'.split(',')
    writer = unicodecsv.DictWriter(outfile, fieldnames)
    writer.writeheader()
    for row in reader:
        email = row['email']
        trait1, trait2, trait3 = row['trait1'], row['trait2'], row['trait3']
        writer.writerows([  # writes three rows of output from each row of input
            dict(zip(fieldnames, [email, 'trait1', trait1])),
            dict(zip(fieldnames, [email, 'trait2', trait2, trait2])),
            dict(zip(fieldnames, [email, 'trait3', trait3]))])

rawDescription: Python script to turn input csv columns into output csv row values


code:
while True:
    db.pending.wait()
    # after waking up, do code. for example, we wait for incoming messages to
    # be stored in the database. the threaded server will call db.pending.set()
    # which will wake us up. we'll poll the DB for new messages, relay them, clear
    # our event flag and go back to waiting.
    # ...
    db.pending.clear()

rawDescription: issues with socket programming - python

description: Issues with socket programming - python


code:
def func(fx):
    d={'AAA':1,'BBB':2,'CCC':3}
    length=len(fx)
    if length % 3 == 0:
        pass
    elif length % 3 == 1:
        fx = fx[:-1]
    elif length % 3 == 2:
        fx = fx[:-2]
    Fx=fx.upper()
    Fx3=[Fx[i:i+3] for i in range(0,len(Fx),3)]
    translate=[d[x] for x in Fx3]
    return translate

rawDescription: Dictionary works for len(string) multiple of 3. Function deletes remainders but now doesn't translate with dictionary. Python 2.7.1


rawDescription: what is the use of recursive relationship and a relationship to an undefined model in Django?

description: What is the use of recursive relationship and a relationship to an undefined model in Django


rawDescription: 'leet' program - getting all permutations


code:
cplot=map.contour(x,y,diff,clevs,
                      cmap=newcmap,
                      norm=newcnorm,
                      vmin=vmin,vmax=vmax)

rawDescription: Color differences between contour and contourf in matplotlib


code:
num=ord(char)
char=chr(num)

rawDescription: Python:Ascii character<->decimal representation conversion


code: file2_path = os.path.join(cur_directory_path, 'inner_dir', 'file2.py')

rawDescription: Include entire directory in python setup.py data_files


code:
df = pd.read_csv(filename, header=None,
                 names=['col1','col2','col3'], skiprows=[0,1,5,16,57,58,59])

rawDescription: Pandas: read_csv (read multiple tables in a single file)


code:
import os
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))
XMLFILES_FOLDER = os.path.join(PROJECT_ROOT, 'xml_files/')

rawDescription: How can I use relative path to read local files in Django app?

description: Use relative path to read local files in Django app


rawDescription: remove rows and columns from numpy array

description: Remove rows and columns from numpy array


code:
words = ['random', 'words']
text = 'a sample message with random words'
for word in words:
    text = text.replace(word, 'swords')

text

rawDescription: Replace all words from word list with another string in python


code:
s = "Columbus Blue Jackets at Buffalo Sabres - 10/09/2014"
re.split(r'\s+(?:at|-)\s+', s)
s = 'Montreal Canadiens at Buffalo Sabres - 10/09/2014'
re.split(r'\s+(?:at|-)\s+', s)

rawDescription: Python regex delimiting a string

description: Python regex delimiting a string


code:
def lookup( pivot_table, col, idx, fall_back=0 ):
    try:
        return pivot_table[ col ][ idx ]
    except KeyError:
        return fall_back

df[ 'cnt1' ] = [ lookup( pv1, row[ 'name' ], row[ 'date' ] ) for idx, row in df.iterrows( ) ]
df[ 'cnt' ] = [ lookup( pv, row[ 'name' ], row[ 'date' ] ) for idx, row in df.iterrows( ) ]

rawDescription: Calculating previous chance figure for use in chi square test


code:
[build_ext]
inplace=True

rawDescription: Python project with C extensions - structure, imports and tests


code: "five" < "three"

rawDescription: Why can't Python understand integers in word form?


code:
class my_cursor(self.conn.cursor):
    def __init__(self):
        self.execute("SET NAMES utf8")
        self.execute('SET CHARACTER SET utf8;')
        self.execute('SET character_set_connection=utf8;')

self.cursor1 = my_cursor()
self.cursor2 = my_cursor()
self.cursor3 = my_cursor()

rawDescription: Creating multiple cursors

description: Creating multiple cursors


code: [m for m in Bar.__dict__.values() if inspect.isfunction(m)]

rawDescription: Python - How can I query the class in which a method is defined?


code:
x = maybelist()
x[0] = 'first'
x[1] = 'second'
x[10] = 'eleventh'
print(x)
print(x[10])

rawDescription: What is the overhead of using a dictionary instead of a list?


code:
not 0
not 42

rawDescription: python and / or operators return value

description: Python and / or operators return value


code:
email_reg = re.compile(r'[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+')
email_reg.findall('I know my best friend mailto:foo@foo.com!')

rawDescription: Python split by regular expression?

description: Python split by regular expression


rawDescription: python lxml.html: proper way to iterate through text with .tail in docstring order

description: Python lxml.html: proper way to iterate through text with .tail in docstring order


rawDescription: python comprehension from two list or zip

description: Python comprehension from two list or zip


code:
class C(str):
    def __new__(cls, *args, **kw):
        return str.__new__(cls, *args, **kw)

c = C("hello world")
type(c)
c.__class__.__mro__

rawDescription: inheritance from str or int

description: Inheritance from str or int


rawDescription: Caesar cipher fails when output character is beyond 'z'


code:
mydict = {'Rust': {'definition':'rusts definition'},
          'Iron': {'definition':'iron definition'},
          'Pyrite': {'definition':'pyrite definition'}}

myorder = ['Pyrite', 'Rust', 'Iron']

from collections import OrderedDict

ordered = OrderedDict()
for k in myorder:
    ordered[k] = mydict[k]

rawDescription: How to reorder a python ordered dict based on array?

description: Reorder a python ordered dict based on array


code:
from itertools import combinations, groupby, islice

cards = ["a", "b", "c", "d"]
players = ["1", "1", "2", "2"]

def hand_combinations(players, cards):
    # convert ["1", "1", "2", "2"] into [("1", 2), ("2", 2)]
    players = list((x, len(list(y))) for x, y in groupby(players))

    # sets are faster to operate on in our case
    cards = set(cards)

    def generate(players, cards):
        if not players:
            yield []
        else:
            # pick the first player
            player_name, player_hand_size = players[0]
            # and then walk over all the possible hands for this player
            for player_hand in combinations(cards, player_hand_size):
                # for each hand, use the cards that are left to build all the
                # possible hands for the rest of the players in this iteration
                for tail in generate(players[1:], cards - set(player_hand)):
                    yield [(player_name, player_hand)] + tail

    return generate(players, cards)

# take only the 100 first combinations; otherwise it'll take
# forever with the larger example
combos = islice(hand_combinations(players, cards), 0, 100)

# convert back to the flat structure
flattened = [
    ' '.join(
        player_name + ':' + card
        for player_name, player_cards in combo
        for card in player_cards
    )
    for combo in combos
]

from pprint import pprint
pprint(flattened)

rawDescription: All possible combinations of card/poker hands for a set of players


code:
import string
b = a.translate(string.maketrans('0123456789', '1234567890'))

rawDescription: Python, context sensitive string substitution


code:
{'author': u'Kevin Boyd', 'link': 'http://www.ijreview.com/2014/08/172770-president-obama-realizes-world-messy-place-thanks-social-media/', 'title': u'President Obama Calls The World A Messy Place & Blames Social Media for Making People Take Notice'}
{'author': u'Reid Mene', 'link': 'http://www.ijreview.com/2014/08/172405-17-politicians-weird-jobs-time-office/', 'title': u'12 Most Unusual Professions of Politicians Before They Were Elected to Higher Office'}
{'author': u'Michael Hausam', 'link': 'http://www.ijreview.com/2014/08/172653-video-duty-mp-fakes-surrender-shoots-hostage-taker/', 'title': u'Video: Off-Duty MP Fake Surrenders at Gas Station Before Revealing Deadly Surprise for Hostage Taker'}
...

rawDescription: Working with post request to load more articles with scrapy python


code:
class general:
    msgs = []

rawDescription: why is this code generating three array values instead of one? python 3.x

description: Why is this code generating three array values instead of one? python 3.x


code:
Dict = {
    'key1': [('Red','Large',30),('Red','Medium',40),('Blue','Small',45)],
    'key2': [('Red','Large',35)],
    'key3': [('Yellow','Large',30),('Red','Medium',30)],
}
color = 'Red'
{key: [color, sum(t[2] for t in value if t[0] == color)] for key, value in Dict.iteritems()}

rawDescription: Sum Values in a Dictionary w/ respect to the Key - Python 2.7


code: 1 0 x x

code: x x x x

rawDescription: Python: replace multiple values of a Matrix


code:
some_needles_exist = any(find_needle(x) for x in haystacks)
all_stacks_have_needles = all(find_needle(x) for x in haystacks)

rawDescription: Better way to search a list of lists for an item in python


code:
movies/models.py
from django.db import models
from media.models import VideoFile as BaseVideoFile

# This model remains until the last migration, which deletes
# it from the schema.  Note the name conflict with media.models
class VideoFile(models.Model):
    movie = models.ForeignKey(Movie, blank=True, null=True)
    name = models.CharField(max_length=1024, blank=True)
    size = models.IntegerField(blank=True, null=True)
    ctime = models.DateTimeField(blank=True, null=True)

class MovieVideoFile(BaseVideoFile):
    movie = models.ForeignKey(Movie, blank=True, null=True, related_name='shows')

rawDescription: Using south to refactor a Django model with inheritance


code:
def  commonElements(t1,t2):
     # find the intersection/common elements
    return tuple(sorted(set(t1).intersection(t2)))

def  commonElements(t1,t2):
    return tuple(sorted(ele for ele in t1 if ele in t2))

rawDescription: how to compare between two Tuples?

description: Compare between two Tuples


code:
# find line number in file with matching text
for i, line in enumerate(some_file):
    if 'some text' in line:
        break
print('First match found at line {}.'.format(i))

rawDescription: Ways to avoid that for-loop variables cut into Python's global namespace


code:
runs = 10
inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55)
results = dict([(i,[]) for i in inputs])

for run in range(runs):
    for i in inputs:
        results[i].append(benchmark(i))

rawDescription: How do I create a unique value for each key using dict.fromkeys?

description: Create a unique value for each key using dict.fromkeys


code:
class ColorCycler:
    def __init__(self, color_int, color_min, color_max, color_change_value):
        self.value = color_int
        self.min = color_min
        self.max = color_max
        self.change = color_change_value
        self.increment = True

    def __next__(self):
        if self.value >= self.max:
            self.increment = False
        elif self.value <= self.min:
            self.increment = True

        if self.increment:
            self.value += self.change
        else:
            self.value -= self.change

        return self.value

r = ColorCycler(130, 5, 250, 2)
g = ColorCycler(120, 0, 255, 1)
b = ColorCycler(200, 10, 240, 3)

for i in range(10):
    print(next(r), next(g), next(b))

rawDescription: how to iterate multiple variables up and back down repeatedly

description: Iterate multiple variables up and back down repeatedly


code: newList = list(set(a).difference(b))

rawDescription: Python list difference

description: Python list difference


code:
def getAttributes2(clazz):
    attrs = {}
    for name in vars(clazz):
        if name.startswith("__"):
            continue
        attr = getattr(clazz, name)
        if callable(attr):
            continue
        attrs[name] = attr
    return attrs

rawDescription: Get class and object attributes of class without methods and builtins


code:
data.index = pd.DatetimeIndex(data['Date'])
goog_totals = data['Earnings'].resample('w', how='sum').dropna()

rawDescription: Sorting column entries in Pandas by name and week


code:
import my_module
...
my_module.my_variable

rawDescription: Python passing variable values via import


code:
#!/usr/bin/python3

from matplotlib import pyplot as plt

m = [[1,2,3,4],
     [2,3,4,5],
     [2,2,1,5]]

fig = plt.figure()
ax = fig.add_subplot(111)

ax.contourf(m)
ax.axis('equal')

fig.savefig("equal.png")

rawDescription: how to change the shape of a contour in matplotlib

description: Change the shape of a contour in matplotlib


code:
for z in range(nsteps):
    waves_sequence[z] = make_wave_snapshot(size,wavelength,(2*math.pi*z/nsteps))

rawDescription: Combining 2-d arrays to form a 3-d array


code: api.write_regular(title, data=data)

rawDescription: Post picture from directory to tumblr via python


code:
def lowest_price(store_dict):
    return [(k,min(v)) if len(v) > 0 else (k,False) for k,v in store_dict.items()]

rawDescription: dictionary to list of tuples with smallest value

description: Dictionary to list of tuples with smallest value


code:
p = subprocess.Popen('./myapp -p s', shell=True)
p.communicate()

rawDescription: Python subprocess passes one argument only


rawDescription: How would I go about playing an alarm sound in python?


code:
penguins = cv2.imread('penguins.png', 0)
kernel = np.ones((5,5),np.float32)/25
# kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]], np.float32)
conv_image = image_convolve_mask(penguins, [(7, 7), (36, 192), (48, 207)], kernel)
plt.imshow(conv_image, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])
plt.show()

rawDescription: Image convolution at specific points

description: Image convolution at specific points


rawDescription: Django: Give custom filtering methods to `QuerySet` objects of a specific model


rawDescription: Python delete row in numpy array

description: Python delete row in numpy array


code:
def my_send_app(environ, start_response):
    status = '200 OK' # HTTP Status
    headers = [('Content-type', 'text/plain')] # HTTP Headers
    start_response(status, headers)

    # The returned object is going to be printed
    # create the HTML including the form; return as list of strings
    return [...]

def my_receive_app(envirion, start_responce):
    # Returns a dictionary containing lists as values.
    d = urlparse.parse_qs(environ['QUERY_STRING'])
    # d should be similar to vars(args)
    # apply the values in d
    # use start_responce to reply to the browser

rawDescription: HTML forms and argparse

description: HTML forms and argparse


rawDescription: universal new line mode in csv reader make csv writer write mistake line break in file

description: Universal new line mode in csv reader make csv writer write mistake line break in file


code: example(square)  # = square(1) + square(2) = 1 + 4 = 5

rawDescription: How can I pass functions or operators as arguments to a function in Python?

description: Pass functions or operators as arguments to a function in Python


code:
from crypt import crypt
from itertools import product
from string import ascii_letters, digits

def decrypt(crypted, charset=ascii_letters + digits):
    # find hash for all 4-char strings from the charset
    # and compare with the given hash
    for candidate in map(''.join, product(charset, repeat=4)):
        if crypted == crypt(candidate, crypted):
            return candidate

rawDescription: How to encrypt all possible strings in a defined character set python?

description: Encrypt all possible strings in a defined character set python


code:
import numpy as np;
L     = 3 # number of bins to zero out along each axis (change this to fit your needs)
          # should be odd for even length array, and even for odd length array

# Following assumes x is the 1D array
lower = (len(x)-L)/2+1
upper = (len(x)+L)/2+1
x[lower:upper] = 0 # zero-out in the middle

# Following assume y is the 3D array
lower = [(d-L)/2+1 for d in y.shape]
upper = [(d+L)/2+1 for d in y.shape]
y[lower[0]:upper[0],:,:] = 0 # zero-out in the middle of axis 0
y[:,lower[1]:upper[1],:] = 0 # zero-out in the middle of axis 1
y[:,:,lower[2]:upper[2]] = 0 # zero-out in the middle of axis 2

rawDescription: which are the high frequency terms in numpy.fftn?

description: Which are the high frequency terms in numpy.fftn


code:
class BAdmin(admin.ModelAdmin):
    form = BForm

admin.site.register(B, BAdmin)

rawDescription: change model admin form default value

description: Change model admin form default value


code:
comb_dict = {}
def find3(S, m, d):
    try:
        return random.sample(comb_dict[(S,m)], d)
    except KeyError:
        comb_dict[(S, m)] = list(itertools.combinations(S, m))
        return random.sample(comb_dict[(S,m)], d)

rawDescription: Python- exact number of subsets

description: Python- exact number of subsets


code: map(lambda x: dict(d, phone=x), lst)

rawDescription: Return copies of dictionary modified

description: Return copies of dictionary modified


code:
import math
def roundTo32(x, base=32):
    return int(base * math.ceil(float(x) / base))

roundTo32(15)
roundTo32(33)

rawDescription: How to round up to 32 using the math module (Python 3,)

description: Round up to 32 using the math module (Python 3,)


code: (ctypes.c_ubyte * 3)(*range(3))

rawDescription: Passing python array to a c function using c_types


rawDescription: How can I have references of lists in Python

description: Have references of lists in Python


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

rawDescription: How can I fetch mysql single column list results directly into a list in python?

description: Fetch mysql single column list results directly into a list in python


code:
df1 = df[df['key2'] == 'one']
df1
df1.groupby('key1')['data1'].sum()

rawDescription: Python Pandas Conditional Sums

description: Python Pandas Conditional Sums


code:
conn = stomp.Connection()
lst = MyListener()
conn.set_listener('', lst)
conn.start()
conn.connect()
conn.subscribe(destination='/queue/test', id=1, ack='auto')
time.sleep(2)
messages = lst.msg_list
conn.disconnect()
return render(request, 'template.html', {'messages': messages})

rawDescription: Stomp.py how to return message from listener


rawDescription: Spark DataFrame TimestampType - how to get Year, Month, Day values from field?


code:
import re
s = "<word1></word1> <word2>worda</word2> <word3>wordb</word3> <word4></word4>"
re.findall("\S+", s.replace(">", "> ").replace("<", " <"))

rawDescription: Splitting a string into multiple strings in Python


rawDescription: How to replace the nth element of multi dimension lists in Python?

description: Replace the nth element of multi dimension lists in Python


code:
List2s = set(List2)
filtered_list = [item for item in List1 if len({item[0], item[3]} & List2s) == 2]

rawDescription: Searching items in two lists

description: Searching items in two lists


rawDescription: Python string formatting, include the 0 at the end


code:
vals = {k: set(val) for k, val in dict1.items()}

for key, val in dict1.copy().items():
    for k, v in vals.copy().items():
        if k == key:
            continue
        if v.intersection(val):
            union = list(v.union(val))
            dict1[key] = union
            del vals[k]
            del dict1[k]

rawDescription: How to combine values composed of lists with common items in a dictionary using Python?

description: Combine values composed of lists with common items in a dictionary using Python


code:
def constantcall():
      j = 2
      chk = 1
      f = open("primes.txt", "w")
      primes = []
      notprimes = []
      ask = input("how many primes? ")
      while len(primes) < int(ask):
          k = 2
          while not(k==j) and not(j%k==0):
                k = k + 1
          if k == j:
                primes.append(j)
                f.write(str(j)+"\n")
          else:
                notprimes.append(j)
          if len(primes) >= 1000*chk:
                chk = chk + 1
                print("There have been " + str(len(primes)) + " primes counted so far")
                j = j + 1
                print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
                f.close
                return(" ")

if __name__ == '__main__':
    constantcall()

rawDescription: List not being written to a text file

description: List not being written to a text file


rawDescription: Numpy: use reshape or newaxis to add dimensions


code: list(k for k, g in itertools.groupby(x for x in numbers if x != 0))

rawDescription: Grouping a series in Python

description: Grouping a series in Python


rawDescription: python pandas custom agg function

description: Python pandas custom agg function


code:
class Earthquake(object):

    def __init__(self, name, otime, lat, lon, depth):
        self.name = name
        self.otime = otime
        self.lat = lat
        self.lon = lon
        self.depth = depth

    @classmethod
    def from_string(cls, strline):
        items = line.split()
        name = items[0]
        otime = dt.datetime.strptime(items[1], "%d-%m-%YT%H:%M:%S")
        lat, lon, depth = map(float, items[2:])
        return cls(name, otime, lat, lon, depth)

rawDescription: How to introduce the attributes of an object in python by calling a method in __init__ method?

description: Introduce the attributes of an object in python by calling a method in __init__ method


code:
class AppLicense(object):
  def GetApplicationStatus(self):
    pass

rawDescription: C Class Instance from Void Pointer using Ctypes


code: float_formatter = lambda x: "%.2f" % x

rawDescription: Formatting floats in a numpy array

description: Formatting floats in a numpy array


code: index = zip(*indices_to_watch)

rawDescription: Numpy masked array modification

description: Numpy masked array modification


code:
names_dict = dict((name,index)
                  for index,lst in enumerate(names)
                  for name in lst)

rawDescription: Python Golf: what's the most concise way of turning this list of lists into a dictionary:


code:
import time

image1 = ("image1.png")
alarm = '17:37:00'

while (True):
    # Look what time it is right now [24 hour format].
    currentTime = time.strftime("%H:%M:%S")
    if (currentTime == alarm):
        print('It is time!')
        # Exit the (while) loop.
        break;

rawDescription: sikuli (python) script starting at xx hour of the day, wait("image.png",highnumber) not working?

description: Sikuli (python) script starting at xx hour of the day, wait("image.png",highnumber) not working


code:
old = dict(old) # if you do go for this approach be sure to build these
new = dict(new) # variables as dictionaries, not convert them each time

removed = {k:old[k] for k in old.keys() - new.keys()}
added = {k:new[k] for k in new.keys() - old.keys()}

rawDescription: python compare difference between two lists

description: Python compare difference between two lists


code:
"""
A pure python (slow) implementation of rijndael with a decent interface

To include -

from rijndael import rijndael

To do a key setup -

r = rijndael(key, block_size = 16)

key must be a string of length 16, 24, or 32
blocksize must be 16, 24, or 32. Default is 16

To use -

ciphertext = r.encrypt(plaintext)
plaintext = r.decrypt(ciphertext)

If any strings are of the wrong length a ValueError is thrown
"""

# ported from the Java reference code by Bram Cohen, April 2001
# this code is public domain, unless someone makes
# an intellectual property claim against the reference
# code, in which case it can be made public domain by
# deleting all the comments and renaming all the variables

import copy
import string

shifts = [[[0, 0], [1, 3], [2, 2], [3, 1]],
          [[0, 0], [1, 5], [2, 4], [3, 3]],
          [[0, 0], [1, 7], [3, 5], [4, 4]]]

# [keysize][block_size]
num_rounds = {16: {16: 10, 24: 12, 32: 14}, 24: {16: 12, 24: 12, 32: 14}, 32: {16: 14, 24: 14, 32: 14}}

A = [[1, 1, 1, 1, 1, 0, 0, 0],
     [0, 1, 1, 1, 1, 1, 0, 0],
     [0, 0, 1, 1, 1, 1, 1, 0],
     [0, 0, 0, 1, 1, 1, 1, 1],
     [1, 0, 0, 0, 1, 1, 1, 1],
     [1, 1, 0, 0, 0, 1, 1, 1],
     [1, 1, 1, 0, 0, 0, 1, 1],
     [1, 1, 1, 1, 0, 0, 0, 1]]

# produce log and alog tables, needed for multiplying in the
# field GF(2^m) (generator = 3)
alog = [1]
for i in range(255):
    j = (alog[-1] << 1) ^ alog[-1]
    if j & 0x100 != 0:
        j ^= 0x11B
    alog.append(j)

log = [0] * 256
for i in range(1, 255):
    log[alog[i]] = i

# multiply two elements of GF(2^m)
def mul(a, b):
    if a == 0 or b == 0:
        return 0
    return alog[(log[a & 0xFF] + log[b & 0xFF]) % 255]

# substitution box based on F^{-1}(x)
box = [[0] * 8 for i in range(256)]
box[1][7] = 1
for i in range(2, 256):
    j = alog[255 - log[i]]
    for t in range(8):
        box[i][t] = (j >> (7 - t)) & 0x01

B = [0, 1, 1, 0, 0, 0, 1, 1]

# affine transform:  box[i] <- B + A*box[i]
cox = [[0] * 8 for i in range(256)]
for i in range(256):
    for t in range(8):
        cox[i][t] = B[t]
        for j in range(8):
            cox[i][t] ^= A[t][j] * box[i][j]

# S-boxes and inverse S-boxes
S =  [0] * 256
Si = [0] * 256
for i in range(256):
    S[i] = cox[i][0] << 7
    for t in range(1, 8):
        S[i] ^= cox[i][t] << (7-t)
    Si[S[i] & 0xFF] = i

# T-boxes
G = [[2, 1, 1, 3],
    [3, 2, 1, 1],
    [1, 3, 2, 1],
    [1, 1, 3, 2]]

AA = [[0] * 8 for i in range(4)]

for i in range(4):
    for j in range(4):
        AA[i][j] = G[i][j]
        AA[i][i+4] = 1

for i in range(4):
    pivot = AA[i][i]
    if pivot == 0:
        t = i + 1
        while AA[t][i] == 0 and t < 4:
            t += 1
            assert t != 4, 'G matrix must be invertible'
            for j in range(8):
                AA[i][j], AA[t][j] = AA[t][j], AA[i][j]
            pivot = AA[i][i]
    for j in range(8):
        if AA[i][j] != 0:
            AA[i][j] = alog[(255 + log[AA[i][j] & 0xFF] - log[pivot & 0xFF]) % 255]
    for t in range(4):
        if i != t:
            for j in range(i+1, 8):
                AA[t][j] ^= mul(AA[i][j], AA[t][i])
            AA[t][i] = 0

iG = [[0] * 4 for i in range(4)]

for i in range(4):
    for j in range(4):
        iG[i][j] = AA[i][j + 4]

def mul4(a, bs):
    if a == 0:
        return 0
    r = 0
    for b in bs:
        r <<= 8
        if b != 0:
            r = r | mul(a, b)
    return r

T1 = []
T2 = []
T3 = []
T4 = []
T5 = []
T6 = []
T7 = []
T8 = []
U1 = []
U2 = []
U3 = []
U4 = []

for t in range(256):
    s = S[t]
    T1.append(mul4(s, G[0]))
    T2.append(mul4(s, G[1]))
    T3.append(mul4(s, G[2]))
    T4.append(mul4(s, G[3]))

    s = Si[t]
    T5.append(mul4(s, iG[0]))
    T6.append(mul4(s, iG[1]))
    T7.append(mul4(s, iG[2]))
    T8.append(mul4(s, iG[3]))

    U1.append(mul4(t, iG[0]))
    U2.append(mul4(t, iG[1]))
    U3.append(mul4(t, iG[2]))
    U4.append(mul4(t, iG[3]))

# round constants
rcon = [1]
r = 1
for t in range(1, 30):
    r = mul(2, r)
    rcon.append(r)

del A
del AA
del pivot
del B
del G
del box
del log
del alog
del i
del j
del r
del s
del t
del mul
del mul4
del cox
del iG

class rijndael:
    def __init__(self, key, block_size = 16):
        if block_size != 16 and block_size != 24 and block_size != 32:
            raise ValueError('Invalid block size: ' + str(block_size))
        if len(key) != 16 and len(key) != 24 and len(key) != 32:
            raise ValueError('Invalid key size: ' + str(len(key)))
        self.block_size = block_size

        ROUNDS = num_rounds[len(key)][block_size]
        BC = block_size // 4
        # encryption round keys
        Ke = [[0] * BC for i in range(ROUNDS + 1)]
        # decryption round keys
        Kd = [[0] * BC for i in range(ROUNDS + 1)]
        ROUND_KEY_COUNT = (ROUNDS + 1) * BC
        KC = len(key) // 4

        # copy user material bytes into temporary ints
        tk = []
        for i in range(0, KC):
            tk.append((ord(key[i * 4]) << 24) | (ord(key[i * 4 + 1]) << 16) |
                (ord(key[i * 4 + 2]) << 8) | ord(key[i * 4 + 3]))

        # copy values into round key arrays
        t = 0
        j = 0
        while j < KC and t < ROUND_KEY_COUNT:
            Ke[t // BC][t % BC] = tk[j]
            Kd[ROUNDS - (t // BC)][t % BC] = tk[j]
            j += 1
            t += 1
        tt = 0
        rconpointer = 0
        while t < ROUND_KEY_COUNT:
            # extrapolate using phi (the round key evolution function)
            tt = tk[KC - 1]
            tk[0] ^= (S[(tt >> 16) & 0xFF] & 0xFF) << 24 ^  \
                     (S[(tt >>  8) & 0xFF] & 0xFF) << 16 ^  \
                     (S[ tt        & 0xFF] & 0xFF) <<  8 ^  \
                     (S[(tt >> 24) & 0xFF] & 0xFF)       ^  \
                     (rcon[rconpointer]    & 0xFF) << 24
            rconpointer += 1
            if KC != 8:
                for i in range(1, KC):
                    tk[i] ^= tk[i-1]
            else:
                for i in range(1, KC // 2):
                    tk[i] ^= tk[i-1]
                tt = tk[KC // 2 - 1]
                tk[KC // 2] ^= (S[ tt        & 0xFF] & 0xFF)       ^ \
                               (S[(tt >>  8) & 0xFF] & 0xFF) <<  8 ^ \
                               (S[(tt >> 16) & 0xFF] & 0xFF) << 16 ^ \
                               (S[(tt >> 24) & 0xFF] & 0xFF) << 24
                for i in range(KC // 2 + 1, KC):
                    tk[i] ^= tk[i-1]
            # copy values into round key arrays
            j = 0
            while j < KC and t < ROUND_KEY_COUNT:
                Ke[t // BC][t % BC] = tk[j]
                Kd[ROUNDS - (t // BC)][t % BC] = tk[j]
                j += 1
                t += 1
        # inverse MixColumn where needed
        for r in range(1, ROUNDS):
            for j in range(BC):
                tt = Kd[r][j]
                Kd[r][j] = U1[(tt >> 24) & 0xFF] ^ \
                           U2[(tt >> 16) & 0xFF] ^ \
                           U3[(tt >>  8) & 0xFF] ^ \
                           U4[ tt        & 0xFF]
        self.Ke = Ke
        self.Kd = Kd

    def encrypt(self, plaintext):
        if len(plaintext) != self.block_size:
            raise ValueError('wrong block length, expected ' + str(self.block_size) + ' got ' + str(len(plaintext)))
        Ke = self.Ke

        BC = self.block_size // 4
        ROUNDS = len(Ke) - 1
        if BC == 4:
            SC = 0
        elif BC == 6:
            SC = 1
        else:
            SC = 2
        s1 = shifts[SC][1][0]
        s2 = shifts[SC][2][0]
        s3 = shifts[SC][3][0]
        a = [0] * BC
        # temporary work array
        t = []
        # plaintext to ints + key
        for i in range(BC):
            t.append((ord(plaintext[i * 4    ]) << 24 |
                      ord(plaintext[i * 4 + 1]) << 16 |
                      ord(plaintext[i * 4 + 2]) <<  8 |
                      ord(plaintext[i * 4 + 3])        ) ^ Ke[0][i])
        # apply round transforms
        for r in range(1, ROUNDS):
            for i in range(BC):
                a[i] = (T1[(t[ i           ] >> 24) & 0xFF] ^
                        T2[(t[(i + s1) % BC] >> 16) & 0xFF] ^
                        T3[(t[(i + s2) % BC] >>  8) & 0xFF] ^
                        T4[ t[(i + s3) % BC]        & 0xFF]  ) ^ Ke[r][i]
            t = copy.copy(a)
        # last round is special
        result = []
        for i in range(BC):
            tt = Ke[ROUNDS][i]
            result.append((S[(t[ i           ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF)
            result.append((S[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF)
            result.append((S[(t[(i + s2) % BC] >>  8) & 0xFF] ^ (tt >>  8)) & 0xFF)
            result.append((S[ t[(i + s3) % BC]        & 0xFF] ^  tt       ) & 0xFF)
        return ''.join(map(chr, result))

    def decrypt(self, ciphertext):
        if len(ciphertext) != self.block_size:
            raise ValueError('wrong block length, expected ' + str(self.block_size) + ' got ' + str(len(ciphertext)))
        Kd = self.Kd

        BC = self.block_size // 4
        ROUNDS = len(Kd) - 1
        if BC == 4:
            SC = 0
        elif BC == 6:
            SC = 1
        else:
            SC = 2
        s1 = shifts[SC][1][1]
        s2 = shifts[SC][2][1]
        s3 = shifts[SC][3][1]
        a = [0] * BC
        # temporary work array
        t = [0] * BC
        # ciphertext to ints + key
        for i in range(BC):
            t[i] = (ord(ciphertext[i * 4    ]) << 24 |
                    ord(ciphertext[i * 4 + 1]) << 16 |
                    ord(ciphertext[i * 4 + 2]) <<  8 |
                    ord(ciphertext[i * 4 + 3])        ) ^ Kd[0][i]
        # apply round transforms
        for r in range(1, ROUNDS):
            for i in range(BC):
                a[i] = (T5[(t[ i           ] >> 24) & 0xFF] ^
                        T6[(t[(i + s1) % BC] >> 16) & 0xFF] ^
                        T7[(t[(i + s2) % BC] >>  8) & 0xFF] ^
                        T8[ t[(i + s3) % BC]        & 0xFF]  ) ^ Kd[r][i]
            t = copy.copy(a)
        # last round is special
        result = []
        for i in range(BC):
            tt = Kd[ROUNDS][i]
            result.append((Si[(t[ i           ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF)
            result.append((Si[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF)
            result.append((Si[(t[(i + s2) % BC] >>  8) & 0xFF] ^ (tt >>  8)) & 0xFF)
            result.append((Si[ t[(i + s3) % BC]        & 0xFF] ^  tt       ) & 0xFF)
        return ''.join(map(chr, result))

def encrypt(key, block):
    return rijndael(key, len(block)).encrypt(block)

def decrypt(key, block):
    return rijndael(key, len(block)).decrypt(block)

rawDescription: Python equivalent of PHP's MCRYPT_RIJNDAEL_256 CBC


code:
def __init__(self, data):
    self.__dict__.update(data)

rawDescription: How to filter the return value of a class that extends the list object

description: Filter the return value of a class that extends the list object


code:
import pandas as pd
import collections

df = pd.DataFrame({'player1' : ['Joe', 'Steve', 'Bill', 'Doug',
                      'Steve','Bill','Joe','Steve'], 'player2' : ['Bill',
                      'Doug', 'Steve', 'Joe', 'Bill', 'Steve', 'Doug', 'Bill'],
                      'winner' : ['Joe','Steve' , 'Steve','Doug', 'Bill',
                      'Steve', 'Doug', 'Steve'], 'loser' : ['Bill', 'Doug',
                      'Bill', 'Joe', 'Steve', 'Bill', 'Joe', 'Bill'], },
                  columns = ['player1', 'player2', 'winner', 'loser'])

wins = collections.Counter()
def count_wins():
    for idx, row in df.iterrows():
        wins[row['winner']] += 1
        yield wins[row['player1']], wins[row['player2']]
df['player1_wins'], df['player2_wins'] = zip(*list(count_wins()))
print(df)

rawDescription: pandas groupby values in different column

description: Pandas groupby values in different column


rawDescription: How can I slice a timeseries dataframe in Pandas based on multiple conditions?

description: Slice a timeseries dataframe in Pandas based on multiple conditions


code:
import re
def getwords(text, splitchars=' \t|!?.;:"'):
  words_iter = re.finditer(
    "([%s]+)" % "".join([("^" + c) for c in splitchars]),
    text)
  for word in words_iter:
    yield word.group()

# a quick test
s = "a:b cc? def...a||"
words = [x for x in getwords(s)]
assert ["a", "b", "cc", "def", "a"] == words, words

rawDescription: Effective way to iteratively append to a string in Python?


code:
l = []
map(l.extend,[[x, a] for a in y])
return l

rawDescription: list comprehension question

description: List comprehension question


code:
nli.go_to_head()
nli.find(4)
nli.insert(11)
nli.nested_list

rawDescription: Convert list of positions [4, 1, 2] of arbitrary length to an index for a nested list


code:
dict2 = dict1.copy()
for key, value in dict2.items():
    dict2[key] = value[0]

print(dict2) # good so far
print(dict1) # okay....

rawDescription: Dictionary comprehension containing dictionary elements


code:
method = "whatever"
getattr(test, method)

rawDescription: How do I access a object's method when the method's name is in a variable?

description: Access a object's method when the method's name is in a variable


rawDescription: What is the inverse function of zip in python?


code: df['periods'] = np.where((morning_start.hour <= df.t.apply(lambda x: x.hour)) & (df.t.apply(lambda x: x.hour) <= morning_end.hour), 'morning', 'evening')

rawDescription: Bin timestamp into custom periods

description: Bin timestamp into custom periods


rawDescription: Convert from 24 bit signed to latitude / longitude?


code: results = models.Object.query.filter(models.Object.id.in_(list_of_ids)).paginate(page, 10, False) if list_of_ids else EmptyPaginator()

rawDescription: empty paginate object sqlalchemy

description: Empty paginate object sqlalchemy


code:
def findvalue(grid, value):
    for rownum, row in enumerate(grid):
        for colnum, itemvalue in enumerate(row):
            if itemvalue == value:
                return (rownum, colnum)
    raise ValueError("Value not found in grid")

rawDescription: How to search nested list grid and give lettered coordinates in Python?

description: Search nested list grid and give lettered coordinates in Python


code:
def justify_bitwise(n):
   int_n = int(abs(n))
   p = 0
   while int_n != 1:
       p += 1
       int_n >>= 1

   return float(n) / (1<<p)

rawDescription: Bitwise operations to produce power of two in Python


code:
x = np.arange(27).reshape(3,3,3)
x
x.swapaxes(0,1)

rawDescription: Reordering rows of a 3D array

description: Reordering rows of a 3D array


code: request.getMessage = extend_with_openid_shutdown_ack.__get__(request, type(request))

rawDescription: passing openid_shutdown_ack parameter to my applicion using the Python OpenID library

description: Passing openid_shutdown_ack parameter to my applicion using the Python OpenID library


rawDescription: Python: Save data with floats and strings with np.savetxt


code: [x for x in name if not any(word in x for word in name if word != x)]

rawDescription: Separating compound nouns from basic nouns


rawDescription: python: save list to a file with performance in mind

description: Python: save list to a file with performance in mind


code:
def nextx(lst,i,n,x):
    ll = np.array(lst)
    rll = np.roll(ll, n-i)
    trll = np.tile(rll, x%n+1)
    return list(trll[:x])

rawDescription: Iterate through a List Multiple times Cyclically starting from the Matching Index


rawDescription: Finding the maximum return value of a function and the corresponding input for a given number of inputs


code:
def after(self, ms, func=None, *args):
    """Call function once after given time.

    MS specifies the time in milliseconds. FUNC gives the
    function which shall be called. Additional parameters
    are given as parameters to the function call.  Return
    identifier to cancel scheduling with after_cancel."""

rawDescription: How do you run your own code alongside Tkinter's event loop?

description: Run your own code alongside Tkinter's event loop


code:
import matplotlib as mpl
import matplotlib.pylab as plt
par = plt.hist2d(x, y, norm=mpl.colors.LogNorm(), cmap=mpl.cm.gray)

rawDescription: matplotlib: log transform counts in hist2d

description: Matplotlib: log transform counts in hist2d


code:
s = mystr('a0a1a2')
s
len(s)
s.capitalize()

rawDescription: Python: Lazy String Decoding

description: Python: Lazy String Decoding


code:
# functions.py ; not .php
def sendMessage(sock, receiver, message):
    sock.send ('PRIVMSG ' + ontvanger + ' :' + message + '\n')

rawDescription: NameError: global name 'sock' is not defined


code:
for member in members:
    print(member.name, member.dayoff)

rawDescription: Create object from several lists

description: Create object from several lists


code:
def anagram_solver(first_words, second_words):
    result = []
    for i in xrange(len(first_words)):
        a = list(first_words[i])
        b = list(second_words[i])
        a.sort()
        b.sort()

        result.append(a == b)
    return result

rawDescription: Anagram check in Python

description: Anagram check in Python


code:
TO_HIDE_ATTRS = {'class': 'hidden'}
class GalleryAdminForm(forms.ModelForm):
    auto_id=False
    order = forms.CharField(widget=forms.TextInput(attrs=TO_HIDE_ATTRS))

rawDescription: How do I hide the field label for a HiddenInput widget in Django Admin?

description: Hide the field label for a HiddenInput widget in Django Admin


code:
new_object = TheModel(
    date=datetime.datetime.strptime('2014-12-15', '%Y-%m-%d'))

rawDescription: Compare saved date field with new unsaved object


code:
def example2():
  return lambda x: x + 1

rawDescription: How to design mathematical program which calculate the derivative of a function using python?

description: Design mathematical program which calculate the derivative of a function using python


code:
def dispatch(self, request, *args, **kwargs):
    @condition(...)
    def _dispatch(request, *args, **kwargs):
        return super(ViewClass, self).dispatch(request, *args, **kwargs)
    return _dispatch(request, *args, **kwargs)

rawDescription: Using ETag / Last-Modified decorators with Django's class-based generic views


code:
df['grp'] = (df['T'] == 0).cumsum()           # label consecutive runs of integers
x = df.groupby('grp')['data'].first()         # first value in each group
df['dataDiv'] = df['data'] / df['grp'].map(x) # divide

rawDescription: How to normalize values in a dataframe column in different ranges

description: Normalize values in a dataframe column in different ranges


code: first_number, _ = line.split()

rawDescription: How can I index a line to the next white space available?

description: Index a line to the next white space available


code:
df1 = pd.DataFrame(np.array([
    ['DJ', 0.1],
    ['SP', 0.2],
    ['USDJPY', 0.03]]),
    columns=['Asset', 'Returns'])
df2 = pd.DataFrame(np.array([
    ['USA', 'E', 'DJ'],
    ['USA', 'E', 'SP'],
    ['USA', 'FX', 'USDJPY']]),
    columns=['Country', 'Class', 'Asset'])

df1.merge(df2, on="Asset")

rawDescription: create multiple index for a dataframe in pandas

description: Create multiple index for a dataframe in pandas


rawDescription: Method to split a SciPy minimum spanning tree based on greatest edge weight?


rawDescription: Is there a way to control the number of partitions when reading a text file in PySpark


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

class Food(models.Model):
     """Food, by name."""
     name = models.CharField(max_length=25)

# ConsumedFood has a foreign key to Food, and a "eaten_by" generic relation
class ConsumedFood(models.Model):
    food = models.ForeignKey(Food, related_name="eaters")
    content_type = models.ForeignKey(ContentType, null=True)
    object_id = models.PositiveIntegerField(null=True)
    eaten_by = generic.GenericForeignKey('content_type', 'object_id')

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    birth_date = models.DateField()
    address = models.CharField(max_length=100)
    city = models.CharField(max_length=50)
    foods = generic.GenericRelation(ConsumedFood)

class Cat(models.Model):
    name = models.CharField(max_length=50)
    foods = generic.GenericRelation(ConsumedFood)

class Cow(models.Model):
    farmer = models.ForeignKey(Person)
    foods = generic.GenericRelation(ConsumedFood)

rawDescription: How can one get the set of all classes with reverse relationships for a model in Django?


code:
from collections import OrderedDict
od = OrderedDict([(u'attributes', OrderedDict([(u'type', u'Campaign__c'), (u'url', u'/services/data/v29.0/sobjects/Campaign__c/a0B9000000I6CDUEA3')])), (u'clicks__c', 0.0)])
od.keys()
od['clicks__c']

rawDescription: How to Parse an orderedDict?

description: Parse an orderedDict


code:
if player is player1:
   score1=score1+1
if player is player2:
   score2=score2+1

rawDescription: Modifying code avoiding break statements


code: pd.DataFrame([tempDF[key] == val for key, val in tempDict.items()]).T.all(axis=1)

rawDescription: Selecting data from Pandas dataframe based on criteria stored in a dict


code:
s="Total DB read time : TDBT(56) TDTO(78) TDTC(567) TON(567) TOT(345)"

spl = s.split(":")[1].replace("("," ").replace(")"," ").split()
print(spl)

rawDescription: regex to extract values within parentheses and the word before parentheses using python

description: Regex to extract values within parentheses and the word before parentheses using python


code:
img=np.ones((28,28),int)
imgr = img.ravel()
imgr.shape

rawDescription: How can I make a "tuple of an ndarray of ndarrays"?

description: Make a "tuple of an ndarray of ndarrays"


code:
from subscript import mytest
a = 1
b = 2
mytest(a, b)

rawDescription: Functioned called from another script returning results twice?


code:
import mock
mock = mock.Mock()
a = A(mock)
a.class_b

rawDescription: Automocking for Python?

description: Automocking for Python


code:
release = Release.objects.get(slug=self.kwargs['slug'])
return Sound.objects.filter(release__slug=release)

rawDescription: Returning File Fields through Many to Many Relationship in Django for Zipview


code: filled = pd.Series(x).fillna(limit=2, method='ffill')

rawDescription: Working with NaN values in matplotlib

description: Working with NaN values in matplotlib


code:
def dict_into_list(self):
    return {key: value for key, value in self.__dict__.items()
            if not inspect.isfunction(value)}

rawDescription: Adding items to a list if it's not a function


rawDescription: Editing data in CSV files using Pandas

description: Editing data in CSV files using Pandas


code: pd.Series([i[0] for i in df.loc[:, ['a', 'b']].apply(random.sample, args=(1,), axis=1)], index=df.index)

rawDescription: Random selection in pandas dataframe

description: Random selection in pandas dataframe


rawDescription: Python: elegant way to split a string in order to pick the last element when the len of string is unknown


code:
with open('output.txt', 'w') as f:
    for line in lines:
        line,p = line.rsplit("$",1)
        f.write("{} ${}".format(line,p))

rawDescription: Beautiful Soup - how to clean extracting data?


code:
stdlibs = []
for lib in sys.path:
    if os.path.isdir(lib):
        for module in os.listdir(lib):
            stdlibs.append(lib + "/" + module)

rawDescription: python how to use imp.find_module or alternative

description: Python how to use imp.find_module or alternative


code:
import numpy as np
arra = np.arange(16).reshape(2, 2, 4)

rawDescription: Iterating and selecting a specific array from a multidimensional array in Python


code:
prof = profile(binary_search)
prof(range(100), 44)

rawDescription: Python: counting how many times a given line is executed


code:
from collections import defaultdict

propertyDict = defaultdict(list)
properties = ('required', 'as_banner', 'min', 'chart_layout', 'client_name',
              'filter_text', 'sort_order', 'chart_type', 'chart_color',
              'position', 'order')

for i, subaxis in enumerate(table.Axes['Side'].SubAxes):
    nField = shatter_sae(subaxis.Specification)['varName']
    field = mdd.Fields[nField]
    for prop in properties:
        value = field.Properties.Item[prop]
        if value:
            propertyDict[prop].append(value)

# optional, turn `defaultdict` back into a `dict` object. This step is really
# not needed unless you need the `defaultdict.__missing__` behaviour to cease for
# later code.
# propertyDict = dict(propertyDict)

rawDescription: Python Create dictionary if properties are found


rawDescription: Sort by last name

description: Sort by last name


code:
class Any(object):
    def __eq__(self, other):
        return True
ANYTHING = Any()

lst = [(1,5), (1,7), (2,3)]

rawDescription: Find tuple structure containing an unknown value inside a list


code:
x = 'green apple'
[c for word in x.split() for c in word]

rawDescription: Two for loops in a comprehensive list

description: Two for loops in a comprehensive list


code: df1.join(df2, on='Fruit')

rawDescription: Update a column in a data frame with the index of another column in another data frame in pandas python


rawDescription: type of variable through indentation of loops Python

description: Type of variable through indentation of loops Python


code:
import types

mymodule = types.ModuleType("mymodule")
mymodule.foo = "foo"

rawDescription: Purpose and usage of PyModule_New

description: Purpose and usage of PyModule_New


code:
def update2new(src_dest):

    print("Hi")
    fileProcess(src_dest)
    os.remove('outfile.csv')
    os.remove('new.csv')

    return src_dest

rawDescription: Why fuction's not returning value?

description: Why fuction's not returning value


rawDescription: Rearrange several sublists into two sublists


rawDescription: Split the list by consecutive common element


rawDescription: How to calculate percentage with Pandas' DataFrame

description: Calculate percentage with Pandas' DataFrame


code: zip(x,y)   # list(zip in py3

rawDescription: Merge 2 arrays vertical to tuple Numpy

description: Merge 2 arrays vertical to tuple Numpy


code:
def powerOfSum():
    listOfN = []
    for base in range(2, 100):
        num = base
        for _ in range(2, 10):
            num *= base
            if sum(map(int, str(num))) == base:
                listOfN.append(num)
    return sorted(listOfN)[:30]
powerOfSum()

rawDescription: Certain Power of Sum of Digits of N == N (running too slowly)


code: result = filter(lambda x: (x[0],) in l1, l2)

rawDescription: Merging list of tuples in python

description: Merging list of tuples in python


code:
def issorted(L):
    return all(x <= y for x, y in zip(L, L[1:]))

rawDescription: Python 3.3: Recursive version of a function


code:
from itertools import izip_longest

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

def process_chunk(chunk):
    "Return sequence of result lines.  Chunk must be iterable."
    for i, line in enumerate(chunk):
        yield 'file-line {1:03d}; chunk-line {0:02d}\n'.format(i, int(line))
    yield '----------------------------\n'

rawDescription: python read specific lines from file and continue

description: Python read specific lines from file and continue


code:
import pandas as pd
import io

data = """
ColumnA    columnB    columnC   columnD
  A          B          C          D
  A          B          C          D
  A          B          C          D
    """
data1 = """
ColumnE    columnF    columnG
  E          F          G
  E          F          G
  E          F          G
    """

df = pd.read_csv(io.StringIO(data), delimiter='\s+')
df1 = pd.read_csv(io.StringIO(data1), delimiter='\s+')

df['columnF'] = pd.Series(df1['columnF'])

print(df)

rawDescription: Adding column(s) from one dataframe to another python pandas


rawDescription: Possible to append multiple lists at once? (Python)


code:
for sec in map(SecurityType._make, reader(reader_input)):
    print(sec)

rawDescription: Is there a better way to do csv/namedtuple with urlopen?


code:
from urllib.parse import quote, unquote
quote('foo/../bar', safe='')
unquote(quote('foo/../bar', safe=''))

rawDescription: Reversible encoding of string to unix filename


rawDescription: python addition 2 digit number

description: Python addition 2 digit number


code:
d2 = {'key': {'owner': 'owner', 'type': 'type'}}
d2['key']['owner']
d2['key']['type']

rawDescription: Multiple Values for a single key in a dictionary


code:
import simplejson

class ml(object):

    def POST(self,data=None):
        # turn the JSON string into a Python data structure
        d = simplejson.loads(data)
        # do stuff
        results = alter_data(d)
        web.header('Content-Type','application/json')
        # send JSON back to the client
        return simplejson.dumps(results)

rawDescription: Bidirectional flow between D3.js frontend and Python Backend? / Interactive graphs in a website


code:
import sys
import os
import traceback
import ctypes
from ctypes import wintypes
import win32con
import win32api
import win32gui
import win32process

def enumWindowsProc(hwnd, lParam):
    if (lParam is None) or ((lParam is not None) and (win32process.GetWindowThreadProcessId(hwnd)[1] == lParam)):
        text = win32gui.GetWindowText(hwnd)
        if text:
            wStyle = win32api.GetWindowLong(hwnd, win32con.GWL_STYLE)
            if wStyle & win32con.WS_VISIBLE:
                print("%08X - %s" % (hwnd, text))

def enumProcWnds(pid=None):
    win32gui.EnumWindows(enumWindowsProc, pid)

def enumProcs(procName=None):
    pids = win32process.EnumProcesses()
    if procName is not None:
        bufLen = 0x100
        bytes = wintypes.DWORD(bufLen)
        _OpenProcess = ctypes.cdll.kernel32.OpenProcess
        _GetProcessImageFileName = ctypes.cdll.psapi.GetProcessImageFileNameA
        _CloseHandle = ctypes.cdll.kernel32.CloseHandle
        filteredPids = ()
        for pid in pids:
            try:
                hProc = _OpenProcess(wintypes.DWORD(win32con.PROCESS_ALL_ACCESS), ctypes.c_int(0), wintypes.DWORD(pid))
            except:
                print("Process [%d] couldn't be opened: %s" % (pid, traceback.format_exc()))
                continue
            try:
                buf = ctypes.create_string_buffer(bufLen)
                _GetProcessImageFileName(hProc, ctypes.pointer(buf), ctypes.pointer(bytes))
                if buf.value:
                    name = buf.value.decode().split(os.path.sep)[-1]
                    #print name
                else:
                    _CloseHandle(hProc)
                    continue
            except:
                print("Error getting process name: %s" % traceback.format_exc())
                _CloseHandle(hProc)
                continue
            if name.lower() == procName.lower():
                filteredPids += (pid,)
        return filteredPids
    else:
        return pids

def main(args):
    if args:
        procName = args[0]
    else:
        procName = None
    pids = enumProcs(procName)
    print(pids)
    for pid in pids:
        enumProcWnds(pid)

if __name__ == "__main__":
    main(sys.argv[1:])

rawDescription: Get the title of a window of another program using the process name


code:
@register.simple_tag(takes_context=True)
def current_time(context, format_string):
    timezone = context['timezone']
    return your_get_current_time_method(timezone, format_string)

rawDescription: Inheriting context variables inside custom template tags


code:
with open('final.csv', 'w') as f:
    f.write("SP,1,2,3\n")
    np.savetxt(f, temp, fmt="%i,%10.6e,%10.6e,%10.6e",delimiter=",")

rawDescription: Formatting a NumPy array

description: Formatting a NumPy array


code:
@add_unregister
@singledispatch
def foo(x):
    return 'default function'

foo.register(int, lambda x: 'function for int')
foo.registry
foo(1)
foo.unregister(int)
foo.registry
foo(1)

rawDescription: Unregister for singledispatch?

description: Unregister for singledispatch


code:
data = {'clad-den': 6.55, 'clad-temp': 578.0}
'MATERIAL 4 {clad-den} {clad-temp} 2'.format(**data)

rawDescription: python - replace string entry with a dictionary entry

description: Python - replace string entry with a dictionary entry


code:
m = line.split("¬")[4].split()
city = ' '.join(m[:-2])
state = m[-2]
zipCode = m[-1]

rawDescription: Parsing name and address information with differing number of spaces


code: mybytes = data[16:19]

rawDescription: Reading UDP Packets

description: Reading UDP Packets


code:
# Notice that pos is passed between calls and initially set to zero
def hamming(s1, s2, pos=0):
    # Are we after the last character already?
    if pos < len(s1):
        # Return one if the current position differs and add the result for the following positions (starting at pos+1) to that
        return (s1[pos] != s2[pos]) + hamming(s1, s2, pos+1)
    else:
        # If the end is already reached, the remaining distance is 0
        return 0

rawDescription: Finding the edit distance of two strings with recursion


code:
d_new = {}
for i,j in d.items():
    if j:
        d_new[i] = ''.join(str(x) for x in j[0])
    else:
        d_new[i] = ''

rawDescription: Stripping whitespace and joining multiple values stored in a single key in a dictionary


code:
from datetime import datetime
from time import time, mktime, strptime

def get_datetime( instr ):
  return datetime.fromtimestamp(mktime(strptime(instr, '%m-%d-%yT%H:%M:%S')))

# eg: get_datetime( '03-25-14T21:20:30' ) => datetime.datetime(2014, 3, 25, 21, 20, 30)

rawDescription: Split value into bins based on time

description: Split value into bins based on time


code:
def T(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return S(n - 1) + T(n - 1)

def S(n):
    if n == 0:
        return 1
    if n == 1:
        return 2
    return 2 * S(n - 1) + S(n - 2) + 4 * T(n - 1)

def tuple_func(n):
    return(S(n), T(n))

rawDescription: python programming help for equation

description: Python programming help for equation


rawDescription: Pandas sort by group aggregate and column


code: sorted("abcABC")

rawDescription: Heapsort not working in Python for list of strings using heapq module


rawDescription: Handle communication in multi layer application


code:
from collections import defaultdict

enrolls = StudentEnroll.objects.filter(semester=semester).values_list(
            'student__name', 'schedule__course', 'schedule__semester_period__name')
# Fetch all the enrolled data; this puts them in a list of tuples like
# [("Chris", "Math", "1st_Period"), ("Kim", "Science", "3rd_Period"), ... ]

periods = SemesterPeriod.objects.values_list('name', flat=True).order_by('name')
# get names of all periods in a flat list like: ['1st_Period', '2nd_Period', '3rd_Period']

period_dict = dict([(period,i) for i,period in enumerate(periods)])
# enumerate(periods) is a generator that has data in the form
# [(0, '1st_Period'), (1, '2nd_Period'), (2, '3rd_Period')] -- it enumerates the list.
# I then use a list comprehension to reverse it:
# [(period,i) for i,period in enumerate(periods)] is
# [('1st_Period', 0), ('2nd_Period', 1), ...]
# and then convert that list of paired tuples into a dictionary:
# {'1st_Period': 0, '2nd_Period': 1, '3rd_Period': 2}
# period_dict['3rd_Period'] returns 2; indicating that classes that are third period
# should fall into a students schedule in the third slot of the list
# (first element of list is 0)

students_dict = defaultdict(lambda: [""]*len(periods))
# a defaultdict that when a new student (not previously stored) is seen
# initializes that student to have an empty schedule.
# the empty schedule is an empty list that is as long as the number of periods,
# with each period an empty string ''
# student_dict once fully populated will be of form
# {'Chris': ['Math', '', 'Science'], 'Kim': ['', 'History', 'Science']}
# Note student_dict['Chris'] = ['Math', '', 'Science'] and
# student_dict['Chris'][0] = 'Math'.
for (student_name, course, period) in enrolls:
    students_dict[student_name][period_dict[period]] = course
    # go through the list of enrolls and assign courses to the schedule in the appropriate spots.

student_list = list(student_dict.items())
# [['Chris', ['Math', '', 'Science']], ['Kim', ['', 'History', 'Science']],]

rawDescription: Django: pivot data

description: Django: pivot data


rawDescription: Pandas - Convert Unbalanced Panel Data to Cross Section


code:
from pyspark.ml.feature import VectorIndexer, VectorAssembler

vector_indexer = VectorIndexer(inputCol="bar", outputCol="bar_indexed")
assembler = VectorAssembler(
    inputCols=["gender_vector", "bar_indexed", "foo"], outputCol="features")

encoded_df_with_indexed_bar = (vector_indexer
    .fit(encoded_df)
    .transform(encoded_df))

final_df = assembler.transform(encoded_df_with_indexed_bar)

rawDescription: Encode and assemble multiple features in PySpark


code:
class UserProfileSerializer(serializers.HyperLinkedModelSerializer):
    email = serializers.CharField(write_only=True)
    username = serializers.CharField(write_only=True)
    password = serializers.CharField(write_only=True)

    class Meta:
        ...

rawDescription: Can django restframework generics.ListCreateAPIView deal with one-to-one field?


code:
#####
# Define a 'Stock' class that can hold simple info
# about a security, like SEDOL and CUSIP info. This
# is mainly for debugging things and quickly getting
# info for a single security.
class MyStock():

    def __init__(self, ticker='None', sedol='None', country='None'):
        self.ticker = ticker
        self.sedol=sedol
        self.country = country
    ###

    def getData(self, end_date=datetime.date.today()+relativedelta.relativedelta(days=-1), num_dates = 30):
        return pandas.DataFrame(getStockSymbolData([self.ticker], end_date=end_date, num_dates=num_dates)[self.ticker])
    ###

#####
# Make some default stock objects for common stocks.
AAPL = MyStock(ticker='AAPL', sedol='03783310', country='US')
SAP  = MyStock(ticker='SAP',  sedol='484628',   country='DE')

rawDescription: How to take out the column index name in dataframe

description: Take out the column index name in dataframe


code:
from collections import Counter
a = Counter('123')
b = Counter('44144')
a
b
a | b
list(a | b)

rawDescription: counterdict unique values Python

description: Counterdict unique values Python


code:
#!/usr/bin/env ipython
#  This program plots the Stumpff functions C(z) and S(z)

import numpy as np
import pylab
from matplotlib.ticker import MaxNLocator

def C(z):
    if z > 0:
        return (1 - np.cos(z ** 0.5)) / z
    elif z < 0:
        return (np.cosh(np.sqrt(-z)) - 1) / -z
    return 0.5

def S(z):
    if z > 0:
        return (np.sqrt(z) - np.sin(z ** 0.5)) / np.sqrt(z) ** 3
    elif z < 0:
        return (np.sinh(np.sqrt(-z)) - np.sqrt(-z)) / np.sqrt(-z) ** 3
    return 1.0 / 6.0

if __name__ == '__main__':
    vC = np.vectorize(C)
    vS = np.vectorize(S)

    z = np.linspace(-50.0, 500.0, 100000.0)
    y = vC(z)
    y2 = vS(z)

    fig = pylab.figure()
    ax = fig.add_subplot(111)
    ax.plot(z, y, 'r')
    ax.plot(z, y2, 'b')
    pylab.legend(('$C(z)$', '$S(z)$'), loc = 0)
    pylab.xlim((-50, 0))
    pylab.ylim((0, 12))
    pylab.xlabel('$z$')
    pylab.gca().xaxis.set_major_locator(MaxNLocator(prune = 'lower'))
    pylab.savefig('stumpffneg50to0.eps', format = 'eps')

    fig2 = pylab.figure()
    ax2 = fig2.add_subplot(111)
    ax2.plot(z, y, 'r')
    ax2.plot(z, y2, 'b')
    pylab.legend(('$C(z)$', '$S(z)$'), loc = 1)
    pylab.xlim((0, 30))
    pylab.ylim((0, 0.5))
    pylab.xlabel('$z$')
    pylab.gca().xaxis.set_major_locator(MaxNLocator(prune = 'lower'))
    pylab.savefig('stumpff0to30.eps', format = 'eps')

    fig3 = pylab.figure()
    ax3 = fig3.add_subplot(111)
    ax3.plot(z, y, 'r')
    ax3.plot(z, y2, 'b')
    pylab.legend(('$C(z)$', '$S(z)$'), loc = 0)
    pylab.xlim((0, 500))
    pylab.ylim((0, 0.05))
    pylab.xlabel('$z$')
    pylab.gca().xaxis.set_major_locator(MaxNLocator(prune = 'lower'))
    pylab.savefig('stumpff0to500.eps', format = 'eps')
    pylab.show()

rawDescription: Python: calling another python script

description: Python: calling another python script


code:
import string
ascii_letters = set(map(ord, string.ascii_letters))
non_letters = ''.join(chr(i) for i in range(256) if i not in ascii_letters)
inputtext.translate(None, non_letters)

rawDescription: how to Ignore characters other than [a-z][A-Z]

description: Ignore characters other than [a-z][A-Z]


rawDescription: Alphabetically sorting a dictionary

description: Alphabetically sorting a dictionary


rawDescription: Searching for content between non-tag strings


code:
from dateutil import parser

dt = parser.parse(s)

rawDescription: Comparing dates in Python - how to handle time zone modifiers


code:
from datetime import datetime
d = datetime.now()
only_date, only_time = d.date(), d.time()
only_date
only_time

rawDescription: How do you extract only the date from a python datetime?

description: Extract only the date from a python datetime


code:
import collections

class UndoBuffer(object):
    def __init__(self,value,max_length=5):
        self.max_length=max_length
        self._buffer=collections.deque([value],max_length)
    @property
    def data(self):
        return self._buffer[-1]
    @data.setter
    def data(self,value):
        self._buffer.append(value)
    def restore(self,index):
        self.data=self._buffer[index]

rawDescription: How to build an undo storage with limit?

description: Build an undo storage with limit


code:
if event.key in (pygame.K_a, pygame.K_b, pygame.K_c):
    f(event.key)

rawDescription: Easier way of getting keyboard input in Pygame?


code:
def tree_operation(f):
    def recursive_wrapper(n, node):
       if node == None or node.data == n:
           # tree traversed to final point. do action for found element or
           # None
           return f(n, node)
       # try getting closer to interesting element
       elif node.data < n:
           return recursive_wrapper(n, node.right)
       else:
           return recursive_wrapper(n, node.left)
    return recursive_wrapper

@tree_operation
def search(n, node):
    if node == None:
        return False
    elif node.data == n:
        return True

@tree_operation
def insert(n, node):
    if node == None:
        # this obviously fail
        node.data = n
        node.left, node.right, node.middle = None
    elif node.data == n:
        insert(node.middle)

rawDescription: Higher order functions in tree traversal


rawDescription: checking to see if same value in two lists

description: Checking to see if same value in two lists


code:
from nltk import sent_tokenize, word_tokenize, pos_tag
sent = "John write His name as Ishmael"
tagged_sents = [pos_tag(word_tokenize(i)) for i in sent_tokenize(sent)]
added_annotation_sents = []
for sentence in tagged_sents:
    each_sent = []
    for word, pos in sentence:
            caps = "CAPITALIZED" if word[0].isupper() else None
            isnoun = "noun" if word[1][0] == "N" else "non-noun"
            each_sent.append((word,caps,isnoun))
    added_annotation_sents.append(each_sent)

added_annotation_sents

rawDescription: How to find elements of an array in Python and add more information to it

description: Find elements of an array in Python and add more information to it


rawDescription: Removing numbers.

description: Removing numbers.


code:
# Invocation
my_input = [2013, 'a', 'b', 'c'] # sequence does NOT have to be a tuple!
my_year = get_year(my_input) # returns 2013

rawDescription: Why do some Python functions have an extra set of parenthesis around the argument list?


code:
l = q.poll(0)
if not l:
    pass # no input
else:
    pass # there is some input

rawDescription: Python: How to peek into a pty object to avoid blocking?


code:
import itertools
for chars in itertools.product('hH', 'eE', 'lL', 'lL', 'oO'):
    print(''.join(chars))

rawDescription: How to get all capitalizations of a word?

description: Get all capitalizations of a word


rawDescription: random subsampling of the majority class

description: Random subsampling of the majority class


code:
import random
import string
allowed_chars = ''.join((string.lowercase, string.uppercase, string.digits))
unique_id = ''.join(random.choice(allowed_chars) for _ in range(32))
unique_id

rawDescription: Django package to generate random alphanumeric string


code:
import urllib2
from BeautifuSoup import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://www.cbssports.com/nba/draft/mock-draft').read())

# if there's only one table with class = data
table = soup.find('table', attrs = {'class' : 'data'})

# if there are multiple tables with class = data
table = soup.findAll('table', attrs = {'class' : 'data'})[n]
# suppose you need the n-th table of the list returned

rows = table.findAll('tr') # gives all the rows, you can set attrs to filter

rawDescription: How do I find an element with a certain class in a web page with BeautifulSoup?

description: Find an element with a certain class in a web page with BeautifulSoup


code:
def next_weekday(d, weekday):
    days_ahead = weekday - d.weekday()
    if days_ahead <= 0:
        days_ahead += 7
    return d + datetime.timedelta(days_ahead)

rawDescription: Get end of week based on date column

description: Get end of week based on date column


code: ' '.join(map(str, [el.tail for el in td_elem.iterchildren() if el.tail]))

rawDescription: Parsing lxml.etree._Element contents

description: Parsing lxml.etree._Element contents


rawDescription: better way to drop nan rows in pandas

description: Better way to drop nan rows in pandas


code: R = A - np.roll(A, -2, axis=0) # 1000x6 array of all differences

rawDescription: I am using a numpy array of randomly generated ordered pairs, I need to determin if the ordered pairs are different types of triangles


rawDescription: Extracting data from HTML table

description: Extracting data from HTML table


code: timeseries['timeblock'] = timeseries['timeblock'].map(lambda x: int(x/300)+1)

rawDescription: Create five minute time blocks (Pandas/Python)


rawDescription: Python magic function, how does it work?

description: Python magic function, how does it work


code:
def addterm(f, pos):
  def g(x):
    return f(x)+1/((x-pos)*(x-pos))
  return g

def zero(x): return 0
f = zero
for pos in poslist:
  f=addterm(f, pos)

rawDescription: Function Design

description: Function Design


code:
if not line.strip():
   continue

rawDescription: Need help to read a file in python

description: Need help to read a file in python


code: map(lambda s: s.split(','))

rawDescription: Parsing a CSV using python's toolz package


code:
from Tkinter import *
p1A=Button

def init(root):
    global p1A
    p1Buzz = Button(root, text = "P1 BUZZ", command = buzzed)
    p1Buzz.pack()
    p1A = Button(root, text = "A")
    p1A.config(state='disabled')
    p1A.pack()

def buzzed():
    p1A.config(state='normal')

root=Tk()
init(root)
root.mainloop()

rawDescription: Disabling button state from other method


code:
type(j)
type(1j)

rawDescription: Complex number in python

description: Complex number in python


code:
for x,y in product(range(X), range(Y)):
    function(x,y)

rawDescription: Pythonic shortcut for doubly nested for loops?


code:
print(BeautifulSoup('<x><c name="b1"><d value="a®"/></c></x>',
    features = "xml").prettify())

rawDescription: How to get Python bs4 to work properly on XML?

description: Get Python bs4 to work properly on XML


code: [int(e) for e in some_list]

rawDescription: How to remove comma from list in python

description: Remove comma from list in python


code:
lst = [random.random() for i in xrange(5000000)]
set1 = set(lst)    # takes 2.4 seconds

set2 = set()       # takes 3.37 seconds
for item in lst:
    set2.add(item)

rawDescription: Performance comparison: insert vs build Python set operations


code: url( r'your pattern', CategoryView.as_view(), name='whatever')

rawDescription: Switching to class-based list_detail

description: Switching to class-based list_detail


rawDescription: Avoiding numpy loops while calculating intersections


code: Counter(l)

rawDescription: Easy way to find what item repeated in list


code:
address = fields[0]
isp = fields[8]
domain = fields[-1]

rawDescription: removing blank lines python

description: Removing blank lines python


rawDescription: Pandas join/merge 2 dataframes using date as index


rawDescription: Re-write loop to assign a number to every row in a column


rawDescription: effectively preprocessing record array from genfromtxt

description: Effectively preprocessing record array from genfromtxt


code:
import test
test.foo(["a", "b", "c"])

rawDescription: Python C wrapper for reading variable argument lengths


code:
class AttributeHelperMixin():
  def GetMethods(self):
    return {funcname: func
            for funcname, func in self.__class__.__dict__.items()
            if hasattr(func, '__dict__')
           }.items()

  def HasAttribute(self, method):
    if method.__dict__.__contains__(Attribute.AttributesMemberName):
      attributeList = method.__dict__[Attribute.AttributesMemberName]
      return (isinstance(attributeList, list) and (len(attributeList) != 0))
    else:
      return False

  def GetAttributes(self, method):
    if method.__dict__.__contains__(Attribute.AttributesMemberName):
      attributeList = method.__dict__[Attribute.AttributesMemberName]
      if isinstance(attributeList, list):
        return attributeList
    return list()

rawDescription: Is it possible to implement .NET-like attributes in Python?


code:
myuser
mypass

rawDescription: Python Login: Error reading Text file

description: Python Login: Error reading Text file


rawDescription: spark custom sort in python

description: Spark custom sort in python


code:
@classmethod
def __import_something_from_xml(cls, data):
    #logic
    return a, b, c

rawDescription: split up classmethods in python

description: Split up classmethods in python


rawDescription: how to sort python dict by its value?

description: Sort python dict by its value


code:
import datetime as dt
import dateutil.rrule as RR

date0 = dt.datetime(2014, 10, 3)
date1 = dt.datetime(2014, 8, 26)

start = min([date0, date1])
end = max([date0, date1])
dow = RR.weekday(date0.weekday())
print(RR.rrule(RR.WEEKLY, byweekday=dow, dtstart=start).between(start, end))

rawDescription: Any way to use rrule going backwards

description: Any way to use rrule going backwards


code: pairs = {(k,v) for k,vs in agents.iteritems() for v in vs}

rawDescription: Efficient algorithm for pairwise computation


code:
from collections import namedtuple
MyObject = namedtuple('MyObject', 'color number')
my_obj = MyObject(color="yellow", number=10)
my_obj.color
my_obj.number

rawDescription: String-based indices in tuple Python

description: String-based indices in tuple Python


code:
for j in range(0,250):
    spyy = float(col[1]) # here you're grabbing the same second item 250 times
    max1 = max(max1,spyy) # setting the new max to the same value 250 times
    min1 = min(min1,spyy) # setting the new min to the same value 250 times
    file_reader.next() # now you advance, but col is the same so ...
    # it's like you're skipping 250 lines

rawDescription: Manipulating csv files in python

description: Manipulating csv files in python


code:
print("Updating: . . ")
W.position = X,Y                      # Updating the coordinates
print(W.position)

rawDescription: Updating Window position in PySDL2 (Help!)


rawDescription: SciPy zeta function returns wildly large value


code:
def create(cls):
    class DynamicSearchIndex(indexes.SearchIndex, indexes.Indexable):
        # What ever fields are needed go here
        def get_model(self):
            return cls
    return SubclassedConceptIndex

rawDescription: Programmatically create haystack index

description: Programmatically create haystack index


code:
from dis import dis
dis(compile("if True: pass", "string", "exec"))
dis(compile("if (True): pass", "string", "exec"))

rawDescription: Difference between having and not having parenthesis in if statements


rawDescription: LookupError: unknown encoding: idna - only from subprocess.call


code:
class Base(object):
    def do( self ):
        self._member1 = 0
        self._member2 = 1

def add_do(a, b):
    def do(self):
        Base.do(self)
        self._member3 = a
        self._member4 = b
    def deco(cls):
        return type(cls.__name__, (Base,), {'do': do})
    return deco

@add_do(0, 1)
class Derived1(Base): pass

@add_do(2, 3)
class Derived2(Base): pass

@add_do(9, 3)
class Derived3(Base): pass

rawDescription: Python: Simplify inheritor method

description: Python: Simplify inheritor method


code:
from operator import itemgetter

data = {'Role Name': ['Administrator'],
        'Approval': ['N', 'N', 'N', 'N', 'N'],
        'Functions': ['Transfer Amount', 'Withdraw Amount', 'Admin Action', 'Create Users', 'User Deletion'],
        'Approve': ['N', 'Y', 'N', 'N', 'N'],
        'Action': ['N', 'Y', 'Y', 'Y', 'Y']}

for key in ['Action', 'Approval', 'Approve']:
    data[key] = map(itemgetter(1), sorted(zip(data['Functions'], data[key])))

data['Functions'] = sorted(data['Functions'])

rawDescription: Python: Sorting list in dictionary by key name


code:
call1 = mock.call('test', example=3)
call2 = mock.call('test', example=4, value=5)
call_args_list = [call1, call2]
[(item[1], item[2]) for item in call_args_list]

rawDescription: Remove call() when using Mock

description: Remove call() when using Mock


code:
pattern = re.compile(r"(?=(([01]+)\2+))")
for match in pattern.finditer("11010"):
    print(match.group(1), "at {}:{}".format(*match.span(1)))

rawDescription: Python Regex to find reccuring patterns or binary strings


code:
with open('myInputFileName') as myInputFile, \
     open('myOutputFileName', 'w') as myOutputFile:
  for withStatute, cite in eachCite(myInputFile):
    if withStatute:
      myOutputFile.write("found cite with statute:\n")
      myOutputFile.write(cite)

rawDescription: Extracting parts of text between specific delimiters from a large text file with custom delimiters and writing it to another file using Python


code:
label=r"\makebox[4cm]{$t^2$ \hfill $0 \leq t \leq 1$}"
label=r"\makebox[4cm]{$1$ \hfill $1 < t \leq 2$}"
label=r"\makebox[4cm]{$3 - t$ \hfill $2 < t \leq 3$}"

rawDescription: Uniform spacing with Matplotlib and TeX

description: Uniform spacing with Matplotlib and TeX


code: yChannel = [[] for dummy in range(4)]

rawDescription: Python populating all the elements of a 2D list (or array) when I change only one


code:
request = QNetworkRequest(QUrl("http://www.google.com/images/srpr/logo1w.png"))
reply = view.page().networkAccessManager().get(request)
byte_array = reply.readAll()
image = QImage()
image.loadFromData(byte_array)
label = QLabel()
label.setPixmap(QPixmap(image))
label.show()

rawDescription: Parsing HTML using QWebElement, how to extract an image?


code:
def gt5(x):
    return x > 5

rawDescription: Python: Pass inequality as string in dict for evaluation


code: a = zip(range(10), range(10))

rawDescription: How to unzip an iterator?

description: Unzip an iterator


code:
for prod_emp in prodemployees:
    prod_emp = prod_emp.split()
    prod, emp = prod_emp[0], prod_emp[1:]

rawDescription: Python : split a list dynamically

description: Python : split a list dynamically


code:
{
    body:
    {
        u'@copyright': u'All data copyright Unitrans ASUCD/City of Davis 2015.',
        u'predictions':
        {
            u'@routeTitle': u'A',
            u'@dirTitleBecauseNoPredictions': u'Outbound to El Cemonte',
            u'@agencyTitle': u'Unitrans ASUCD/City of Davis',
            u'@stopTag': u'22258',
            u'@stopTitle': u'Silo Terminal & Haring Hall (WB)',
            u'@routeTag': u'A',
            u'message':
            [
                {
                    u'@text': u'Weekend service is running Monday-Wednesday Dec. 28-30.',
                    u'@priority': u'Normal'
                },
                {
                    u'@text': u'The A-line and Z-line do not run on weekends. Use O-line for weekend service.',
                    u'@priority': u'Normal'
                }
            ]
        }
    }
}

rawDescription: How to remove select characters from xml parse in python / django?

description: Remove select characters from xml parse in python / django


code:
class Complex(object):
    def __init__(self, realpart=0, imagpart=0):
        self.realpart = realpart
        self.imagpart = imagpart

rawDescription: python class namespace and init function

description: Python class namespace and init function


code:
from os import path
out= check_output(["tail","-n","1",path.expanduser("~/.bash_history")])
print(out)

rawDescription: Run shell builtin command in Python

description: Run shell builtin command in Python


code: sorted(a, key=lambda p: map(str.strip, p.split(',')[::-1]))

rawDescription: Ordering a list according to hierarchy

description: Ordering a list according to hierarchy


rawDescription: How do I decide which way to backtrack in the Smith–Waterman algorithm?

description: Decide which way to backtrack in the Smith–Waterman algorithm


code:
d = {}
with open('yourfile.tsv') as tsvfile:
  next(tsvfile)
  for line in tsvfile:
    row = line.split()
    componentid, subcomponent, measurement = row[0], row[1], float(row[2])
    if not componentid in d:
      d[componentid] = {'subcomponents': [subcomponent], 'measurement': measurement}
    else:
      assert measurement == d[componentid]['measurement']
      d[componentid]['subcomponents'] += [subcomponent]

rawDescription: Sorting and reorganizing a CSV file as a python dictionary


code:
#!/usr/bin/env python
# test.py
class A(object):
    def __init__(self, id):
        self.id = id

class B(A):
    def __eq__(self, other):
        return self.id == other.id

@profile
def main():
    list_a = []
    list_b = []
    for x in range(100000):
        list_a.append(A(x))
        list_b.append(B(x))

    ob_a = A(1)
    ob_b = B(1)
    for ob in list_a:
        if ob == ob_a:
            x = True
        if ob is ob_a:
            x = True
        if ob.id == ob_a.id:
            x = True
        if ob.id == 1:
            x = True
    for ob in list_b:
        if ob == ob_b:
            x = True
        if ob is ob_b:
            x = True
        if ob.id == ob_b.id:
            x = True
        if ob.id == 1:
            x = True

if __name__ == '__main__':
    main()

rawDescription: Optimising Python dictionary access code


code:
words = ['man','map','human']
res = []
for letter in (letter for word in words for letter in word):
    if letter not in res:
        res.append(letter)

rawDescription: Return only single occurrences of a string


code:
lst = [-4, 3, -8, -9]
map(cmath.sqrt, lst)
[cmath.sqrt(x) for x in lst]

rawDescription: Square root of a negative array Python

description: Square root of a negative array Python


rawDescription: Gensim Word2vec storing attribute syn0norm


rawDescription: Extract a column from a DataFrame

description: Extract a column from a DataFrame


rawDescription: numpy.ndarray sent as argument doesn't need loop for iteration?

description: Numpy.ndarray sent as argument doesn't need loop for iteration


code:
from elixir import *
import auth as auth
au = auth.UserAuth()

metadata.bind = 'mysql://' + au.user + ':' + au.password + '@localhost/' + au.database
metadata.bind.echo = True

class Investigator(Entity):
    id = Field(Integer, primary_key = True)
    prefix = Field(Text)
    fname = Field(Text)
    lname = Field(Text)
    email = Field(Text)
    using_options(tablename = 'investigators')

    def __repr__ (self):
        return '%d' %(self.id)

class Protocol(Entity):
    id = Field(Integer, primary_key = True)
    irb_no = Field(Text)
    title = Field(Text)
    investigator = ManyToOne('Investigator', colname='investigator_id')
    action_date = Field(Date)
    action = Field(Text)
    approved = Field(Integer)
    using_options(tablename = 'protocols')

    def __repr__ (self):
        return '%d' %(self.id)

rawDescription: Using python and elixir to send emails utilizing db tables with foreign keys


code:
def sum(*values):
    s = 0
    for v in values:
        s = s + v
    return s

s = sum(1, 2, 3, 4, 5)

rawDescription: What does the Star operator mean in Python?


code:
(df
    .select("user_id", struct(col("product_id"), col("timestamp_gmt")))
    .rdd.groupByKey()
    .toDF(["user_id", "purchase_info"]))

rawDescription: Pyspark: Rename a dictionary key which is within a DataFrame column


rawDescription: Add second axis to polar plot

description: Add second axis to polar plot


rawDescription: Commutative combination of elements of two lists


rawDescription: Plotting quantiles, median and spread using scipy and matplotlib


code:
import sys

if sys.byteorder == 'little':
    values.byteswap()  # convert to big-endian before writing to a file
values.tofile(fileobj)

rawDescription: Pack 4 byte integers into bytearray or array


code:
class Jagged3DBitArray(object):
    def __init__(self, xsize, ysize, zsize):
        self.lll = [[bitarray(zsize) for y in range(ysize)]
                    for x in range(xsize)]
    def __getitem__(self, key):
        x, y, z = key
        return self.lll[x][y][z]
    def __setitem__(self, key, value):
        x, y, z = key
        self.lll[x][y][z] = value

class Fixed3DBitArray(object):
    def __init__(self, xsize, ysize, zsize):
        self.xsize, self.ysize, self.zsize = xsize, ysize, zsize
        self.b = bitarray(xsize * ysize * zsize)
    def __getitem__(self, key):
        x, y, z = key
        return self.b[x + y * self.ysize + z * self.ysize * self.zsize]
    def __setitem__(self, key, value):
        x, y, z = key
        self.b[x + y * self.ysize + z * self.ysize * self.zsize] = value

rawDescription: python multidimensional boolean array?

description: Python multidimensional boolean array


code: base_string % values

rawDescription: String formatting options: pros and cons


code:
import requests

session = requests.session()
response = session.post('http://www.camp.bicnirrh.res.in/predict/hii.php',
               files={'userfile': ('fasta.txt', open('fasta.txt'), 'text/plain')},
               data={'algo[]':'svm'})

rawDescription: POST request via requests (python) not returning data


code: table.Cell(Row = 1, Column= 1)

rawDescription: How to read contents of an Table in MS-Word file Using Python?

description: Read contents of an Table in MS-Word file Using Python


code:
s = SomeSpriteClass()
s.rect = s.rect.move(100, 0)

rawDescription: Pygame in-place methodes

description: Pygame in-place methodes


code:
import itertools
n = 4
formula = [[1, -2, 3], [-1, 3], [-3], [2, 3]]

allorderings = itertools.product ([False, True], repeat = n)

for potential in allorderings:
    print ("Initial values:", potential)
    allclauses = []
    for clause in formula:
        curclause = []
        for item in clause:
            x = potential[abs (item) - 1]
            curclause.append (x if item > 0 else not x)
        cal = any (curclause)
        allclauses.append (cal)
    print ("Clauses:", allclauses)
    formcheck = all (allclauses)
    print ("This combination works:", formcheck)

rawDescription: np complete algorithm in python [solved]

description: Np complete algorithm in python [solved]


rawDescription: Click event is sent immediately after I start application (PySide and Python)


code:
mask = ' '.join(('_' for i in range(len('jabberwocky'))))
mask

rawDescription: Letter guessing game in python

description: Letter guessing game in python


code:
mrows = matrix.shape[0]
prows = pattern.shape[0]
out = np.einsum('ijk->i',(pattern[:,None,:] == matrix[None,:,:]).astype(int))/mrows
# OR out = np.einsum('ijk->i',(pattern[:,None,:] == matrix[None,:,:])+0)/mrows

rawDescription: Numpy matrix row comparison

description: Numpy matrix row comparison


rawDescription: efficient sign function in python for case of periodic boundary conditions

description: Efficient sign function in python for case of periodic boundary conditions


code:
from .meta import Base

class Foo(Base):
    pass

rawDescription: How do I split models.py into different files for different models in Pyramid?

description: Split models.py into different files for different models in Pyramid


code:
#! /usr/bin/python3.2

colours = {'white': 7, 'green': 2, 'blue': 4, 'black': 0, 'yellow': 3}

class Tile:
    data = {'.': ('Floor', 'white', True),
        'Y': ('Forest', 'green', False),
        '~': ('Water', 'blue', False) }

    def __init__ (self, code, position):
        self.code = code
        self.position = position
        self.name, self.colour, self.passable = Tile.data [code]

    def __str__ (self):
        return '\x1b[{}m{}'.format (30 + colours [self.colour], self.code)

class GameObject:
    #here got he general interfaces common to all game objects
    def __str__ (self):
        return '\x1b[{}m{}'.format (30 + colours [self.colour], self.code)

class Door (GameObject):
    def __init__ (self, code, position, colour, key):
        self.code = code
        self.position = position
        self.colour = colour
        self.key = key

    def close (self): pass
        #door specific interface

class Dragon (GameObject):
    def __init__ (self, code, position, colour, stats):
        self.code = code
        self.position = position
        self.colour = colour
        self.stats = stats

    def bugger (self): pass
        #dragon specific interface

class Map:
    def __init__ (self, codeMap, objects):
        self.tiles = [ [Tile (c, (x, y) ) for x, c in enumerate (line) ] for y, line in enumerate (codeMap) ]
        self.objects = {obj ['args'] ['position']: obj ['cls'] (**obj ['args'] ) for obj in objects}

    def __str__ (self):
        return '\n'.join (
            ''.join (str (self.objects [ (x, y) ] if (x, y) in self.objects else tile)
                for x, tile in enumerate (line) )
            for y, line in enumerate (self.tiles)
            ) + '\n\x1b[0m'

mapRouge = ['~~~~~~~~~~',
            '~~~~.....Y',
            'YYYYY.YYYY',
            'YYYY....YY']

objects = [ {'cls': Door,
        'args': {'code': '.', 'position': (5, 2), 'colour': 'black',
        'key': 'Ancient Key of Constipation'} },
    {'cls': Dragon,
        'args': {'code': '@',  'position': (7, 3), 'colour': 'yellow',
        'stats': {'ATK': 20, 'DEF': 20} } } ]

theMap = Map (mapRouge, objects)
print (theMap)

rawDescription: Use composition, strategy pattern and dictionnary to better instatiate class stored in dictionnary


code: table = ["header 1", "header 2"]

rawDescription: Generating HTML tables where more items have one key asnd must fit on the same row


code:
for sentence in master_list:
    # regex_patterns maps directly onto terms (strictly speaking it's one-to-one and onto)
    for term, pattern in zip(terms, regex_patterns):
        if re.search(pattern, sentence, flags=re.IGNORECASE):
            # process term (put it in the db)
            print('TERM: {0} FOUND IN: {1}'.format(term, sentence))

rawDescription: Best way to match a large list against strings in python

description: Match a large list against strings in python


code: if not line.startswith("Maths") : continue

rawDescription: comparing 2 csv files starting from 1st line of first file with the 2nd line of the second file-Python

description: Comparing 2 csv files starting from 1st line of first file with the 2nd line of the second file-Python


code: result = z[z_idx].diagonal()

rawDescription: Selecting multiple elements from an 2d array using a 1d array in numpy


code: your_json = YourModelSerializer(YourModel.objects.all(), many=True).data

rawDescription: zip and download Django Rest Framework generated json file

description: Zip and download Django Rest Framework generated json file


code: results = root.xpath("//*[starts-with(local-name(), 'TEXT')]")

rawDescription: lxml find tags by regex

description: Lxml find tags by regex


code:
from lxml import etree

root = etree.XML('
Hello
World
')
print(etree.tostring(root, method='xml'))
print(etree.tostring(root, method='html'))
print(etree.tostring(root, method='text'))

rawDescription: Why is etree.tostring() not working for different methods?


code:
try:
    return the_list[i]
except IndexError:
    return None

rawDescription: Get value at list/array index or "None" if out of range in Python


code:
import sys
from PIL import Image

img = Image.open(sys.argv[1])
width, height = img.size
m = -0.5
xshift = abs(m) * width
new_width = width + int(round(xshift))
img = img.transform((new_width, height), Image.AFFINE,
        (1, m, -xshift if m > 0 else 0, 0, 1, 0), Image.BICUBIC)
img.save(sys.argv[2])

rawDescription: How does perspective transformation work in PIL?


code:
import logging
import os
import re
import sys

from sre_parse import Pattern

class DuplicateFilter(logging.Filter):
    def __init__(self, match_against, reset_at_message, hide_at_count=5, name=''):
        super(DuplicateFilter, self).__init__(name)

        if isinstance(match_against, Pattern):
            self.match_against = match_against
        else:
            self.match_against = re.compile(match_against)

        if isinstance(reset_at_message, Pattern):
            self.reset_at_message = reset_at_message
        else:
            self.reset_at_message = re.compile(reset_at_message)

        self.hide_at_count = hide_at_count

        self.count = 0

    def filter(self, record: logging.LogRecord):
        _ = super(DuplicateFilter, self).filter(record)
        if not _:
            return _

        msg = record.getMessage()

        if self.match_against.match(msg):
            self.count += 1

            if self.count >= self.hide_at_count:
                return False

        elif self.reset_at_message.match(msg):
            record.msg = os.linesep.join([
                '{:d} more generated'.format(self.count - self.hide_at_count),
                record.msg
            ])
            self.count = 0

        return True

handler = logging.StreamHandler(sys.stdout)
handler.addFilter(DuplicateFilter('Filter me!', 'Reset at me'))

logging.basicConfig(level='INFO', handlers=[handler, ])

log = logging.getLogger()

for _ in range(10):
    log.info('Filter me!')

log.info('Reset at me')

for _ in range(3):
    log.info('Filter me!')

rawDescription: How to limit the number of identical log messages?

description: Limit the number of identical log messages


code:
from PIL import Image
im = Image.open("bride.jpg")
im.show()

rawDescription: Getting Width and Height of an Inputted Picture in Python


rawDescription: Is it possible for the Python compiler to optimize away some integer arithmetic?


code:
import os
import time

class RotatingFileOpener():
    def __init__(self, path, mode='a', prepend="", append=""):
        if not os.path.isdir(path):
            raise FileNotFoundError("Can't open directory '{}' for data output.".format(path))
        self._path = path
        self._prepend = prepend
        self._append = append
        self._mode = mode
        self._day = time.localtime().tm_mday
    def __enter__(self):
        self._filename = self._format_filename()
        self._file = open(self._filename, self._mode)
        return self
    def __exit__(self, *args):
        return getattr(self._file, '__exit__')(*args)
    def _day_changed(self):
        return self._day == time.localtime().tm_mday
    def _format_filename(self):
        return os.path.join(self._path, "{}{}{}".format(self._prepend, time.strftime("%Y%m%d"), self._append))
    def write(self, *args):
        if self._day_changed():
            self._file.close()
            self._file = open(self._format_filename())
        return getattr(self._file, 'write')(*args)
    def __getattr__(self, attr):
        return getattr(self._file, attr)
    def __iter__(self):
        return iter(self._file)

rawDescription: Create log file one every day in python

description: Create log file one every day in python


code:
matchOCR("Ro?co?er", "?flcopt?")
matchOCR("Ro?co?er", "?flcopt?z")
matchOCR("Ro?co?er", "?flc?pt?")
matchOCR("Ro?co?e?", "?flc?pt?")

rawDescription: elegant way to match two wildcarded strings

description: Elegant way to match two wildcarded strings


code:
string = string.replace("'", "") # replaces single quotes in the string with nothing
string = string.replace('"', '') # for double quotes

rawDescription: Removing string quotations without slicing?


code:
from collections import Counter
c = Counter(b)

rawDescription: how to find whether this python list within list contains duplicates or not?

description: Find whether this python list within list contains duplicates or not