code:
tree = lambda: defaultdict(tree)

my_tree = tree()
my_tree['a']['b']['c']['d']['e'] = 'whatever'

rawDescription: How to initialize nested dictionaries in Python

description: Initialize nested dictionaries in Python


code:
# example
json.dump([1,2,3], fp)
json.dump({"name": "abc"}, fp)
json.dump(33, fp)
# content of file
# [1, 2, 3]{"name": "abc"}33

rawDescription: Loading and reading JSON file is very slow after writing in python


code:
re.search(r'([a-z])\1', 'ugknbfddgicrmopn').group()
[i+i for i in re.findall(r'([a-z])\1', 'abbbbcppq')]

rawDescription: Find "one letter that appears twice" in a string


rawDescription: Remove selected text using regular expressions


code:
G = nx.Graph()
G.add_nodes_from([0,1,2])
n0 = emoji.emojize(':thumbsup:',use_aliases=True)
n1 = emoji.emojize(':sob:',use_aliases=True)
n2 = emoji.emojize(':joy:',use_aliases=True)
labels ={0:n0,1:n1,2:n2}
nx.draw_networkx(G,labels=labels, node_color = 'w', linewidths=0, with_labels=True, font_family = 'Symbola' ,font_size = 35)
plt.show()

rawDescription: Substitute node labels with emoji using networkX in Python


code:
@staticmethod
def my_static_method(foo):
   ...

rawDescription: python: When to use static method over class method?

description: Python: When to use static method over class method


rawDescription: Shorten the IF condition for 2 variables (same comparison)


code:
t, offset_sign, offset = t[:-6], t[-6], t[-5:]
t = time.strptime(t, "%Y-%m-%dT%H:%M:%S")
offset = time.strptime(offset, "%H:%M")

rawDescription: Python : Convert time format to unix_timeformat


code: Gtk.ListStore(*(x for bar in spam))

rawDescription: Generating variable amounts of parameters for function call in code


code:
pat0 = re.compile(r'=(?: A\d+)+')
pat1 = re.compile(r' A(\d+)')

m = pat0.search("= A1 A2 A3 A4")
if not m:
    print("input string not what was expected")
else:
    s = m.group(0)
    lst = re.findall(pat, s)

rawDescription: RegEx in Python matching multiple substrings using one group


code:
{'type':'ineq', 'fun': lambda x: np.sum(x, 0) - 1}  # row sum >= 1
{'type':'ineq', 'fun': lambda x: 1 - np.sum(x, 0)}  # row sum <= 1

rawDescription: Element-wise constraints in scipy.optimize.minimize


code:
country = ["United States"]
i = 0
name = ["a", "b", "c"]
age = [1, 2, 3]
city = ["aaa", "bbb", "ccc"]
v = (country[i], )
[t + v for t in zip(name, age, city)]

rawDescription: adding the same variable to a list of tuples

description: Adding the same variable to a list of tuples


rawDescription: How to find sequence in text file

description: Find sequence in text file


rawDescription: Using Eval in Python to create class variables


code: result = [(i.home, i.away) for i in fixtures[:5]]

rawDescription: How to slice a list of objects in association of the object attributes

description: Slice a list of objects in association of the object attributes


code:
# Client
import socket

HOST = '127.0.0.1'             # The remote host, but here using localhost
PORT = 50007                   # The port used by both the client and server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(b'1')                # a bytes object
data = s.recv(1)               # Receive data from the socket with bufsize of 1
s.close()
print('Received', repr(data))  # confirm receipt

rawDescription: ctypes in python size with the `sys.getsizeof(Var)` method vs `ctypes.sizeof(Var)`

description: Ctypes in python size with the `sys.getsizeof(Var)` method vs `ctypes.sizeof(Var)`


code:
client = pymongo.MongoClient()
client.admin.command('enableSharding', 'dbname')

rawDescription: Looking for a way to shard a MongoDB collection from within Python code


rawDescription: Specific Permutations

description: Specific Permutations


code: import LDconfig

rawDescription: Creating a file to lookup paths and file names?


code:
next = driver.find_element_by_xpath("//li[@class='next']/a")
prev = driver.find_element_by_xpath("//li[@class='previous']/a")

rawDescription: python, locating and clicking a specific button with selenium

description: Python, locating and clicking a specific button with selenium


code:
from itertools import groupby
# "chunk" our input file, delimited by blank lines
with open(filename) as f:
    res = [list(g) for b,g in groupby(f, lambda x: bool(x.strip())) if b]

rawDescription: parsing a .srt file with regex

description: Parsing a .srt file with regex


code: data = [[row[0]]+row[1].tolist() for row in data]

rawDescription: Writing Multiple Rows to CSV using Numpy Arrays without Brackets?


code: client.admin.command('shardCollection', 'dbname.collectionname', key={'shardkey': 1})

description: Looking for a way to shard a MongoDB collection from within Python code


code:
from threading import Timer

class RepeatingTimer(Timer):
    def run(self):
        while not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
            self.finished.wait(self.interval)

t = RepeatingTimer(30.0, self.mqConn.heartbeat_tick)
t.start() # every 30 seconds, call heartbeat_tick

# later
t.cancel() # cancels execution

rawDescription: How to create a background threaded on interval function call in python?

description: Create a background threaded on interval function call in python


code:
def find_re_results(findme, separator, s):
    p1=re.compile(findme)
    p2=re.compile(separator)
    m=p1.search(s)
    if m:
        li=p2.split(s[m.start():], maxsplit=1)
    else:
        return ''
    try:
        return li[1]
    except IndexError:
        return ''

rawDescription: Returning NoneType vs. returning "" in re.search


code: row = search_in_table(table_name, search_for)[0]

rawDescription: How do I satisfy the Unused Variable rule from PEP8 if I don't need a variable returned by a function?

description: Satisfy the Unused Variable rule from PEP8 if I don't need a variable returned by a function


code:
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-f", "--filename",
                  metavar="FILE", help="write output to FILE"),

rawDescription: Python optparse metavar

description: Python optparse metavar


code:
import numpy as np
def d(x, p):
    return np.sum((p-np.array([x,2*np.sin(x)]))**2)

def diff_d(x, p):
    return -2 * p[0] + 2 * x - 4 * p[1] * np.cos(x) + 4 * np.sin(2*x)

rawDescription: Find global minimum using scipy.optimize.minimize


code:
from collections import namedtuple
from enum import Enum

Body = namedtuple("Body", ["mass", "radius"])

class Planet(Body, Enum):

    MERCURY = Body(mass=3.303e+23, radius=2.4397e6)
    VENUS   = Body(mass=4.869e+24, radius=6.0518e6)
    EARTH   = Body(mass=5.976e+24, radius=3.3972e6)
    # ... etc.

rawDescription: Can named arguments be used with Python enums?


code: '\n'.join(['\n'.join(item) for item in zip(['e_'+str(num) for num in range(1, len(new)+1)], new)])

rawDescription: cut a string with duplicates

description: Cut a string with duplicates


code:
args = {'a': 1, 'b': 2}
s = Struct(**args)
s
s.a
s.b

rawDescription: Convert Python dict to object?

description: Convert Python dict to object


code:
def filter_rows(tag):
    return tag.name == "tr" and \
           tag.find_previous_sibling("tr", text="RED BOX") and \
           tag.find_next_sibling("tr", text="GREEN BOX")

for row in soup.find_all(filter_rows):
    print([td.get_text(strip=True) for td in row.find_all("td")])

rawDescription: beautifulsoup table tree: find all tr between two objects?

description: Beautifulsoup table tree: find all tr between two objects


code:
import re
filter = {'id_number': re.compile("^1234[8-9]")}

rawDescription: python pass regex to mongo via http

description: Python pass regex to mongo via http


rawDescription: Clean way to get the "true" stem of a Path object?


rawDescription: what is the default python logging formatter

description: What is the default python logging formatter


code:
def flattenDict(d):
    node_map = {}
    node_path = []
    def nodeRecursiveMap(d, node_path):
        for key, val in d.items():
            if type(val) is not dict: node_map['.'.join(node_path + [key])] = val
            if type(val) is dict:
                nodeRecursiveMap(val, node_path + [key])
    nodeRecursiveMap(d, node_path)
    return node_map

rawDescription: Get nested arrays out of a dictionary

description: Get nested arrays out of a dictionary


code:
import pandas as pd

df = pd.read_csv('CSVData.csv')
df = df.groupby(['month', 'weekday', 'hour'])['data'].agg(['mean'])

#                             mean
# month    weekday   hour
# April    Saturday  16    0.809566
#          Wednesday 19    0.897632
# August   Friday    16    0.243372
#          Sunday    21    0.201673
#          Thursday  7     0.411290
# January  Friday    0     0.378825
#          Sunday    17    0.315196
#          Tuesday   7     0.938471
# July     Tuesday   10    0.527339
# March    Tuesday   2     0.590246
# May      Friday    7     0.135752
#          Thursday  0     0.067077
#          Tuesday   18    0.822701
#          Wednesday 15    0.436915
# November Saturday  4     0.180149
#          Tuesday   6     0.252064
# October  Saturday  7     0.456020
#          Sunday    22    0.970212

rawDescription: Calculate mean over values in lines of CSV file if month, week day, and time match a conditon


code: index(value, [start, [stop]])

rawDescription: Determine number of row in matrix with duplicate rows


code:
import functools

def yield_not_None(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        return (x for x in f(*args, **kwargs) if x is not None)
    return wrapper

@yield_not_None
def do_stuff():
    yield maybe(1)
    yield maybe(6)
    yield maybe(5)

rawDescription: python 2.7 - is there a more succint way to do this series of yield statements (in python 3, "yield from" would help)

description: Python 2.7 - is there a more succint way to do this series of yield statements (in python 3, "yield from" would help)


code:
import os.path
os.path.join('first_part', 'second_part')
os.path.join('first_part', '/second_part')

rawDescription: New folder that is created inside the current directory


rawDescription: List Comprehension with Varible Length Outputs


rawDescription: IndexError: too many indices for array. Numpy array with 42 features not homogeneous


code:
binary_a = a.decode("hex")
binary_b = b.decode("hex")

rawDescription: Python: XOR hex strings

description: Python: XOR hex strings


rawDescription: Datetime Unix timestamp contains milliseconds


rawDescription: wxPython - Align buttons in an expanding sizer

description: WxPython - Align buttons in an expanding sizer


code:
import os
import http.cookies

c = http.cookies.SimpleCookie(os.environ.get('HTTP_COOKIE'))
c['hello'] = 'world'
c['hello']['expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT'
print(c)

rawDescription: Clearing a cookie with SimpleCookie

description: Clearing a cookie with SimpleCookie


code:
result = []
temp = []
for i in X:
    if i <= 0:
        if temp:
            result.append(temp)
            temp = []
    else:
        temp.append(i)
if temp:
    result.append(temp)

rawDescription: Taking Apart A List Python

description: Taking Apart A List Python


code:
# First column of output array as the union of first columns of a,b
out_id = np.union1d(a[:,0],b[:,0])

# Masks of first columns of a and b matches in the output ID array
mask1 = np.in1d(out_id,a[:,0])
mask2 = np.in1d(out_id,b[:,0])

# Initialize second column of output array
out_count = np.zeros_like(out_id)

# Place second column of a into out_id & add in second column of b
out_count[mask1] = a[:,1]
np.add.at(out_count, np.where(mask2)[0],b[:,1])

# Stack the ID and count arrays into a 2-column format
out = np.column_stack((out_id,out_count))

rawDescription: Updating a NumPy array with another

description: Updating a NumPy array with another


rawDescription: converting integers to decimals in a string

description: Converting integers to decimals in a string


code: [field for field in dir(Language) if not field.startswith("__")]

rawDescription: Get a list of lists out of a Python object


rawDescription: Does the global keyword inline the global exactly as a local variable declaration in python?


rawDescription: Problem with exiting a Word doc using Python


rawDescription: Regex: Get "London, UK" from "Evolution Recruitment (Agency) (London, UK)"


rawDescription: Python: Pulling data out of dictionary like a 2D array


code: user = fn[subject]()

rawDescription: need help for calling function

description: Need help for calling function


code: line = next(sysinp)

rawDescription: read value from the next line of a match

description: Read value from the next line of a match


rawDescription: Reshaping two-column data using pandas pivot


code: {k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}

rawDescription: How to filter a dictionary according to an arbitrary condition function?

description: Filter a dictionary according to an arbitrary condition function


code: d = dict(reflist)

rawDescription: How to compare one value from a list of lists to another value from a list of lists in Python

description: Compare one value from a list of lists to another value from a list of lists in Python


code:
import scipy.sparse as sps
a = sps.csr_matrix([[1, 0, 0], [0, 0, 0], [0, 2, 3]])
a.indptr
mask = np.concatenate(([True], a.indptr[1:] != a.indptr[:-1]))
mask  # 1st occurrence of unique a.indptr entries
sps.csr_matrix((a.data, a.indices, a.indptr[mask])).A

rawDescription: How to eliminate zeros in sparse matrix in (Python)?

description: Eliminate zeros in sparse matrix in (Python)


code:
gli=(e for e in li)
max(int(l[2]) for l in gli)
max(int(l[2]) for l in zip(*li))

rawDescription: search the biggest number of one column in a list of list python

description: Search the biggest number of one column in a list of list python


code:
graph
out

rawDescription: Numpy- get neighbors matrix from 2D array


rawDescription: How can I make putall and getall methods of a Queue subclass atomic?

description: Make putall and getall methods of a Queue subclass atomic


code:
sz = asign == 0
while sz.any():
    asign[sz] = np.roll(asign, 1)[sz]
    sz = asign == 0

rawDescription: How to detect a sign change for elements in a numpy array

description: Detect a sign change for elements in a numpy array


rawDescription: Manipulations with raw_input

description: Manipulations with raw_input


code:
import pandas as pd

# change sep to use '\t' if those files actually are tab-delimited
df1 = pd.read_csv('file1.txt', sep=r'\s+', header=None)
df2 = pd.read_csv('file2.txt', sep=r'\s+', header=None)

result = pd.merge(df1, df2, on=0)
result.to_csv('output.txt', sep='\t', header=False, index=False)

rawDescription: Find the same pattern in two files python


code:
RandomCharField(length=4, include_alpha=False)
# 7097

rawDescription: Tricky coding logic for Django web app

description: Tricky coding logic for Django web app


code:
def parse(self, response):
    sel = Selector(response)
    videos = sel.xpath('//div[@class="video"]')

    for video in videos:
        try:
            url = video.xpath('.//a[@class="hRotator"]/@href').extract()[0]
        except IndexError:
            continue
        loader = ItemLoader(VideoItem(), videos)
        loader.add_xpath('original_title', './/u/text()')
        loader.add_xpath(
            'original_id',
            './/a[@class="hRotator"]/@href',
            re=r'movies/(\d+)/.+\.html'
        )
        item = loader.load_item()
        yield Request(
            urlparse.urljoin(response.url, url),
            callback=self.parse_video_page,
            # Note: item passed to the meta dict, not loader itself
            meta={'item': item}
        )

    pages = sel.xpath('//div[@class="pager"]//a/@href').extract()
    for page in pages:
        url = urlparse.urljoin('http://www.mysite.com/', page)
        yield Request(url, callback=self.parse)

def parse_video_page(self, response):
    item = response.meta['item']

    # Note: new loader object created,
    # item from response.meta is passed to the constructor
    loader = ItemLoader(item, response=response)
    loader.add_xpath(
        'original_description',
        '//*[@id="videoInfo"]//td[@class="desc"]/h2/text()'
    )
    loader.add_xpath(
        'duration',
        '//*[@id="video-info"]/div[2]/text()'
    )
    loader.add_xpath('tags', '//*[@id="tags"]//a/text()')
    return loader.load_item()

rawDescription: How to change selector for ItemLoader

description: Change selector for ItemLoader


code:
def my_method(self, param, keyword='spacial'):
    handler = dispatch_mapping.get(keyword)
    if handler is None:
        raise Exception("No handler for %s" % keyword)
    return handler(param)

rawDescription: Omitting long 'if, elif, elif, else' from keyword-arguments


code:
thread_test.run()
1

rawDescription: time.sleep -- sleeps thread or process?

description: Time.sleep -- sleeps thread or process


code:
import numpy as np

# Generate some x, y data
x, y = np.random(2, 100)

# Create a histogram of x
counts, bins = np.histogram(x, bins=30)

# Return an series of indicies of which bin each x-value falls into
# This will be the same size as x and have values between 0 to len(bins)
idx = np.digitize(x, bins)

# Print the y-values for each bin
for i in range(bins.size):
   y[idx == i]

rawDescription: Arrays in loops

description: Arrays in loops


code:
AB = [A[i] + B[i] for i in range(min(len(A), len(B)))]

AB = map(sum, zip(A, B))

AB = [a + b for a, b in zip(A, B)]

rawDescription: Finding the sum of matching components in two lists


rawDescription: Printing value of a variable as a object name python


code:
student_list = []
for x, y in zip(files, scores):
    student_result = (x, int(y))
    student_list.append(student_result)

print(student_list)

rawDescription: How to sort a list of strings by highest number

description: Sort a list of strings by highest number


rawDescription: Access dictionary from a list

description: Access dictionary from a list


code:
import numpy as np

# Given axis along which elementwise multiplication with broadcasting
# is to be performed
given_axis = 1

# Create an array which would be used to reshape 1D array, b to have
# singleton dimensions except for the given axis where we would put -1
# signifying to use the entire length of elements along that axis
dim_array = np.ones((1,a.ndim),int).ravel()
dim_array[given_axis] = -1

# Reshape b with dim_array and perform elementwise multiplication with
# broadcasting along the singleton dimensions for the final output
b_reshaped = b.reshape(dim_array)
mult_out = a*b_reshaped

rawDescription: multiply numpy ndarray with 1d array along a given axis

description: Multiply numpy ndarray with 1d array along a given axis


code:
import random
import pygame

WHITE = (255,255,255)
BLACK = (0  ,0  ,0  )

#----------------------------------------------------------------------

class Player():

    def __init__(self, image, x=0, y=0):

        self.image = pygame.image.load(image)#.convert()
        #self.image.set_colorkey(WHITE)
        self.rect = self.image.get_rect()

        self.rect.centerx = x
        self.rect.centery = y

    #------------

    def draw(self, screen):
        screen.blit(self.image, self.rect)

    #------------

    def update(self):
        # here change randomly positon
        self.rect.topleft = random.randint(60,220+1), random.randint( 0, 475+1)

#----------------------------------------------------------------------

class Game():

    def __init__(self):

        pygame.init()

        self.screen = pygame.display.set_mode((800,600))

        self.background = pygame.image.load("background.jpg").convert()
        self.multi_players = []

        # create 3 balls 1...3

        for i in range(1,4):
            player = Player("ball"+str(i)+".png")
            player.update() # set random position on start
            self.multi_players.append(player)

    #------------

    def run(self):

        clock = pygame.time.Clock()
        RUNNING = True

        while RUNNING:

            # --- events ---

            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    RUNNING = False

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        RUNNING = False

                    # changes position when key is pressed

                    for player in self.multi_players:
                        player.update()

            # --- updates ----

            # place for updates

            # --- draws ---

            self.screen.fill(BLACK)

            self.screen.blit(self.background, self.background.get_rect())

            for player in self.multi_players:
                player.draw(self.screen)

            pygame.display.flip()

            # --- FPS ---

            clock.tick(20)

        # --- quit ---

        pygame.quit()

#----------------------------------------------------------------------

Game().run()

rawDescription: Pygame display multiple images randomly

description: Pygame display multiple images randomly


rawDescription: What features of images will produce good result used in SVM multiclass image classification?


code: [l for l in range(3) for k in range(5)]

rawDescription: List of repeating integers

description: List of repeating integers


rawDescription: Transposing arrays in an array

description: Transposing arrays in an array


code:
df = df.sortlevel()
df
pd.concat([ df.loc[idx[:,:,x],:]*v for x,v in forex.iteritems() ])

rawDescription: Multiply all columns of a multi-indexed DataFrame by appropriate values in a Series


code: xlwt.Utils.rowcol_to_cell(30, 27)

rawDescription: converting excel positioning to numbers

description: Converting excel positioning to numbers


code:
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Product(models.Model):
     ...

class Food(Product):
     ...

class Wine(Product):
     ...

class Review(models.Model):
    ...

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

rawDescription: Django sharing one model between two others


rawDescription: Python difference between two dates

description: Python difference between two dates


rawDescription: Write the digits of a number into an array


code:
def afunc(some_param_name):
    assert isinstance(some_param_name, SomeClassName), (
           'some_param_name must be an instance of SomeClassName, silly goose!')

rawDescription: How to format a python assert statement that complies with PEP8?

description: Format a python assert statement that complies with PEP8


code: a[a[:,1].argsort()] # Replace 1 with the index you need

rawDescription: Sorting numpy mix-typed matrices

description: Sorting numpy mix-typed matrices


code:
word1
word2
word3
word1, word2, word3 = replace_all_slash(word1, word2, word3)
word1
word2
word3

rawDescription: how to define function with variable arguments in python - there is 'but'

description: Define function with variable arguments in python - there is 'but'


rawDescription: Python filtering for numeric and string in a single data frame column


code:
mymodel = forms.ModelChoiceField(
            required=True,
            queryset=ships.models.Authority.objects.all(),
            widget=autocomplete_light.ChoiceWidget('AutocompleteName')
          )

rawDescription: django-autocomplete-light simple usage

description: Django-autocomplete-light simple usage


code: num = int((low + high) / 2)

rawDescription: Fastest way to guess a number only knowing if it is higher or lower than the previous guess?


code:
def even_pos(data):
    if isinstance(data,list):
        return [data[i] for i in range(0,len(data),2)]
    else:
        raise ValueError("only a list")

rawDescription: What does isinstance with a dictionary and abc.Mapping from collections doing?


code:
class ScribbleMedia(models.Model):
     media = models.FileField(upload_to=get_file_path)

     def __unicode__(self):
        return self.media
     def find_typecheck(self):
        filename = self.media.name
        try:
           ext = filename.split('.')[-1]
           if ext == 'jpeg':
              a=1
           else:
              a=2
        except Exception:
           a=-1 #couldn't determine
        return a

rawDescription: Django- Check the filetype of an uploaded file and then alter the template


rawDescription: Is this a "pythonic" method of executing functions as a python switch statement for tuple values?


code:
body_tags = tree.xpath('//body')
if body_tags:
  body = body_tags[0]
  text_document = body.text_content()
else:
  text_document = ''

rawDescription: Parsing HTML documents using lxml in python


rawDescription: Initialize empty list with same shape as array


code:
rx, ry = y - cx, x - cy
r = np.hypot(rx, ry)
v2 = s * np.dstack((-ry, rx)) / r[..., None]
v2[np.isnan(v2)] = 0

rawDescription: Initialising a vector field in numpy

description: Initialising a vector field in numpy


code:
def weighted_choice(weights):
    cs = numpy.cumsum(weights)
    return bisect.bisect(cs, numpy.random.random() * cs[-1])

rawDescription: Fast way to obtain a random index from an array of weights in python


rawDescription: Python Generator Returns Last Item

description: Python Generator Returns Last Item


code:
def get_form_kwargs(self):
    kwargs = super(UserChangePassword, self).get_form_kwargs()
    kwargs.update({'user': self.request.user, 'post': self.request.POST})
    return kwargs

rawDescription: Pass request object to form instantion with Class-based views


code:
fields = ('description', 'title', 'etc')
Book.objects.all().update(**{f: None for f in fields})

rawDescription: Delete Multiple Django Model Attributes

description: Delete Multiple Django Model Attributes


code:
num = []
for h in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
    for b in range(1, int(size) + 1):
        num.append(h + str(b))

rawDescription: Bombs Away Battleships

description: Bombs Away Battleships


code:
class MyCallable(object):
    def __call__(self):
        return "Hello World!"

mc = MyCallable()
callable(mc)
mc()

rawDescription: How to know if a member of a class is a method?

description: Know if a member of a class is a method


code: set(wordList)

rawDescription: Python NLTK not taking out punctuations correctly


rawDescription: Mapping diagonal elements recursively and check for condition, Python


code:
from itertools import cycle

def vigenere(plain, key, alphabet):
    for p, k in zip(plain, cycle(key)):
        index = alphabet.index(p) + alphabet.index(k)
        yield alphabet[index % len(alphabet)]

rawDescription: Modified Vigenere Cipher in python - Alphabet


code:
df
df.T.to_dict().values()

rawDescription: Pandas DataFrame to List of Dictionaries (Dics)


code:
recs = {}
for r in d.foo.find(fields=['data', 'timestamp']):
    text, time = r['data']['text'], r['timestamp']
    if text not in recs or recs[text] < time:
        recs[text] = time

rawDescription: Saving entries of Mongo documents into CSV + Formatting ISODate


code:
for a, b, c in zip(x,y,z):
    for i in range(a - dx + 1, a):
        for j in range(b - dy + 1, b):
            bin_data[i,j] += c

rawDescription: 2D data binning with overlapping in python


code:
TreeView = Gtk.TreeView()
list = Gtk.ListStore(str, str)
TreeView.set_model(list)

def down(widget):
    selection = TreeView.get_selection()
    sel = selection.get_selected()
    if not sel[1] == None:
        next = list.iter_next(sel[1])
        if next:
            selection.select_iter(next)

rawDescription: Python GTK3 Treeview Move Selection up or down


code:
# Note that this is Python 3.4+ only
import time
import multiprocessing

def foo(x):
    for x in range(2**28):pass
    print(x**2)

if __name__ == "__main__":
    completely_unrelated_array = list(range(2**23))  # Again, this only exists in the parent
    ctx = multiprocessing.get_context("spawn") # Use process spawning instead of fork
    P = ctx.Pool()

    for x in range(8):
        ctx.Process(target=foo, args=(x,)).start()

rawDescription: How can I restrict the scope of a multiprocessing process?

description: Restrict the scope of a multiprocessing process


code:
weights = {fruit:weight for fruit, weight in weights}
prices  = {fruit:price for fruit, price in prices}

rawDescription: Create a 3-dimension list from two 2-dimension lists with a common element in each


rawDescription: How to test if all rows are equal in a numpy

description: Test if all rows are equal in a numpy


code:
list_iter = iter([])
list_iter
dir(list_iter)

rawDescription: Which element are we currently at in a "for x in y:" loop


code:
from collections import Counter
counts = Counter(['abc', 'def', 'abc', 'foo', 'bar', 'foo', 'foo'])
counts
Counter(['abc', 'def', 'abc', 'foo', 'bar', 'foo', 'foo']).most_common(1)

rawDescription: Increasing speed/performance in counting through very large lists in Python


rawDescription: Count of specific case per row in matrix


code:
data1 = "00:02:12.935 mta         Messages       I Doc O:NVS:FAXG3/ R:NVS:SMTP.0/xxxx@x.fr mid:6499"
data2 = "00:03:12.935 mta         Messages       I Doc O:NVS:FAXG3/ R:NVS:SMTP.0/xxxxx@xxxxx.fr mid:6599"
data_list = [ data1, data2 ] #store the data in a list so we can iterate over it
tableau = [] #create a list to hold our output
for data in data_list:  #iterate over the list, getting 1 "data" at a time
    #extract info we want
    i = re.findall(r"^.[^\ ]*", data )
    j = re.findall(r"\d+$", data )
    k = re.findall(r"O:[^\ ]*", data )
    r = re.findall(r"R:[^\ ]*", data )

    #create dictionary and append it to tableau
    tableau.append({'Heure':i,'MID':j,'Source':k,'Destination':r})

rawDescription: How to use "While()" in python

description: Use "While()" in python


code:
while(n < len(spacesLocation)):#goes through where all the spaces are
    finalResult = finalResult[:spacesLocation[n]+n] + ' ' +finalResult[spacesLocation[n]+n:]#adds spaces where they go
    n+=1#re-iterates to go through where all the spaces should be

rawDescription: Python: Moving letters within the alphabet in a string


code:
mystring = "Safety/Report/Image/489"
mystore = mystring.split('/')
mystore
mystore[2]

rawDescription: python string manipulation

description: Python string manipulation


rawDescription: Finding superstrings in a set of strings in python


code: [l for l in list_dirs if l.split('\\')[-1] not in unwanted_files]

rawDescription: Remove string from list if from substring list


rawDescription: Python -- Turn Tree into HTML calendar

description: Python -- Turn Tree into HTML calendar


code:
def traverse(rootdir):
    names = []
    dir_to_names = {rootdir: names}
    for cdirname, dirnames, filenames in os.walk(rootdir):
        subnames = dir_to_names[cdirname]
        for subdirname in sorted(dirnames):
            subnames2 = dir_to_names[os.path.join(cdirname, subdirname)] = []
            subnames.append([subdirname, subnames2])
        for filename in sorted(filenames):
            subnames.append(filename)
    return names

rawDescription: Python File Transversal

description: Python File Transversal


rawDescription: Opening TOPCAT through command line Via Python Script


code:
def f4():
    for n, e in enumerate(my_list[0:1000000]):
        np1 = my_list[n+1]
        my_function(e * 2,
                    e + np1,
                    e * np1,
                    e - np1)

rawDescription: Python code speedup by storing commonly used list elements in local variables


code:
import re
string = "It was never going to work, he thought. He did not play so well, so he had to practice some more. Not foobar !"
transformed = re.sub(r'\b(?:not|never|no)\b[\w\s]+[^\w\s]',
       lambda match: re.sub(r'(\s+)(\w+)', r'\1NEG_\2', match.group(0)),
       string,
       flags=re.IGNORECASE)

rawDescription: How to add tags to negated words in strings that follow "not", "no" and "never"

description: Add tags to negated words in strings that follow "not", "no" and "never"


rawDescription: Is there a shorthand for using the same variable being assigned for the argument in a function?


rawDescription: How can I plot multiple lines using the same array and set disconnect points in python?

description: Plot multiple lines using the same array and set disconnect points in python


code:
df.loc[:,'RecordOffset'] = df.record + 1
df = df.merge(df, left_on = ['person', 'record'], right_on = ['person', 'RecordOffset'], how = 'left')

rawDescription: Pandas DataFrame Self-Join on Key1 == Key1 and Key2 +1 == Key2


rawDescription: NumPy Array Indexing

description: NumPy Array Indexing


code:
VALID_LABEL_OPTIONS=['text', 'and', 'so', 'on']
VALID_PACK_OPTIONS = ['side', 'etc']

def extract_args(all_args, valid_keys):
    return {k:v for k,v in all_args.items()
            if k in valid_keys}

rawDescription: how to pythonically pass arguments to methods of subclassed widgets?

description: Pythonically pass arguments to methods of subclassed widgets


rawDescription: Python: Slicing a String based on Indicies and character


code:
for polygon in order_points(xs, regions):
    xx, yy = zip(*polygon)

rawDescription: How to order points for Matplotlib's fill function?

description: Order points for Matplotlib's fill function


code:
idx = 0;
for  row1, row2, row3 in zip(u[0::,:],u[1::,:],u[2::,:]):
    print(row1, row2, row3)
    np.savetxt('array{:03d}.txt'.format(idx),
                (row1, row2, row3),
                delimiter=' ', fmt='%.2e')
    idx = idx + 1

rawDescription: Saving numpy arrays as txt file [Beginner]


code:
import random
rand_l = random.sample(l, len(l))

for f in rand_l:
    f()

rawDescription: Generate random numbers in range without repetition


code:
c = toyschema.Contact()
c.lat = 10
c.lat
import math
math.cos(c.lat)
math.cos(toyschema.Contact.lat)

rawDescription: Python - SqlAlchemy: Filter query by great circle distance?


code: from __future__ import division

rawDescription: Python 2.7 rounding vs Python 3

description: Python 2.7 rounding vs Python 3


code:
import collections

def uniques(*args):
    """For an arbitrary number of sequences,
           return the items in each sequence which
            do not occur in any of the other sequences
    """

    # ensure that each value only occurs once in each sequence
    args = [set(a) for a in args]

    seen = collections.defaultdict(int)
    for a in args:
        for i in a:
            seen[i] += 1
    # seen[i] = number of sequences in which value i occurs

    # for each sequence, return items
    #  which only occur in one sequence (ie this one)
    return [[i for i in a if seen[i]==1] for a in args]

rawDescription: Comparing `list`s in python

description: Comparing `list`s in python


code: tmp = os.popen("ls").read()

rawDescription: in python, get the output of system command as a string

description: In python, get the output of system command as a string


code: pattern = r'src="images/(.+?.png")'

rawDescription: regex python - using lookbehinds to find my specific text

description: Regex python - using lookbehinds to find my specific text


code:
def weighted_fast_samp(refs, weights=None, lim=10000, blocksize=10000):

    samp = np.random.choice(refs, size=blocksize, replace=True, p=weights)
    samp_sum = np.cumsum(samp)

    # is the sum of our current block of samples >= lim?
    while samp_sum[-1] < lim:

        # if not, we'll sample another block and try again until it is
        newsamp = np.random.choice(refs, size=blocksize, replace=True,
                                   p=weights)
        samp = np.hstack((samp, newsamp))
        samp_sum = np.hstack((samp_sum, np.cumsum(newsamp) +  samp_sum[-1]))

    last = np.searchsorted(samp_sum, lim, side='right')
    return samp[:last + 1]

rawDescription: Speed up loop to fill an array with closest values from another array


rawDescription: How to convert unsigned value to byte string

description: Convert unsigned value to byte string


code:
import itk
meshType2D = itk.Mesh[itk.D, 2, itk.QuadEdgeMeshTraits.D2BBFF]
meshType3D = itk.Mesh[itk.D, 3, itk.QuadEdgeMeshTraits.D3BBFF]

rawDescription: How to create a mesh object in ITK using Python bindings?

description: Create a mesh object in ITK using Python bindings


code:
application = webapp.WSGIApplication([('/city', ShowCityPage)],
                                     debug=True)

rawDescription: Make URL point to .py file in App Engine


code:
class Page(tornado.web.RequestHandler):
    def get(self,title):
        title = tornado.escape.url_unescape(title, encoding='utf-8')
        self.write(title)

miaw = tornado.web.Application([
(tornado.escape.url_escape(u'/ééé/(*.)'), Page),
])
# you can get /ééé/page_name, where page_name can be unicode

if __name__ == "__main__":
    miaw.listen(8000)
    tornado.ioloop.IOLoop

rawDescription: Tornado and Unicode

description: Tornado and Unicode


rawDescription: python: arbitrary order by

description: Python: arbitrary order by


code:
class Register(object):
    def __init__(self,x):
        self.fieldwidths = [6,12,6,4,12,8,16]

        ## Reverse the input string then convert it to an integer
        x = int(x[2:][::-1],2)

        ## To keep code size down, store fields in a list (+ laziness)
        ## [BitField1, BitField2, ...,BitField7]
        self.fields = [0,0,0,0,0,0,0]

        for i,width in enumerate(self.fieldwidths):
            ## You can change the variables this stores the values in to
            ## your liking, but this is the basic procedure

            ## Store the last "width" number of bits in the current field
            ## e.g. 0b1000101 & 0b111 (or (2**3)-1) yields 0b101
            self.fields[i] = x & ((2**width)-1)

            ## Chop off the last "width" number of bits from x
            ## e.g. 0b1010 >> 1 would result in 0b101
            x = x >> width

obj = Register('0b11011101110111011101110111011101110011001100110011001100110011001011101110111011101110111011101110101010101010101010101010101010')

rawDescription: How read bits in 64 bit data put into corresponding bitfields in python


code:
def fileManipulator(infile=None,outfile="C:\\out\\File.kml"):
    if infile is None:
        infile=browse()
    #code that manipulates the file here
    file.save(outfile)

rawDescription: Execute function when button is pressed, not when script runs


code:
ndims = 5
N = 10

# Define bin boundaries
binbnds = ndims*[None]
nbins = []
for idim in xrange(ndims):
    binbnds[idim] = numpy.linspace(-10.0,10.0,numpy.random.randint(2,15))
    binbnds[idim][0] = -float('inf')
    binbnds[idim][-1] = float('inf')
    nbins.append(binbnds[idim].shape[0]-1)

nstates = numpy.cumprod(nbins)[-1]

# Define variable values for N particles in ndims dimensions
p = numpy.random.normal(size=(N,ndims))

# Assign to bins along each dimension
binassign = ndims*[None]
for idim in xrange(ndims):
    binassign[idim] = numpy.digitize(p[:,idim],binbnds[idim]) - 1

binassign = numpy.array(binassign)

# multidimensional array with elements mapping from multidim to linear index
# Two different arrays for C vs F ordering
linind_C = numpy.arange(nstates).reshape(nbins,order='C')
linind_F = numpy.arange(nstates).reshape(nbins,order='F')

rawDescription: Numpy interconversion between multidimensional and linear indexing


code:
with open("data.csv", "r") as f_input:
    lmin_col = []
    lmin_row = []

    for row in csv.reader(f_input):
        row = [float(col) for col in row]
        lmin_row.append(min(row))

        if lmin_col:
            lmin_col = [min(x,y) for x,y in zip(lmin_col, row)]
        else:
            lmin_col = row

    print("Min per row:", lmin_row)
    print("Min per col:", lmin_col)

rawDescription: Finding the minimum of each column of a CSV file using python


code: notes[note % len(notes)]

rawDescription: Python wrapping around on a list when list index is out of range


code:
def desc(self):
    out = []
    for kid in self.children:
        out.append(kid)
        out.extend(kid.desc())
    return out

rawDescription: Python: Family-class

description: Python: Family-class


code:
from itertools import accumulate, takewhile, repeat

def collatz(n):
    seq = accumulate(repeat(n), lambda x,_: handle(x))
    return list(takewhile(lambda x: x!=1, seq)) + [1]

rawDescription: Python repeat: Is there a conditional/lambda based repeat method for python?


rawDescription: Can I repeat a string format descriptor in python?

description: Repeat a string format descriptor in python


code:
def parse(self, response):
    item = crawledScore()
    item['reviewScore'] = response.xpath('//*[@id="avgRating"]/span/a/span/text()').re("[0-9,.]+")[0]
    item['reviewCount'] = response.xpath('//*[@id="summaryStars"]/a/text()').re("[0-9,]+")
    item['reviewURL'] = response.url
    yield item

rawDescription: Saving Scrapy data to corresponding URL in MySQL


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

db = ['paul', 'steve', 'anna']

@app.before_request
def before_request():
    if request.endpoint in ['show_user', 'delete_user', 'update_user']:
        user = request.path[request.path.rfind('/') + 1:]
        if user not in db:
            return 'user not found', 404

@app.route('/<user>')
def show_user(user):
    """ Show user information """
    return 'hello %s' % user

@app.route('/other')
def show_other():
    """ Demonstrates other routes are not effected by before_request """
    return 'other stuff'

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

rawDescription: python flask do something at each route

description: Python flask do something at each route


code:
main_category = Category("Main")
main_category.put()

sports_category = main_category.add_sub_category("Sports")
baseball_category = sports_category.add_sub_category("Baseball")
football_category = sports_category.add_sub_category("Football")
hockey_category = sports_category.add_sub_category("Hockey")

tv_category = main_category.add_sub_category("TV")

rawDescription: Datastore Design Inquiry

description: Datastore Design Inquiry


code:
class Something(ndb.Model):
  tags = ndb.StringProperty(repeated=True)
  tagset = ndb.ComputedProperty(lambda self: ','.join(self.tags.sort()))

rawDescription: How to filter NDB entities having exactly the same repeated properties?

description: Filter NDB entities having exactly the same repeated properties


rawDescription: How to add elements from a dictonary of lists in python

description: Add elements from a dictonary of lists in python


code:
month_abbreviations = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4,
                       'May': 5, 'Jun': 6, 'Jul': 7, 'Aug': 8,
                       'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
day = int(line[0:2])
month = month_abbreviations[line[3:6]]
year = 2000 + int(line[7:9]) # this should be adapted to your specific use-case

rawDescription: Parse timestamps containing different lengths Python


code:
import random

num1 = int(input("Input First number: "))
num2 = int(input("Input Second number: "))

random_numbers = [random.uniform(num1, num2) for i in range(100)]
print(sum(random_numbers)/len(random_numbers))

rawDescription: How to calculate the average number of random numbers generated?

description: Calculate the average number of random numbers generated


code:
from django import forms

DISPLAY_CHOICES = (
    ("locationbox", "Display Location"),
    ("displaybox", "Display Direction")
)

class MyForm(forms.Form):
    display_type = forms.ChoiceField(widget=forms.RadioSelect, choices=DISPLAY_CHOICES)

rawDescription: Django check if checkbox is selected

description: Django check if checkbox is selected


code: df.loc[:, df.columns != 'col_n']

rawDescription: pandas get all columms without one

description: Pandas get all columms without one


code:
import os, signal
os.kill(5383, signal.SIGKILL)

rawDescription: Terminate a python script from another python script


code:
amlist.append(thing) # This doesn't modify the original object, but it does
                     # set up the modification. After this line completes,
                     # amlist[i] and eachtickerlist[j] are both references
                     # to the same object (for some value of i and j).

amlist[0].append('undefined') # This statement modifies the object referenced by
                              # amlist[0]. Since that object is also referenced by
                              # eachtickerlist[j] (for some j), you have now
                              # stored the word 'undefined' "inside" the object
                              # referenced by eachtickerlist. Since that object
                              # is also referenced by the caller's eachtickerlist,
                              # the change is permanent and globally visible

rawDescription: Python 2.7 Local Variables are acting like global variables


rawDescription: Value for each row in Pascal Triangle - Recursion


code:
df = pd.DataFrame(np.random.randn(100, 2))
msk = np.random.rand(len(df)) < 0.8
train = df[msk]
test = df[~msk]

rawDescription: How do I create test and train samples from one dataframe with pandas?

description: Create test and train samples from one dataframe with pandas


code:
from collections import defaultdict
dct = defaultdict(float('-inf'))

rawDescription: Defaultdict with values defaulted to negative infinity


code:
def index_page(request):
    logged_in_user = request.user
    logged_in_user_posts = Post.objects.filter(user=user)

    return render(request, 'index.html', {'posts': logged_in_user_posts})

rawDescription: how can I get all post of user's in django

description: Get all post of user's in django


code:
ids_to_save = [x.id for x in SeqIO.parse(r"c:\Users\Sergio\Desktop\nsp.fasta", "fasta")]
records_to_save = [x for x in SeqIO.parse(r"c:\Users\Sergio\Desktop\wsp.fasta", "fasta") if (x.id in ids_to_save)]
SeqIO.write(records_to_save, r"c:\Users\Sergio\Desktop\nuevsp.fasta", "fasta")

rawDescription: Replace sequences between files using Biopython


code:
with self.canvas.before:
    Color(1,0,0,1)
    Rectangle(pos=self.pos, size=self.size)

rawDescription: Why does the root widget not have the same size of the window?


rawDescription: extract binary data and convert them following a specific alphabet

description: Extract binary data and convert them following a specific alphabet


code: prefix_lengths = {len(key) for sublst in price_lists for dct in sublst for key in dct}

rawDescription: getting the prefix of a number in python

description: Getting the prefix of a number in python


code:
myListWidget=QtGui.QListWidget()

for i in range(10):
    item=QtGui.QtGui.QListWidgetItem()
    myListWidget.addItem(item)

indexToRemove=[2,4,6]

itemsToRemove=[]
for index in indexToRemove:
    item=myListWidget.item(index)
    if item: itemsToRemove.append(item)

for i in range(myListWidget.count()):
    listItem = myListWidget.item(i)
    if not listItem: continue
    if not listItem in itemsToRemove: continue
    itemRow=myListWidget.row(listItem)
    if itemRow:
        myListWidget.takeItem(itemRow)

rawDescription: How to delete multiple Items from QTreeWidget, QListWidget or QListView

description: Delete multiple Items from QTreeWidget, QListWidget or QListView


code:
#__END__
#Whatever I write here will be ignored
#Woohoo !

rawDescription: In Python what's the best way to emulate Perl's __END__?


code:
import collections
for A,B,expected_output in (
    ([1,1,2,3], [1,1,2,4], [1,1,1,1,2]),
    ([1,1,2,3], [1,2,4], [1,1,2])):
    cntA = collections.Counter(A)
    cntB = collections.Counter(B)
    output = [
        x for x in sorted(set(A) & set(B)) for i in range(cntA[x]*cntB[x])]
    assert output == expected_output

rawDescription: Python: intersection of 2 lists keeping duplicates from both lists


code:
global ID
ID="Yes"

rawDescription: How to change variables in Python

description: Change variables in Python


code: frame['pct'] = frame.groupby(['pid','type']).transform(lambda x: x/sum(x))

rawDescription: python and pandas: adding a pct column to a dataframe

description: Python and pandas: adding a pct column to a dataframe


code: d = np.diff(y(x))/np.diff(x)

rawDescription: numpy gradient function and numerical derivatives

description: Numpy gradient function and numerical derivatives


code: target.insert(0, element)

rawDescription: Insertion Sort Python

description: Insertion Sort Python


rawDescription: How to read a middle size-specified chunk of a file in Python

description: Read a middle size-specified chunk of a file in Python


code:
from Tkinter import *

root = Tk()
mybutton = Button(root,text="Push me to increase x!")
mybutton.pack()

text = Text(root)
text.insert(INSERT, "Hello!")
text.pack()

x = 0

def max():
    text.insert(END, "\nx is too big!")

def show():
    global x

    if x  == 6:
        max()
        return

    text.insert(END, "\nx is {}".format(x))
    x += 1

mybutton.configure(command=show)

root.mainloop()

rawDescription: Trying to get a Button to change a Text widget


code:
foo1 = parser.add_argument('foo',help='foo 1 positional')
foo2 = parser.add_argument('foo',help='foo 2 positional')
parser.print_help()

rawDescription: Disable/Remove argument in argparse

description: Disable/Remove argument in argparse


code:
tag = soup.find('div', {'id': "whatever"})
tag.find('code').find_all_next('a')

rawDescription: How to scrape elements that immediately follows a certain element?

description: Scrape elements that immediately follows a certain element


code:
command = "window.frames['IFrame1'].document.getElementById('elementInFrame1')"
driver.execute_script(command)

rawDescription: Several iFrames in multiple processes?

description: Several iFrames in multiple processes


code:
from django import forms

class OrderForm(forms.Form):
    address = forms.ModelChoiceField(
        queryset=UserAddress.objects.all(),
        widget=forms.widgets.RadioSelect(),
    )

rawDescription: How can I get user selected radio option? Django

description: Get user selected radio option? Django


code: soup = BeautifulSoup(data, "html.parser")

rawDescription: Python extract info from a local html file


code:
def f(a_b_c):
    a,b,c = a_b_c
    ...

rawDescription: Assigning a name to a pattern-matched item in Python


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

labels = 'ABCDEFGHIKJLMNOPQRSTUV'
data = np.random.random((len(labels), len(labels)))

fig, ax = plt.subplots()
ax.pcolor(data)
ax.axis('tight')
ax.set(xticks=np.arange(len(labels)), xticklabels=labels,
       yticks=np.arange(len(labels)), yticklabels=labels)
plt.show()

rawDescription: matplotlib - Large Heatmap

description: Matplotlib - Large Heatmap


rawDescription: Python: tree like implementation of dict datastructure


code:
from datetime import datetime
dt = datetime.today()
dt.strftime('%A')

rawDescription: How can I make django output the day of the week? both in views an in templates

description: Make django output the day of the week? both in views an in templates


code: apply_pairwise([2, 64], lambda x,y: (x+y)/2.0, 3)

rawDescription: Algorithm to generate a series

description: Algorithm to generate a series


code:
['mailNickname',
 'publicDelegatesBL',
 'logonCount',
 'cn',
 'countryCode',
 'dSCorePropagationData',
 'objectClass',
 # ... many many more
'telephoneNumber',
'physicalDeliveryOfficeName',
'name',
'memberOf',
'codePage',
'userAccountControl',
'msExchMDBRulesQuota',
'lastLogon',
'protocolSettings',
'uSNChanged',
'sn',
'msExchVersion',
'mDBUseDefaults',
'givenName',
'msExchMailboxGuid',
'lastLogoff']

rawDescription: How to retrieve all the attributes of LDAP database

description: Retrieve all the attributes of LDAP database


code:
from numpy.polynomial import Polynomial as P
p = P(coeffs)
result = p(x)

rawDescription: Calculating "generating functions" with numpy


code:
def func(one=None, two=None, three=None, four=None):
    return (one, two, three, four)

params = ("one", "two", "three", "four")
for var in params:
    tmp = func(**{var: "!!"})
    print(tmp)

rawDescription: Pass in argument to function by name dynamically


code:
key1 = lambda item: item[0][0]
key2 = lambda item: item[1][0]
key3 = lambda item: item[1][1]

rawDescription: Sort a dictionary by key, value (tuple)

description: Sort a dictionary by key, value (tuple)


code:
class Vector(object): # subclass object for new style class

    def __init__(self):
        self.x = 1
        self.y = 1
        self.z = 1

    @property
    def sum(self):
        return self.x + self.y + self.z

rawDescription: Redirect class variable to class function


code:
import itertools

lst = []

ast = [3,1]
fgh = list(itertools.product(ast, repeat=3))
hij = [",".join(map(str, item)) for item in fgh]

my_list = [3, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 1, 1, 1, 3, 3, 3, 3, 1, 1, 3, 1, 1]
n=3
gth =[",".join(str(number) for number in my_list[(i * n):(i * n + n)])

for i in range(len(my_list) / n)]

for i in range(0, len(gth)-1):
    for t in range(0, len(hij)-1):
      if gth[i] == hij[t]:
         lst.append(gth[i])

rawDescription: output is column and want it to be in a row

description: Output is column and want it to be in a row


code:
string1 = "Today I went to the (market) to pick up some (fruit)."
string2 = "Today I went to (school) to learn (algebra) and science."
word_dict = {'market': 'library', 'fruit': 'books', 'school': 'class', 'algebra': 'calculus'}

for word, translation in word_dict.items():  # Use word_dict.iteritems() for Python 2
    string1 = string1.replace('(' + word + ')', translation)
    string2 = string2.replace('(' + word + ')', translation)

rawDescription: How to replace parenthesis and text within it in Python string

description: Replace parenthesis and text within it in Python string


code:
# key and answer are variable from an http GET or POST request.
ref = db.get(key)
ref.answer = answer
ref.put()

rawDescription: using GAE datastore for job management

description: Using GAE datastore for job management


rawDescription: converting strings to numeric

description: Converting strings to numeric


code:
def parity(word, nbits):
    if nbits & (nbits - 1):
        raise ValueError("nbits must be power of two")

    while nbits > 1:
        nbits >>= 1
        word ^= (word >> nbits)
    return word & 1

rawDescription: Python - How to break word into 64bit chunks


code:
def detail(request, slug):
   ...
   institution = Institution.objects.get(slug=slug)

   # `select_related` not strictly necessary
   courses = institution.course_set.all().select_related('certification')

   context_dict['courses'] = courses
   context_dict['institution'] = institution

rawDescription: Getting spesific data from three models in django


code:
import pandas as pd
df = pd.DataFrame(data={"CommonIdentifier":[1234,1235,1236,1237],
                        "CommonValue":["type1","type2","type1","type1"],
                        "Identifier1":["a","a","b","b"],
                        "Value1":[1,1.5,2,1.3],
                        "Identifier2":["b","b","c","a"],
                         "Value2":[4,2,3.2,1]})

df = df.set_index(['CommonIdentifier', 'CommonValue'])
df.columns = pd.MultiIndex.from_product([["Identifier", "Value"], range(2)])
df = df.stack()
df.index = df.index.droplevel(-1)
print(df.reset_index())

rawDescription: Flattening pandas DataFrame

description: Flattening pandas DataFrame


code: from moduleb import my_cool_function

rawDescription: How to import appropriately

description: Import appropriately


code:
def outer():
    fsm = Fysom(TABLE)
    def myfunction():
        print("I call the state machine transition when called")
        fsm.onload()
    return fsm

rawDescription: python FSM Fysom callbacks on the other way

description: Python FSM Fysom callbacks on the other way


code: empty = [[] for _ in xrange(50)]

rawDescription: Pythonic way to create a list with X amount of empty sub-lists


code:
from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter(name='domain')
@stringfilter
def domain(value):
    if '@' in value:
        return value.split('@')[1]

rawDescription: Variables in Django

description: Variables in Django


rawDescription: Make a counter in Python

description: Make a counter in Python


code:
ra,dec = F.pixel2world(xpix,ypix)
F.show_lines([[ra,dec]])

rawDescription: How could I convert a contour plot (matplotlib) to FITS format with header?


code:
helico ['he', 'li', 'c', 'o']
helico ['he', 'li', 'co']
cute ['c', 'u', 'te']
cute ['cu', 'te']

rawDescription: is recursion the solution ?- Python

description: Is recursion the solution ?- Python


code: new_values = [(x, val) for x in range(0, len(allowed)) for val in found[x] if val not in allowed[x]]

rawDescription: List comprehension missing some values versus writing loops


code:
expand(b*(x+y)*a)
gobbleExpr(_)

rawDescription: Force evaluation of Mul(tiplication) in sympy


code:
import ImageChops
def equal(im1, im2):
  return ImageChops.difference(im1, im2).getbbox() is None

rawDescription: Compare images Python PIL

description: Compare images Python PIL


code:
files = (file for file in os.listdir(path)
         if os.path.isfile(os.path.join(path, file)))
for file in files: # You could shorten this to one line, but it runs on a bit.
    ...

rawDescription: List only files in a directory?

description: List only files in a directory


rawDescription: Numpy-y way to build a polynomial array from set of points


code:
from collections import OrderedDict
s = ["Apple", "Orange", "Grape", "Orange", "Watermelon", "Apple", "Grape"]
dict(enumerate(OrderedDict.fromkeys(s), 1))

rawDescription: Adding key-value pairs to a dictionary in an ascending order


rawDescription: Why is hardcoding this list slower than calculating it?


code:
import contextlib
import functools

def file_reader(func):
    @functools.wraps(func)
    @contextlib.contextmanager
    def wrapper(file, *args, **kwargs):
        close = kwargs.pop('close', True) # remove `close` argument if present
        f = open(file)
        try:
            yield func(f, *args, **kwargs)
        finally:
            if close:
               f.close()
    return wrapper

rawDescription: functools.wraps won't let me wrap a function with a class in Python 3

description: Functools.wraps won't let me wrap a function with a class in Python 3


code: {'Occupation': 'Developer Hacker', 'Name': 'Saun-Jean', 'Address': 'Sadar Bazaar new Delhi,India'}

rawDescription: Parse list of certain Format

description: Parse list of certain Format


rawDescription: Splitting a String using multiple delimiters


code:
[[x+':'+y for x in i.split(',')]
 for i, y in map(lambda l: map(str.strip, l.split(':')), dinner)]

rawDescription: Using Python Higher Order Functions to Manipulate Lists


rawDescription: Python regex : Replacing dots and signs followed by spaces


code: K += [max(l, key=lambda x: x[0])]

rawDescription: Python: List is a int, TypeError

description: Python: List is a int, TypeError


code:
from itertools import islice
lines_of_interest = list( islice(f, 17, 34) )

do_something_awesome( lines_of_interest )
do_something_else( lines_of_interest )

rawDescription: Memory-efficent way to iterate over part of a large file


rawDescription: Standard way to serialize and plot IP addresses?


code:
@classmethod
def create(cls, **kwargs):
    return cls.objects.create(**kwargs)

rawDescription: Return information from dict

description: Return information from dict


rawDescription: Expanding tuple into number repeated X times in a list (python)


rawDescription: How to obtain the same result as numpy.where over a 2D array without getting 2 indices from the same row

description: Obtain the same result as numpy.where over a 2D array without getting 2 indices from the same row


rawDescription: Using the source code of a opensource project to learn


code: df

rawDescription: Calculating the accumulated summation of clustered data in data frame in pandas


code:
import string
a = 'add {new} sentence {with} this word'
[x.strip(string.punctuation) for x in a.split() if x.startswith("{") and x.endswith("}")]

rawDescription: Python regex to match all words in {}

description: Python regex to match all words in {}


code:
df
df.T.to_dict()

rawDescription: Fastest way to store data from Pandas DataFrame


code:
while HP > 0:
    atack()

print("You defeated the enemy!")

rawDescription: Keep getting the same random values when using a function


code:
import numpy as np
np.array([True, False]) & np.array([True, True])
np.array([True, False]) and np.array([True, True])

rawDescription: Conditional searches on pandas Dataframe


code:
import numpy as np

class MyArray():
    def __init__(self):
        self.data = np.zeros(10)

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

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

    def __repr__(self):
        return 'MyArray({})'.format(self.data)

a = MyArray()

print(a[9])
print(a[1:5])
a[:] = np.arange(10)
print(a)

rawDescription: Overloading the [] operator in python class to refer to a numpy.array data member


code:
import tkinter as tk

def onKeyPress(event, value):
    global speed # alter the global speed variable inside a function

    # Keep in mind this insert will only occur for the selected keys
    text.insert('end', 'You pressed %s\n' % (event.char, ))
    speed += value # update speed variable with value
    print(speed) # print current speed

speed = 50

root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()

# Individual key bindings
root.bind('<KeyPress-w>', lambda e: onKeyPress(e, 1)) # value is 1 for 'w'
root.bind('<KeyPress-s>', lambda e: onKeyPress(e, -1)) # value is -1 for 's'

root.mainloop()

rawDescription: Python - While Loop changing a variable

description: Python - While Loop changing a variable


code: g2 = [elem[:12] for elem in g]

rawDescription: How to truncate all strings in a list to a same length, in some pythonic way?

description: Truncate all strings in a list to a same length, in some pythonic way


code: forward( diameter * π / 360 )

rawDescription: Python Drawing a Circle with X Radius Using Forward()


code:
import random
while True:
    choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate blah\n(Q)uit\n>>>")).lower()
    if choice == "i":
        print("blahblah.")
        continue
    elif choice == "q":
        break
    elif choice == "c":
        while True:
            x = int(input("Please enter the number of x: "))
            if x >= 0: break
        while True:
            y = int(input("Please enter the number of y: "))
            if y >= 0: break
        while True:
            z = str(input("blah (B) or (P) z?: ")).lower()
            if z in "bp": break
        if z == "b":
            total = x*10 + y*6 + 0
            print("blah $", total, " blah ", x, " x and ", y, " y. blah!")
        #function that outputs the cost of premium z
        else:  # z must be "p"
            luck = random.randrange(1, 11, 1)
            if luck == 10:
                total = x*10 + y*6
                print("\nblah$", total, " blah z for ", x, " x and ", y, " y. blah!")
            #below is the normal function, for when the customer is not a lucky winner
            if luck != 10:
                total = x*12.50 + y*7.50
                print("blah $", total, " blah ", x, " x and ", y, " y. blah!")
    else:
        print("Invalid menu choice.")
        continue

rawDescription: Ending a Python Script

description: Ending a Python Script


rawDescription: Maximal Growth Period in time series

description: Maximal Growth Period in time series


code:
self.tree.bind("<Double-1>",lambda event :self.OnDoubleClick(event))
#note the OnDoubleClick is the name of the sub that python will look for when tree
#double clicked

rawDescription: Selecting data from a treeview

description: Selecting data from a treeview


code: a[0,:][np.newaxis, :]

rawDescription: How can I create a matrix, or convert a 2D array into matrix in Python?

description: Create a matrix, or convert a 2D array into matrix in Python


code:
for word in keywords:
    if word in line:
        d[word] = True

rawDescription: Is there a better way to create dynamic functions on the fly, without using string formatting and exec?


code:
fmt = '<' + str(592*600) + 'H'
pix = struct.unpack(fmt, trimdata)
lightest = max(pix)
scaled = ''.join(chr(int((float(p) / lightest)**(1/2.2) * 255)) for p in pix)
im = Image.fromstring('L', (592,600), scaled, 'raw')

rawDescription: Reading data from a 16-bit unsigned big endian raw image file in python


code:
def mwl(text):
    import string
    import collections
    text = text.lower()
    for l in string.punctuation:
        for x in text:
            if x == l:
                text = text.replace(x,'')
    collist=collections.Counter(text).most_common(1)
    print(collist[0][0])

rawDescription: Most Common letter in a string

description: Most Common letter in a string


code:
q = Queue.Queue()
q.queue.clear()

rawDescription: Clear all items from the queue

description: Clear all items from the queue


code:
def UseOpenpyxl(file_name):
    wb = openpyxl.load_workbook(file_name, read_only=True)
    sheet = wb.active
    rows = sheet.rows
    first_row = [cell.value for cell in next(rows)]
    data = []
    for row in rows:
        record = {}
        for key, cell in zip(first_row, row):
            if cell.data_type == 's':
                record[key] = cell.value.strip()
            else:
                record[key] = cell.value
        data.append(record)
    return data

rawDescription: Reading Excel file is magnitudes slower using openpyxl compared to xlrd


code:
class MyWindow(Window):
    def __init__(self):
        wpf.LoadComponent(self, 'IronPyWpf.xaml')
        self._button.Content = 'My Button'
        self._textbox.Text = 'My Text'

    def get_button(self):
        return self._button

    def set_button(self, value):
        self._button = value

    button = property(get_button, set_button)

    def get_textbox(self):
        return self._textbox

    def set_textbox(self, value):
        self._textbox = value

    textbox = property(get_textbox, set_textbox)

rawDescription: GUI development with IronPython and Visual Studio 2010


code: texts = map(lambda x: x['text'], data5)

rawDescription: Beginner Python query - selecting items in a JSON list


code:
dictionary = {
    value: list[0] if list else None,
}

rawDescription: Python - How to use try/except statement in dictionary


code:
merge_sort(['foo', 'a', 'bar', 'foobar'], key=len) # ['a', 'bar', 'foo', 'foobar']
sorted(['foo', 'a', 'bar', 'foobar'], key=len) # ['a', 'foo', 'bar', 'foobar']

rawDescription: Merge sort a list of words

description: Merge sort a list of words


code:
for search_term in search_terms:
    results = []
    results = [pool.apply_async(search_method, args=(search_term, partitions[x])) for x in range(len(partitions))]

    # Get the actual results from the AsyncResult objects returned.
    results = [r.get() for r in results]

rawDescription: How can I improve CPU utilization when using the multiprocessing module?

description: Improve CPU utilization when using the multiprocessing module


code:
from mock import patch
import unittest

def func_b():
    return "Real value"

def func_a():
    return "The result of func_b is '%s'" % func_b()

class MyTestCase(unittest.TestCase):
    def test_fake_value(self):
        with patch('test.func_b', return_value="Fake value") as mock_function:
            self.assertEqual(func_a(), "The result of func_b is 'Fake value'")

rawDescription: Fake subfunction in django UnitTest Case (Mocking)


code: import numpy as np

rawDescription: subsets [that are of length l] of list in S size

description: Subsets [that are of length l] of list in S size


code: desc = Case.__table__.c.version.info.get('description', '<no description>')

rawDescription: SQLAlchemy Declarative: Adding a static text attribute to a column


code:
if request.user.is_authenticated():
    username = request.user.username
    user = User.objects.get(email=username)

rawDescription: Improving Python/django view code

description: Improving Python/django view code


rawDescription: Finding numbers with a certain format

description: Finding numbers with a certain format


code: next((value[1] for value in names_dict.values() if value[0]==name), None)

rawDescription: Retrieving value from this dictionary of tuples


code: {'name': u'Nokia asha 515 dual sim'}

rawDescription: bypassing body unload ="window.print" while scraping the page

description: Bypassing body unload ="window.print" while scraping the page


code:
from itertools import izip_longest
sequences = []
with open('protein1.fasta', 'r') as fin:
    for header, seq in izip_longest(*[fin]*2):
        sequences.append(seq)

rawDescription: Trying to find efficient ways to remove headers in fasta files


rawDescription: Concatenating dictionaries of numpy arrays of different lengths (avoiding manual loops if possible)


code:
def test():
    # Here I'm making a variable as Global
    global a
    a = 1
    return a

rawDescription: How do I make a variable created inside a function become global?

description: Make a variable created inside a function become global


code:
with open(datafile) as f:
    file_sorted = sorted((ast.literal_eval(x) for x in f),
                         key=lambda z:(int(z[1]),z[0]),
                         reverse=True)

rawDescription: Python Sorting Text File From Highest To Lowest Based On Column Values


rawDescription: Sklearn - How to add custom stopword list from txt file


rawDescription: Reading BerkleyDB files from python: `\x01\x0b\x88\x0c\x01`?


code: setTimeout("javascript statement to update part of page",milliseconds);

rawDescription: Live updating charts in google app engine (python)


code: re.match(owner[j], str(team.value)) and (not re.findall('Defense', str(position.value)))

rawDescription: Match multiple strings using re.search within an if condition


code: print(r"abc\ndef")

rawDescription: In Python, is it possible to escape newline characters when printing a string?


code: return function_result

rawDescription: Python 2.7 multiprocessing get process result whithout using pool


rawDescription: Adding a line to a matplotlib scatterplot based on a slope


code:
# in ui.py
import Tkinter as tk
class MyApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        ...

# in main.py
import ui
def main():
    main = ui.MyApp()
    main.mainloop()

rawDescription: Python: load a UI from a separate file

description: Python: load a UI from a separate file


code:
def thing (length, depth, prefix = None):
    if not depth: return
    if not prefix: prefix = []
    for l in range (length):
        r = prefix + ['a[{}]'.format (l) ]
        yield '.'.join (r)
        for r in thing (length, depth - 1, r):
            yield r

for x in thing (2, 3): print (x)

rawDescription: Permutation growing algorithm in Python and print strings


code: not rex_nomatch and re1_matches

rawDescription: Merge several regular expressions into one RE


rawDescription: Mpmath.meijerg: Order of arguments

description: Mpmath.meijerg: Order of arguments


code: dist, c = np.split(out, [4], 1)

rawDescription: Skipping rows, and saving a row into several arrays during file readings using Python


code:
def argument_decorator(will_I_call_f):
    def decorator(f):
        def g(*args, **kwargs):
            if will_I_call_f: return f(*args, **kwargs)
        return g
    return decorator

rawDescription: Python dynamic decorators - why so many wraps?


rawDescription: Wilcard matching substring in Python

description: Wilcard matching substring in Python


code:
soup = BeautifulSoup('
get thisignore this
')
soup.div.find(text=True, recursive=False)

rawDescription: how to get text from within a tag, but ignore other child tags

description: Get text from within a tag, but ignore other child tags


code:
from distutils.core import setup

setup(
    # various package metadata fields

    install_requires=[
        'requests',
    ],
)

rawDescription: Include 'requests' module with Python script


code:
items = d.items()
# last key first
items.sort(key=lambda x: x[1]['title'])
# first key last
items.sort(key=lambda x: x[1]['score'], reverse=True)

rawDescription: Sort Multi-dimensional dictionary

description: Sort Multi-dimensional dictionary


code:
def difference_matrix(a):
    x = np.reshape(a, (len(a), 1))
    return x - x.transpose()

rawDescription: Numpy - compute all possible differences in an array at fixed distance


code:
# Initialize the object with some default values (I'm guessing here)
such_and_such = SuchAndSuch((0, 0), (0, 0), 0, 0, None, '')

# Define keydown to make use of the such_and_such object
def keydown(key):
    if key == simplegui.KEY_MAP['up']:
        such_and_such.update()
        # (Perhaps your update method should take another argument?)

rawDescription: How do I use a method outside a class?

description: Use a method outside a class


code:
import base64

base64_encoded = base64.b64encode(data)
print('base64_encoded length: {}, "{}"'.format(len(base64_encoded), base64_encoded))

rawDescription: Convert exe to hex to be run by Python

description: Convert exe to hex to be run by Python


code:
c.measure_dict('firstname', 'instrument__name', full=False) == {
    'Miles': {
        'trumpet': {'measure': 1},
        'sax': {'measure': 0},
        'piano': {'measure': 0},
    },
    'John': {
        'trumpet': {'measure': 0},
        'sax': {'measure': 1},
        'piano': {'measure': 4},
    },
}

rawDescription: Python / Django : emulating a multidimensional layer on a MySQL database


code:
from sympy.physics.mechanics import dynamicsymbols, init_vprinting
init_vprinting
init_vprinting()
x
y.diff(t)

rawDescription: Is it possible to implement Newton's Dot Notation (or Lagrange's Prime Notation) in sympy?


code:
import numpy as np
x = np.arange(4)
numrepeats = 1e15

y = np.lib.stride_tricks.as_strided(x, (numrepeats,)+x.shape, (0,)+x.strides)

rawDescription: repeated numpy subarrays

description: Repeated numpy subarrays


code:
import io
import lxml.etree as ET

content='''\
<result>
    <field k='field1'>
        <value h='1'><text>text_value1</text></value>
    </field>
    <field k='field2'>
        <value><text>text_value2</text></value>
    </field>
    <field k='field3'>
        <value><text>some_text</text></value>
    </field>
</result>'''

contentBuffer=io.BytesIO(content)
context = ET.iterparse(contentBuffer,tag='result')
for action, elem in context:
    fields=elem.xpath('field/@k')
    values=elem.xpath('field/value/text/text()')
    for field,value in zip(fields,values):
        print('\t{f} = {v}'.format(f=field,v=value))

rawDescription: python's lxml and iterparse method

description: Python's lxml and iterparse method


rawDescription: Sorting a list containing lists

description: Sorting a list containing lists


code:
class PositiveIntegerAttribute(object):

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

    def __get__(self, obj, typ=None):
        return getattr(obj, self.name)

    def __set__(self, obj, val):
        if not isinstance(val, (int, long)):
            raise TypeError()
        if val < 0:
            raise NegativeValueError()
        setattr(obj, self.name, val)

    def __delete__(self, obj):
        delattr(obj, self.name)

rawDescription: Value never below zero

description: Value never below zero


code:
import matplotlib.pyplot as plt

status_day1 = [
    [0.2, 0.3, 0.5],
    [0.1, 0.3, 0.6],
    [0.4, 0.4, 0.2],
    [0.6, 0.1, 0.4],
]

status_day2 = [
    [0.1, 0.2, 0.7],
    [0.3, 0.2, 0.5],
    [0.1, 0.5, 0.4],
    [0.2, 0.5, 0.3],
]

days = ('Day1', 'Day2')

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(1, 1, 1)

for day, data in enumerate((status_day1, status_day2)):
    bottom = 0
    for hour in data:  # Looping through every hour
        for value, color in zip(hour, ('b', 'r', 'g')):
            ax.bar(
                day,
                value,
                bottom=bottom,
                color=color,
                align='center',
            )
            bottom += value

ax.set_xticks([0, 1])
ax.set_xticklabels(days)
ax.set_xlabel('Day')
ax.set_ylabel('Hours')
plt.show()

rawDescription: Stacking multiple columns in a stacked bar plot using matplotlib in python 3


code:
def _peek(self):
    return self.queue[0]

rawDescription: How to wait until a multithread queue is not empty without wasting too much cpu cycles

description: Wait until a multithread queue is not empty without wasting too much cpu cycles


code: process = subprocess.Popen("nohup ssh -t -A $host 'remote_command'", ...)

rawDescription: Line-by-line Remote Data Transmission in Python


code:
list_of_bools = [True, True, True, False]
all(list_of_bools)
list_of_bools = [True, True, True, True]
all(list_of_bools)

rawDescription: Check at once the boolean values from a set of variables


code:
def lists(n):
    l = [0]*n
    while True:
        yield l[:]
        for i in reversed(xrange(n)):
            if l[i] != n-1:
                break
            l[i] = 0
        else:
            # All digits were n-1; we're done
            return
        l[i] += 1

rawDescription: Generate all permutations of n by n list with max value n-1 without recursion python


code:
import creole
from creole.creole2html import emitter
def new_emitter(self, node):
   return 'blah'
emitter.HtmlEmitter.link_emit = new_emitter
creole.creole2html(u"[[link]]")

rawDescription: Change internal links rendering using python-creole


code:
def is_list(value):
    return isinstance(value, list)

rawDescription: Python Template, checking for variable value type for iteration


rawDescription: Django: Having trouble setting up Many-To-One model


rawDescription: Pylons paginator question

description: Pylons paginator question


code:
import sys
from tkinter import *
from tkinter.filedialog import askopenfilename

fname = "unassigned"

def openFile():
    global fname
    fname = askopenfilename()
    root.destroy()

if __name__ == '__main__':

    root = Tk()
    Button(root, text='File Open', command = openFile).pack(fill=X)
    mainloop()

    print (fname)

rawDescription: Tkinter window not closing after closed file dialog


code:
stats = (df.groupBy("dsc")
  .agg(
      func.stddev_pop("TranAmount").alias("sd"),
      func.avg("TranAmount").alias("avg")))

df.join(broadcast(stats), ["dsc"])

(df
    .join(func.broadcast(stats), ["dsc"])
    .select("dsc", "TranAmount", (df.TranAmount - stats.avg) / stats.sd))

rawDescription: How to create z score in spark sql for each group

description: Create z score in spark sql for each group


code:
# Initialize empty list
lst_intensities = []

# For each list of contour points...
for i in range(len(contours)):
    # Create a mask image that contains the contour filled in
    cimg = np.zeros_like(img)
    cv2.drawContours(cimg, contours, i, color=255, thickness=-1)

    # Access the image pixels and create a 1D numpy array then add to list
    pts = np.where(cimg == 255)
    lst_intensities.append(img[pts[1], pts[0]])

rawDescription: Access pixel values within a contour boundary using OpenCV in Python


code:
from difflib import SequenceMatcher
number1 = 54378
number2 = 54379
SequenceMatcher(None, str(number1), str(number2)).ratio()

rawDescription: Compare two integers for similarity

description: Compare two integers for similarity


code:
def findStrAfterStr(myString, searchText, afterText):
    after_index = myString.index(afterText)
    return myString.find(searchText, after_index)

rawDescription: How can I find the first occurrence of a substring occurring after another substring in python?

description: Find the first occurrence of a substring occurring after another substring in python


rawDescription: Python 3.4 : LXML : Parsing Tables

description: Python 3.4 : LXML : Parsing Tables


code:
from Tkinter import Tk, Button, Label

root = Tk()

label = Label(text="This is some text")
label.grid()

def click():
    label.config(text="This is different text")

Button(text="Change text", command=click).grid()

root.mainloop()

rawDescription: Python - TKinter - Editing Widgets

description: Python - TKinter - Editing Widgets


code: result = [s for s in re.split(r'([a-zA-Z\xC0-\xFF]+)', inputstring) if s]

rawDescription: python split string into strings with same language characters

description: Python split string into strings with same language characters


code: ['{someid}']

rawDescription: lxml xpath RDF not working

description: Lxml xpath RDF not working


code:
product(["Long", "Med"], ["Yes", "No"])
list(product(["Long", "Med"], ["Yes", "No"]))

rawDescription: Efficient way to create strings from a list


code:
class EventInterface(list):
    # pass in the `source` list
    def filter(event, index):  # returns a generator
        start = event[index].TimeStamp
        end = event[index+1].TimeStamp
        return (s for s in self if start <= s.TimeStamp < end)

sources = EventInterface(sourceVqts)

for i in range(len(eventVqts)-2, 0, -1):
    filtered = map(attrgetter('Variant.Double'), sources.filter(eventVqts, i))

rawDescription: Pythonic conditional sum on member

description: Pythonic conditional sum on member


code:
users = {1:'john'}
userorders = {1:[21]}
#goes to a list of item ids ONLY
orders = {21:[2,3]}
items = {2:'glass',3:'wine'}

rawDescription: Re-organize a list using python with 1 to many relation


code:
x = ['apples', 'oranges', 'bananas']
for i, item in enumerate(x):
    item=item.replace('app', 'spam')
    x[i] = item

x

rawDescription: How can I replace parts of strings in a list?

description: Replace parts of strings in a list


code:
s = '''<CATALOG>
    <CD>
        <TITLE>Empire Burlesque</TITLE>
        <ARTIST>Bob Dylan</ARTIST>
        <COUNTRY>USA</COUNTRY>
        <COMPANY>Columbia</COMPANY>
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </CD>
    <CD>
        <TITLE>Hide your heart</TITLE>
        <ARTIST>Bonnie Tyler</ARTIST>
        <COUNTRY>UK</COUNTRY>
        <COMPANY>CBS Records</COMPANY>
        <PRICE>9.90</PRICE>
        <YEAR>1988</YEAR>
    </CD>
</CATALOG>
'''

e = etree.fromstring(s)

for cd in get_cd(e):
    if cd['country'] == 'USA':
        print('The cd "{0}" is from the USA.'.format(cd['title']))

# prints 'The cd "Empire Burlesque" is from the USA.'

rawDescription: XML parsing in Python with element tree

description: XML parsing in Python with element tree


code:
narray=numpy.array([[x for x in xrange(i,i+5)] for i in xrange(0,100,10)])
tarray=numpy.transpose(narray)

rawDescription: separating mutidimensional array numpy python

description: Separating mutidimensional array numpy python


rawDescription: Accessing GET Form data from - Javascript Form in Django


code:
import threading
import asyncio

class EchoClientProtocol:
    def __init__(self, message, loop):
        self.message = message
        self.loop = loop
        self.transport = None

    def connection_made(self, transport):
        self.transport = transport
        print('Send:', self.message)
        self.transport.sendto(self.message.encode())

    def datagram_received(self, data, addr):
        print('Received:', data.decode())

    def error_received(self, data, addr=None):
        raise data

async def sendChar(transport, msg):
    print('send: ', msg)
    transport.sendto(msg.encode())

user_input = [None]

# spawn a new thread to wait for input
def get_user_input(user_input_ref):
    while True:
        user_input_ref[0] = input()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    message = 'Hello World!'
    connect = loop.create_datagram_endpoint(
            lambda: EchoClientProtocol(message, loop),
            remote_addr=('127.0.0.1', 9999)
            )
    transport, protocol = loop.run_until_complete(connect)
    input_thread = threading.Thread(target=get_user_input, args=(user_input,))
    input_thread.daemon = True
    input_thread.start()
    while (True):
        if user_input[0] is not None:
            loop.run_until_complete(sendChar(transport, user_input[0]))
            user_input[0] = None
        loop.run_until_complete(asyncio.sleep(1))
    loop.run_forever()
    transport.close()
    loop.close()

rawDescription: cannot receive datagram correctly in python3 asyncio

description: Cannot receive datagram correctly in python3 asyncio


code:
# Find the pattern name="X691" value="<base64 stuff>"
base64str = re.search("name=\"X691\" value=\"(\w+)\"", data).group(1)

rawDescription: What is the most efficient way at extracting a string out of a string?


code:
l = [Cat('Joe')]

'Joe' in l
#True

rawDescription: python custom class operator overloading

description: Python custom class operator overloading


code:
import os
dirname = 'PathToFile'
myuniquelist = []
for d in os.listdir(dirname):
    if d.startswith('fname'):
        myuniquelist.append(d.split('_')[1][:4])

rawDescription: Extract subset from several file names using python


code:
# From looking at your code, "bins" and "values" are the same length.
# Therefore, the width of the last (or first) bar is undefined.
# We'll assume that the width of the last bar is the same as the one before it
diff = np.diff(bins)
widths = np.hstack([diff, diff[-1]])

rawDescription: Matplotlib display error - narrow bars and distorted axis


code: int('0x10', 16)  # here, the 16 is for the base, and 0x is optionnal

rawDescription: Create a list of Hex value in python

description: Create a list of Hex value in python


code:
Set1 = {('soda','coca cola'): 5}
Set2 = {('soda','coca cola'): 3, ('chocolate','mars'): 10}
{k: Set1[k] + Set2.get(k, 0) for k in Set1}

rawDescription: Python merge sets partially

description: Python merge sets partially


code:
import datetime

with open('file.csv','w') as outputfile:
    wrtr = csv.writer(outputfile, delimiter=',', quotechar='"')
    a = (datetime.datetime.now().strftime('%Y-%m-%d'),0,6058.7,False,1913736200,0,False)
    wrtr.writerow(a)  # pass an iterable here

    # outputfile.close() you don't have to call close() because you use with

rawDescription: Python: problems with csvwriter

description: Python: problems with csvwriter


code:
df1=pd.DataFrame( {'s1':np.random.randn(10), 's2':np.random.randn(10) } )
df2=pd.DataFrame( {'i1':np.random.randn(10), 'i2':np.random.randn(10) } )
df1.corr()

rawDescription: How do you calculate correlation between all columns in a DataFrame and all columns in another DataFrame?

description: Calculate correlation between all columns in a DataFrame and all columns in another DataFrame


rawDescription: how to access elements by path?

description: Access elements by path


code:
import types

class Test(object):
    def __init__(self, function = None):
        self.dicty = {1:{'height': 4, 'width': 2}, 2:{'height': 1, 'width': 2} }
        if function == None:
            function = lambda self, x: self.dicty[x]['height']
        self.function = types.MethodType(function, self)

rawDescription: __init__ with function as parameter (using the NetworkX)


code:
import json
from splinter import Browser

class LocalStorage:

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

  def set(self, key, value):
    self.browser.execute_script(\
      "window.localStorage.setItem('{}',{})".format(key, json.dumps(value)))

  def get(self, key):
    return self.browser.evaluate_script(\
      "window.localStorage.getItem('{}')".format(key));

  def get_all(self):
    return self.browser.evaluate_script("""(function(){
      var items = {}, ls = window.localStorage;
      for (var i = 0, k; i < ls.length; i++)
        items[k = ls.key(i)] = ls.getItem(k);
      return items;
      })()""")

  def remove(self, key):
    self.browser.execute_script(\
      "window.localStorage.removeItem('{}');".format(key));

  def clear(self):
    self.browser.execute_script(\
      "window.localStorage.clear();")

rawDescription: Access and manage local storage from Splinter?


rawDescription: No line outputted in Python

description: No line outputted in Python


rawDescription: Python : Get gtk.treeview selection from another widget


code:
def unique_by_key(elements, key=None):
    if key is None:
        # no key: the whole element must be unique
        key = lambda e: e
    return {key(el): el for el in elements}.values()

rawDescription: Making a sequence of tuples unique by a specific element


code:
cols = sorted(set(a for a, b in result_dict.iterkeys()))
rows = sorted(set(b for a, b in result_dict.iterkeys()))

rawDescription: In Python: create a table to visualize pairwise data


code:
def set_session_key(self, key):
    if self.last_session_key and not self.last_session_key == key:
        Session.objects.get(session_key=self.last_session_key).delete()
    self.last_session_key = key
    self.save()

rawDescription: django one session per user

description: Django one session per user


code:
min((math.ceil((max((x,y)) / float(x+y)) * n) * min((x,y)),
     math.ceil((min((x,y)) / float(x+y)) * n) * max((x,y))))

rawDescription: Algorithm for distributing tasks to two printers?


code: F = lambda x: sin(pi*x) / (pi*x)

rawDescription: Fixing the singularity of a function

description: Fixing the singularity of a function


code:
class CommonBase(object):
    def create(self):
        pass

class Base1(CommonBase):
    def create(self):
        super(Base1, self).create()

class Base2(CommonBase):
    def create(self):
        super(Base2, self).create()

class C(Base1, Base2):
    def create(self):
        super(C, self).create()

rawDescription: Class Inheritence Naming in Python

description: Class Inheritence Naming in Python


code:
# module with the mappings

Base = declarative_base()

class Foo (Base):
    __table__ = foo_table
    # ...

rawDescription: SQLAlchemy: How can I add common mapping logic to my custom base class (using declarative style mapping)?


code:
import pyaudio
import wave
import sys

from threading import Thread,Event
from time import sleep

class AudioFile(Thread):
    chunk = 1024

    def __init__(self, file):
        """ Init audio stream """
        Thread.__init__(self)
        self.wf = wave.open(file, 'rb')
        self.p = pyaudio.PyAudio()
        self.stream = self.p.open(
            format = self.p.get_format_from_width(self.wf.getsampwidth()),
            channels = self.wf.getnchannels(),
            rate = self.wf.getframerate(),
            output = True
        )
        self._stop = Event()

def run(self):
    self._stop.clear()
    """ Play entire file """
    while not self._stop.is_set():
        data = self.wf.readframes(self.chunk)
        self.stream.write(data)

    def stop(self):
        """ Graceful shutdown """
        self._stop.set()
        self.stream.close()
        self.p.terminate()

rawDescription: Run a GUI and play a alarm sound simultaneously in python using easygui and pyaudio


code:
parser = OptionParser()
inspect.getmembers(parser, predicate=inspect.ismethod)

rawDescription: How do I get list of methods in a Python class?

description: Get list of methods in a Python class


code:
if file.endswith('.docx'):
    ...
    cleaned = re.sub('<(.|\n)*?>','',content)
    cleaner = string.translate(cleaned, None, ["‘","’"])
    # python3 has to use:
    # # cleaner = cleaned.translate(str.maketrans({'‘':'','’':''}))

rawDescription: How to remove apostrophe from text?

description: Remove apostrophe from text


rawDescription: python numpy array slicing

description: Python numpy array slicing


code:
header = ['foo', 'bar', 'baz', ]
query = ['SELECT {} UNION'.format(','.join([repr(h) for h in header]))]
sql, params = queryset.query.sql_with_params()
query.append(sql)
sql = '''INTO OUTFILE %s
         FIELDS TERMINATED BY ','
         OPTIONALLY ENCLOSED BY '"'
         LINES TERMINATED BY '\n' '''
query.append(sql)
sql = ' '.join(query)
csv_path = os.path.join(settings.MEDIA_ROOT + '\\tmp', csv_filename)

cursor = connection.cursor()
cursor.execute(sql, params + (csv_path,))

rawDescription: How to add a header to an existing csv file?

description: Add a header to an existing csv file


rawDescription: Duplicate values in a dictionary

description: Duplicate values in a dictionary


code: {'kja': 'blue', 'kjf': 'green', 'fdf': 'yellow', 'asd': 'green', 'fff': 'brown', 'dff': 'blue'}

rawDescription: PYTHON: Read a file into a dictionary with column n as key and column m as value


code:
#!/usr/bin/python3

import unicodedata

items = "Apple tree", "Banana plant", "Orange 으르", "Goodbye"
values = 100, 200, 300, 400
for i, v in zip(items, values):
    eawid = len(i) + sum(1 for v in i if unicodedata.east_asian_width(v) == 'W')
    pad = ' ' * (15 - eawid)
    print("%s%s : %-4s" % (i, pad, v))

rawDescription: Align unicode text in terminal window using default monospace font


code:
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
list(enumerate(seasons))
list(enumerate(seasons, start=1))

rawDescription: Python: Check an index against multiple other indexes


code:
import datetime
import matplotlib.pyplot as plt
import pandas as pd
InvoicesFYThisYear = pd.DataFrame([0, 0, 0, 0, 5511, 4934, 7529, 3552])
Disputes = pd.DataFrame([98, 211, 32, 43, 21, 29, 54, 8])
PercentThisYear = (Disputes / InvoicesFYThisYear)
datenow = datetime.date.today()
ax = plt.subplot(111)
dates = [datetime.date(2015,i,1) for i in xrange(1, 9, 1)]
plt.plot(dates, PercentThisYear)
ax2 = ax.twinx()
ax2.plot(dates, InvoicesFYThisYear)
dstart = datetime.datetime(2015,4,1)
plt.xlim(dstart, datenow)
plt.xticks(dates, dates)
plt.show()

rawDescription: Lines not showing up on Matplotlib graph


code:
def edit(request, order_id):
    order = Order.objects.get(pk=order_id)
    can_edit_work_type = bool(request.REQUEST.get('can_edit_work_type', False))
    can_edit_vender = bool(request.REQUEST.get('can_edit_vender', False))
    can_edit_note = bool(request.REQUEST.get('can_edit_note', False))

    exclude_fields = []

    if not can_edit_work_type:
        exclude_fields.append('work_type')

    if not can_edit_vender:
        exclude_fields.append('vender')

    if not can_edit_note:
        exclude_fields.append('note')

    class CustomizedOrderForm(OrderDetailForm):
        class Meta:
            model = Order
            exclude = tuple(exclude_fields)

    if request.method == 'POST':
        form = CustomizedOrderForm(instance=order, data=request.POST)
        if form.is_valid():
            form.save()
    else:
        form = CustomizedOrderForm(instance=order)
    return render(request, 'order_form.html', {'form': form})

rawDescription: How do I programmatically set fields in ModelForm in Django?

description: Programmatically set fields in ModelForm in Django


code:
mtcars[['n','total_wt']] = mtcars.groupby("cyl").apply(
    lambda x: pd.DataFrame({'n': len(x['cyl']), 'total_wt': x['wt'].sum()},
                           index=x.index))
print(mtcars.head())

rawDescription: Equivalent of transform in R/ddply in Python/pandas?


code:
my_nested_list = [[0,0] for count in range(4)]
my_nested_list[1][1] = 5
print(my_nested_list)

rawDescription: Python: Replacing an element in a list of lists (#2)


code:
fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')
#Note that the bbox_extra_artists must be an iterable

rawDescription: Moving matplotlib legend outside of the axis makes it cutoff by the figure box


code:
p_type = ContentType.objects.get(name="mattress")
Product.objects.filter(content_type=p_type)

rawDescription: How to access method of "sub-model" in Django?

description: Access method of "sub-model" in Django


code:
def print_head(url):
    print ('Starting %s' % url)
    return urllib2.urlopen(url).read()

rawDescription: Gevent incremental process through non blocking joinall()


code:
parser = ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.set_defaults(mode='insert')
group.add_argument('--delete', action='store_const', dest='mode', const='delete')
group.add_argument('--update', action='store_const', dest='mode', const='update')
group.add_argument('--insert', action='store_const', dest='mode', const='insert')
parser.add_argument('value', nargs='?')
args = parser.parse_args()

rawDescription: How to include one positional argument into argparse mutually exclusive group?

description: Include one positional argument into argparse mutually exclusive group


code:
from threading import Timer
t = Timer(300.0, function_call)
t.start() # after 300 seconds, function_call will be called

rawDescription: Periodically execute function every n minutes while doing other stuffs


code:
def story_counts(request, *args, **kwargs):
    all_countries = Country.objects.annotate(Count('story')).order_by('-story__count')
    context = dict(all_countries = all_countries)
    return render_to_response(..., context)

rawDescription: Django: output aggregation of aggregation ordered by counts


code: lines = open(path,"r").readlines()

rawDescription: How to make an annonimizer with random proxy/UA from files?

description: Make an annonimizer with random proxy/UA from files


rawDescription: Consecutive, conflicting regex substitutions


code:
class Blog(Container):
    def __init__(self, name, realm=None):
        Container.__init__(realm)
        self.name = name

rawDescription: Python API design pattern question

description: Python API design pattern question


code:
# Check there are more plots in the row, just in case
if ndim > 1:
    # Get tick locations from 2nd plot in first row
    ticks = np.asarray(plots[0][1].yaxis.get_majorticklocs())

    # Throw out the ones that aren't within the limit
    # (Copied from pandas code, but probably not necessary)
    ticks = ticks[(ticks >= limits[0][0]) & (ticks <= limits[0][1])]

    # Scale ticks to range of [0, 1] (relative to axis limits)
    ticks_scaled = (ticks - limits[0][0]) / (limits[0][1] - limits[0][0])

    # Y limits of top-left density plot (was automatically determined
    #       by matplotlib)
    dlim = plots[0][0].get_ylim()

    # Set the ticks scaled to the plot's own y-axis
    plots[0][0].set_yticks((ticks_scaled * (dlim[1] - dlim[0])) + dlim[0])

    # Set tick labels to their original positions on the 2d plot
    plots[0][0].set_yticklabels(ticks)

rawDescription: "Faking" axis ticks and labels with Matplotlib


code:
def display_name(dispname):
    def decorate_with_display_name(prop):
        prop.display_name = dispname
        return prop
    return decorate_with_display_name

rawDescription: Python Decorators on Class Level Variables as Metadata for Reflection?


rawDescription: sorting a nested list by both members of an element

description: Sorting a nested list by both members of an element