code:
dt = yaml.load("""dt: !!python/object/apply:apply
    - !!python/object/apply:getattr
        - !!python/name:datetime.datetime
        - now
    - []
""")

rawDescription: How to create a datetime object with PyYAML

description: Create a datetime object with PyYAML


code: checkstart = False

rawDescription: psychopy event based on mouse position

description: Psychopy event based on mouse position


code:
import ctypes
import os

current_dir = os.path.dirname(os.path.realpath(__file__))
dll_path = os.path.join(current_dir, "tmpDll.dll")

_tmp_dll = ctypes.CDLL(dll_path)

# int change_mountain_heights(char* mountains[], float heights[], int8_t num_elements)

_tmp_dll.change_mountain_heights.restype = ctypes.c_int  # default, not required
_tmp_dll.change_mountain_heights.argtypes = (
    ctypes.POINTER(ctypes.c_char_p), ctypes.POINTER(ctypes.c_float),
    ctypes.c_int8)

def change_mountain_heights(mountains, mountain_heights):
    if len(mountains) != len(mountain_heights):
        raise ValueError()

    # pointer to strings
    string_pointers = (ctypes.c_char_p * len(mountains))(*mountains)
    # floats
    floats = (ctypes.c_float * len(mountain_heights))(*mountain_heights)
    # pointer to floats
    pfloat = ctypes.cast(floats, ctypes.POINTER(ctypes.c_float))

    # call C function
    result = _tmp_dll.change_mountain_heights(string_pointers, pfloat,
                                              len(mountain_heights))
    print("result: {}".format(result))
    if result == 1:
        # change passed list with new results
        del mountain_heights[:]
        mountain_heights.extend(list(floats))

    return result

def main():
    mountains = ["foo", "bar", "baz"]
    mountain_heights = [100.0, 200.0, 300.0]

    print("Before: {}".format(mountain_heights))

    change_mountain_heights(mountains, mountain_heights)

    print("After: {}".format(mountain_heights))

if __name__ == "__main__":
    main()

rawDescription: Python lists and ctypes

description: Python lists and ctypes


code:
q = 2 * [ 2 * [0] ]
for i in range(2):
   for j in range(2):
       q[i][j] = (1-i) * j
       print(q)

rawDescription: Python variable value reset out of loop

description: Python variable value reset out of loop


code:
class C(A, B):
    def __init__(self):
        B.__init__(self,4)

rawDescription: How can I call a particular base class method in Python?

description: Call a particular base class method in Python


code:
class UserProfile(db.Model):
    UserID = db.UserProperty()
    FirstSession = db.DateTimeProperty(auto_now_add=True)

rawDescription: display new message to new user App Engine

description: Display new message to new user App Engine


rawDescription: Find difference between two multi dimensional lists


code:
def foo (x, y): return x + y

bar = (lambda f: lambda y: f (0, y) ) (foo)
print (bar (4) )
del foo
print (bar (4) )

rawDescription: How to copy a function and set a default parameter in Python?

description: Copy a function and set a default parameter in Python


code:
import networkx
A = graph.get_edgelist()
G = networkx.DiGraph(A) # In case your graph is directed
G = networkx.Graph(A) # In case you graph is undirected

rawDescription: Convert python-igraph graph to networkx

description: Convert python-igraph graph to networkx


code:
def create(n):
    df = pd.DataFrame({ 'gene':["foo",
                                "bar // lal",
                                "qux",
                                "woz"],
                        'cell1':[5,9,1,7], 'cell2':[12,90,13,87]})
    df = df[["gene","cell1","cell2"]]
    df = pd.concat([df]*n)
    df = df.reset_index(drop=True)
    return df

def orig(df):
    s = df["gene"].str.split(' // ').apply(pd.Series,1).stack()
    s.index = s.index.droplevel(-1)
    s.name = "Genes"
    del df["gene"]
    return df.join(s)

def faster(df):
    s = df["gene"].str.split(' // ', expand=True).stack()
    i = s.index.get_level_values(0)
    df2 = df.loc[i].copy()
    df2["gene"] = s.values
    return df2

rawDescription: Fast way to split column into multiple rows in Pandas


rawDescription: How to approach list of range of values

description: Approach list of range of values


code: return JsonResponse(data)

rawDescription: Django list of json objects

description: Django list of json objects


code:
from random import random

def shuffle(items):  # returns new list
    return [t[1] for t in
            sorted((random(), i) for i in items)]

rawDescription: How do I randomize a list of strings with random.seed?

description: Randomize a list of strings with random.seed


code:
ET.Element('Level0', text='test text')

ET.Element('Level0', {'text': 'test text'})

rawDescription: Need help interpreting Python documentation


code:
groups = []
uniquekeys = []
data = sorted(data, key=keyfunc)
for k, g in groupby(data, keyfunc):
    groups.append(list(g))      # Store group iterator as a list
    uniquekeys.append(k)

rawDescription: Python groupby behaves strangely

description: Python groupby behaves strangely


code:
a = 4
b = a

rawDescription: Why are lists linked in Python in a persistent way?


code:
import subprocess
import os

scripts_to_run = ['my_app1.py', 'my_app2.py', 'my_app3.py']

for s in scripts_to_run:
    subprocess.Popen([os.path.join(os.getcwd(), s)])

rawDescription: Running several programs from one program


rawDescription: How to use the sphero_ros Python API?

description: Use the sphero_ros Python API


code:
with open(outputfile,'w') as fo:
    for inputfile in inputfiles: #assuming inputfiles is a list of filepaths
        with open(inputfile,'r') as fi:
            for chunk in iter(lambda: fi.read(chunksize), ''):
                fo.write(fi.read(chunk))
            fo.write('\n') #newline between each file(might not be necessary)

rawDescription: Does it takes RAM to save a readlines array?


code:
{
  "201": {
    "name": "Dunajsky",
    "municipalities": [
      "Streda",
      "Klatov"
    ]
  },
  "205": {
    "name": "Kosoln",
    "municipalities": {
      "Leopoldov",
      "Trnava"
    }
  }
}

rawDescription: Split dictionary by keys in Python

description: Split dictionary by keys in Python


code:
with open('file.dat', 'rb') as f:
    chunks = iter(lambda: f.read(32), b'')
    hexlines = map(binascii.hexlify, chunks)

rawDescription: pythonic way to hex dump files

description: Pythonic way to hex dump files


rawDescription: Groupby Clause in Pandas

description: Groupby Clause in Pandas


code:
import datetime
data = np.random.rand(24)

#a list of time: 00:00:00 to 23:00:00
times = [datetime.datetime.strptime(str(i), '%H') for i in range(24)]

#'H' controls xticklabel format, 'H' means only the hours is shown
#day, year, week, month, etc are not shown
plt.plot_date(times, data, fmt='H')
plt.setp(plt.gca().xaxis.get_majorticklabels(),
         'rotation', 90)

rawDescription: Using datetime as ticks in Matplotlib

description: Using datetime as ticks in Matplotlib


code:
import pygame ,sys, time
from pygame.locals import *

# User define function
def ball_move(surface, pos, rad, speed):
    def _add(l_pos, l_speed, l_size):
        l_pos += l_speed
        if l_pos <= rad or l_pos >= l_size - rad:
            l_speed = -l_speed
        return l_pos, l_speed
    size = surface.get_size()
    pos_x, speed_x = _add(pos[0], speed[0], size[0])
    pos_y, speed_y = _add(pos[1], speed[1], size[1])
    return (pos_x, pos_y), (speed_x, speed_y)

pygame.init()
screen_size = (500, 400)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption('Pong')
running = True

pos1 = (100, 200)
pos2 = (400, 200)
speed1 = (2, -2)
speed2 = (-2, 2)
rad = 10

while running:
    # Handdle your events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # update your state
    pos1, speed1 = ball_move(screen, pos1, rad, speed1)
    pos2, speed2 = ball_move(screen, pos2, rad, speed2)

    # draw to your display
    screen.fill(pygame.Color('black'))
    pygame.draw.circle(screen, pygame.Color('white'), pos1, rad)
    pygame.draw.circle(screen, pygame.Color('white'), pos2, rad)
    pygame.display.update()

rawDescription: Why balls cannot move in my code in Pygame when I code 'Pong'? Can Someone help me to check my code?


code:
def replaceToken(match):
    token = match.group()
    if len(token) == 3:
        return token
    else:
        return '[' + token + ']'

re.sub(r'(\[\[\])|(\[\]\])|\[|\]', replaceToken, 'foo[[bar]bloh')

rawDescription: Python Regex Pattern Replacement

description: Python Regex Pattern Replacement


rawDescription: Python String to Escaped Hex

description: Python String to Escaped Hex


code:
class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

rawDescription: Can someone help me understand special methods vs normal methods?


rawDescription: Vectorize large NumPy multiplication

description: Vectorize large NumPy multiplication


code: [getattr(obj, "drive")() for obj in gc.get_referrers(car) if isinstance(obj, car)]

rawDescription: Calling a method on all instances of an object


code:
for box in self.boxes:
    box.grid_remove()
else:
    self.choice_title.grid_remove()

rawDescription: Deleting parts of a frame using grid_forget Tkinter


code:
import os

def html_part(filepath):
    """
    Generator returning only the HTML lines from an
    SEC Edgar SGML multi-part file.
    """
    start, stop = '<html>\n', '</html>\n'
    filepath = os.path.expanduser(filepath)
    with open(filepath) as f:
        # find start indicator, yield it
        for line in f:
            if line == start:
                yield line
                break
        # yield lines until stop indicator found, yield and stop
        for line in f:
            yield line
            if line == stop:
                raise StopIteration

origpath = '0001005214-12-000007.txt'
htmlpath = origpath.replace('.txt', '.html')

with open(htmlpath, "w") as out:
    out.write(''.join(html_part(origpath)))

rawDescription: Python: HTML Parsing Error

description: Python: HTML Parsing Error


code:
root = Trie()
current_positions = []
for letter in letters:
    current_positions = [
        position.add_child(letter)
        for position in current_positions
    ]
    current_positions.append(root.add_child(letter))

rawDescription: find and remove common substring with python

description: Find and remove common substring with python


code:
d = OrderedDict([('a', '1'), ('b', '2')])
ordered_dict_prepend(d, 'c', 100)
d
ordered_dict_prepend(d, 'a', d['a'])
d
ordered_dict_prepend(d, 'd', 500)
d

rawDescription: How can I add an element at the top of an OrderedDict in python?

description: Add an element at the top of an OrderedDict in python


code:
palabras = "Buenos dias"
[c for c in palabras]

rawDescription: Get rid of stopwords and punctuation

description: Get rid of stopwords and punctuation


code:
def splitToOddSeqs(numbers):
    seq = ""
    for n in numbers:
        if n not in "02468":
            seq += n      # as long as we have odd numbers, we accumulate
        else:
            if seq:
                yield seq # we've found an even number - return one sequence
                seq = ""

    if seq:
        yield seq         # return last one (when input ends with odd digit)

rawDescription: How to split a string to sequences of odd numbers?

description: Split a string to sequences of odd numbers


rawDescription: Adding an additional index to an existing multi-index dataframe


code: {k: d[k] if k in d else 0 for k in v} # ≡ {k: (d[k] if k in d else 0) for k in v}

rawDescription: Simple syntax error in Python if else dict comprehension


code:
def out_csv(mydata, filename):
    with open(filename, 'w') as out_handle:
        for line in mydata:
            out_handle.write(','.join(line) + '\n')

rawDescription: how do I export my lists into an excel compatible file?

description: Export my lists into an excel compatible file


code:
for row_idx, row in enumerate(data):
    for col_idx, element in enumerate(row):
        if row_idx >= col_idx and data[row_idx][col_idx] == data[col_idx][row_idx]:
            continue

rawDescription: Optimizing Very Large Distance Matrix Processing Workflow


code:
import cPickle as pickle
with open('data.p', 'wb') as fp:
    pickle.dump(data, fp)

rawDescription: Storing Python dictionaries

description: Storing Python dictionaries


code:
old_layout = self.vbox_tags
self.vbox_tags = QtGui.QVBoxLayout()
...
self.clearLayout(old_layout)

rawDescription: My widgets don't want to disappear

description: My widgets don't want to disappear


rawDescription: Pythonic way to select elements of an array based on values?


rawDescription: Python - can text file data be stored in code?


code:
import numpy as np
from scipy.interpolate import griddata

nan = np.NaN
dat = np.array([[ 1,    nan,  nan,  nan,   5,],
                [ nan,  nan,  nan,  nan,  nan,],
                [ nan,  6,    nan,  nan,  8,  ],
                [ nan,  nan,  9,    nan,  nan,],
                [ nan,  nan,  nan,  nan,  nan,],
                [ 0,    nan,  nan,  nan,  2,  ]])

def fill_nans(indata, method='linear'):
    """
    Fill NaN values in the input array `indata`.
    """
    # Find the non-NaN indices
    inds = np.nonzero(~np.isnan(indata))
    # Create an `out_inds` array that contains all of the indices of indata.
    out_inds = np.mgrid[[slice(s) for s in indata.shape]].reshape(indata.ndim, -1).T
    # Perform the interpolation of the non-NaN values to all the indices in the array:
    return griddata(inds, indata[inds], out_inds, method=method).reshape(indata.shape)

out = fill_nans(dat)
print(out)

rawDescription: fill/predict unknown values of matrix in python

description: Fill/predict unknown values of matrix in python


code:
def change_alpha(img,alpha=255):
  width,height=img.get_size()
  for x in range(0,width):
    for y in range(0,height):
      r,g,b,old_alpha=img.get_at((x,y))
      if old_alpha>0:
        img.set_at((x,y),(r,g,b,alpha))

rawDescription: Pygame, set transparency on an image imported using convert_alpha()


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup("
1205%
")
tr = soup.find("tr")
tr
td_list = tr.find_all("td")
td_list
td_list[0]  # Python starts counting list items from 0, not 1
td_list[0].text
td_list[2].text
td_list[3].text

rawDescription: How can I get the first and third td from a table with BeautifulSoup?

description: Get the first and third td from a table with BeautifulSoup


rawDescription: How to add a string to os.system() command? (Python)

description: Add a string to os.system() command? (Python)


code:
for i in range(1, ROWS+1):
    for j in range(1, COLS+1):
        mine_field[(i, j)] = 0 # you don't even need the parentheses!

rawDescription: Python: Accessing Values For Dict Key Made Using Variables


code:
#!/usr/bin/env python
from pylab import *

x = linspace(0.1, 2*pi, 10)
markerline, stemlines, baseline = stem(x, cos(x), '-.')
setp(markerline, 'markerfacecolor', 'b')
setp(baseline, 'color','r', 'linewidth', 2)

show()

rawDescription: Plotting PMF neatly in python

description: Plotting PMF neatly in python


code:
import re
text = 'This is a post mentioning @nathancahill and @jacob_bennet'
re.sub(r'@([a-zA-Z0-9_]+)', r'@\1', text)

rawDescription: How to make a filter to check if someone has tagged a user with @?

description: Make a filter to check if someone has tagged a user with @


code:
registry = []
class Plugin(metaclass=PluginMetaclass):
    def __init__(self, stuff):
        self.stuff = stuff
class SpamPlugin(Plugin):
    def __init__(self, stuff):
        self.stuff = stuff
class BaconPlugin(Plugin):
    def __init__(self, stuff):
        self.stuff = stuff
c = SpamPlugin(0)
b = BaconPlugin(0)
mycls = registry[1][1]
d = mycls(0)
d
registry

rawDescription: python 3.2 plugin factory: instantiation from class/metaclass

description: Python 3.2 plugin factory: instantiation from class/metaclass


code:
patches = []
patches.append(ax.add_patch( plt.Circle((xp[i],yp[i]),0.02,color='b') ))

rawDescription: How to save an animation without showing the previous frames in the video?

description: Save an animation without showing the previous frames in the video


code:
def some_condition(line):
    return "line_to_be_skipped" in line

rawDescription: Python Skip one or more lines in a text file


code: d = datetime.datetime.strftime(datetime.datetime.strptime(userInDate, '%Y-%m-%d'), '%Y-%m-%d')

rawDescription: python - convert date input to date output without time

description: Python - convert date input to date output without time


code: 'WhAtChAtHiNk?'

rawDescription: How would I capitalize every other letter in a str?


code:
def addTen(var):
    if isinstance(var, int):
        var += 10
    return var

rawDescription: Most Pythonic way to update variables if condition is met


code: V4_orig_form, V4_grids = recreate(V4, aGrid, mGrid, eGrid)

rawDescription: Correspondence between a "ij" meshgrid and a long meshgrid


rawDescription: Python Scipy How to traverse upper/lower trianglar portion non-zeros from csr_matrix


code:
data['event number'] = (data.event == 'event start').cumsum()
data

rawDescription: Fill NA Values in pandas Series with a stop


code:
import irc

def start():
  irc.run()

rawDescription: Reload self-made module

description: Reload self-made module


rawDescription: Las data record format reading

description: Las data record format reading


code:
from io import BytesIO
from PIL import Image

from django.core.files.base import ContentFile

from stdimage.utils import render_variations

def preprocess(file_name, variations, storage):
    with storage.open(file_name) as f:
        with Image.open(f) as image:
            file_format = image.format

            # resize to a maximum of 1000x1000 keeping aspect ratio
            image.thumbnail((1000, 1000), resample=Image.ANTIALIAS)

            with BytesIO() as file_buffer:
                image.save(file_buffer, file_format)
                f = ContentFile(file_buffer.getvalue())
                # delete the original big image
                storage.delete(file_name)
                # save the resized version with the same filename and format
                storage.save(file_name, f)

    # render stdimage variations
    render_variations(file_name, variations, replace=True, storage=storage)

    return False  # prevent default rendering

rawDescription: Django modify image before it's handled by stdimage


code:
total = 0                          #Have total number
bigNumber = str(45858383)          #Convert our big number to a string
for number in bigNumber:           #for each little number in our big number
    total = total + int(number)    #add that little number to our total
print(total)                       #Print our total

rawDescription: How does one add the digits of a large number?

description: Add the digits of a large number


rawDescription: In Python what's some other ways to write a if x==1 or x==5 or x==10...?


rawDescription: How to get predicted class labels in TensorFlow's MNIST example?

description: Get predicted class labels in TensorFlow's MNIST example


code: (f(x) for x in list)

rawDescription: List Comprehensions in Python : efficient selection in a list


code:
locale.setlocale(locale.LC_ALL, 'es_ES')
print(locale.format('%d', 10000000, grouping=True, monetary=True))

rawDescription: How to format a number with spanish thousand grouping in python?

description: Format a number with spanish thousand grouping in python


code:
from itertools import groupby
from operator import itemgetter
inputlist = [(1,2,5),(2,10,13),(5,24,56),(1,8,10),(2,3,11)]
{k: (min(item[1] for item in gv), max(item[2] for item in gv))
         for k, g in groupby(sorted(inputlist, key=itemgetter(0)), itemgetter(0))
         for gv in (list(g),)}

rawDescription: Can Python's comprehensions make groups?

description: Can Python's comprehensions make groups


code: result_img = (test_condition).ifthenelse(value_if_true, value_if_false)

rawDescription: How to perform logical operation and logical indexing using VIPS in Python?

description: Perform logical operation and logical indexing using VIPS in Python


rawDescription: Difference between every pair of columns of two numpy arrays (how to do it more efficiently)?


code:
class TeeOut(object):
    def __init__(self, *writers):
        self.writers = writers

    def write(self, s):
        for writer in self.writers:
            writer.write(s)

rawDescription: Read python stdout as string

description: Read python stdout as string


code:
r1 = requests.get('http://www.google.com')
check_peer(r1)
r2 = requests.get('https://www.google.com')
check_peer(r2)
r3 = requests.get('http://wheezyweb.readthedocs.org/en/latest/tutorial.html#what-you-ll-build')
check_peer(r3)

rawDescription: How do I get the IP address from a http request using the requests library?

description: Get the IP address from a http request using the requests library


rawDescription: requests module return json with items unordered

description: Requests module return json with items unordered


code:
import re
text = """kAewtloYgcFQaJNhHVGxXDiQmzjfcpYbzxlWrVcqsmUbCunkfxZWDZjUZMiGqhRRiUvGmYmvnJ"""
print(re.search(r"[A-Z]{3}[a-z][A-Z]{3}", text).group(0))

rawDescription: Python Challenge #3: Loop stops way too early


code:
y, s = [], set()
for t in x:
    w = tuple(sorted(t))
    if not w in s:
        y.append(t)
        s.add(w)

rawDescription: Python: Remove Sublists from List if Same Including/Not Including Order


rawDescription: How to manage precedence in argparse?

description: Manage precedence in argparse


code:
import locale
locale.setlocale(locale.LC_TIME, "C")

rawDescription: Python logging time stamp convert to mysql timestamp


code:
from PIL import Image
import numpy as np
im = Image.open("image.png") # Replace with your image name here
indexed = np.array(im) # Convert to NumPy array to easier access

rawDescription: Read in an indexed color image in Python


code:
ldap_con.protocol_version = 3
ldap_con.set_option(ldap.OPT_REFERRALS, 0)

rawDescription: Pulling data from external Active Directory in Django


rawDescription: Set differences on columns between dataframes


code:
def merge_dicts(d1, d2):
    return {} if any(d1[k] != d2[k] for k in d1.keys() & d2) else dict(d1, **d2)

rawDescription: Merging two dicts in python with no duplication permitted


rawDescription: Is a specific timezone using DST right now?


code:
widgets = {
        'specialization' : SpecializationByCategory,
    }

rawDescription: Access a property of model field using a form in template


code:
numRatings = []
avgRating = []
with open('ratings.txt', 'rb') as f:
    reader = csv.reader(f, delimiter='|')
    for row in reader:
        numRatings.append(int(row[1]))
        avgRating.append(float(row[2]))

rawDescription: Trying to read information in a file into two lists in Python


code:
def __setattr__(self, name, value):
    super(Test, self).__setattr__(name, value)

rawDescription: I need to define __setattr__ for assignment of fields without properties, but use the setter/getter functions for fields with a property defined


code:
def find_ip(in_file,sub_s):
    import re
    with open(in_file) as f:
        lines = reversed(f.readlines())
        for line in lines:
            if sub_s in line:
                return re.findall(r"[0-9]+(?:\.[0-9]+){3}",next(lines))[0]

rawDescription: python search a text file for a string and add the value to a variable

description: Python search a text file for a string and add the value to a variable


code:
with open("myfile.txt", "w") as fstream:
    for key, data in myIndex.items():
        fstream.write("'{}': {!s}\n".format(key, data))

rawDescription: How to write an index that I have crated to a file in Python

description: Write an index that I have crated to a file in Python


rawDescription: Going through names of a set of matrices in Python


code:
from collections import defaultdict

class BetterDefaultDict(defaultdict):
  def __missing__(self, key):
    return self.setdefault(key, self.default_factory(key))

rawDescription: is it possible to use a lambda as a dictionary default?

description: Is it possible to use a lambda as a dictionary default


code:
import numpy as np
import pandas as pd

def create_data():
    # create dates
    dates = pd.date_range('2010-01-01T00:30', '2013-01-04T23:30', freq='H')
    # convert to iso
    iso_dates = dates.map(lambda x: x.strftime('%Y-%m-%dT%H:%M:%S'))
    # create data
    data = pd.DataFrame(np.random.random((iso_dates.size, 10)) * 100,
                        index=iso_dates)
    # write to file
    data.to_csv('dates.csv', header=False)

rawDescription: Convert list of datestrings to datetime very slow with Python strptime


code:
test = [[(u'hello',), (u'hello',)], [(u'hello',)]]
result = [[str(j[0]) for j in i] for i in test]

rawDescription: How to change this list tuple into list only in Python?

description: Change this list tuple into list only in Python


code:
def get_queryset(self):
    return OM.Order.objects.order_by('date__date')\
           .filter(user=self.request.user)

rawDescription: Nested object listing with conditions

description: Nested object listing with conditions


code:
good = [x for x in mylist if x in goodvals]
bad  = [x for x in mylist if x not in goodvals]

rawDescription: Python: split a list based on a condition?


code:
class UserContainer(Container):
    cls = User

rawDescription: Using singleton classes in domain model traversal in Pyramid


code:
x = []
y = []
for xrow, yrow in plot:
    x.append(int(xrow))
    y.append(int(yrow))

rawDescription: Why is this python list showing empty in this certain case?


code:
def the_longest_word(list):

    new_list = maps(list)
    return max_in_list(new_list)

rawDescription: Assigning return value of a function to a variable in Python


code:
def replaceNthWith(n, replacement):
    c = [0]
    def replace(match):
        c[0] += 1
        return replacement if c[0] == n else match.group(0)
    return replace

rawDescription: Python - Function attributes or mutable default values


code:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split(),
                   'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
#      A      B  C   D
# 0  foo    one  0   0
# 1  bar    one  1   2
# 2  foo    two  2   4
# 3  bar  three  3   6
# 4  foo    two  4   8
# 5  bar    two  5  10
# 6  foo    one  6  12
# 7  foo  three  7  14

print(df.loc[df['A'] == 'foo'])

rawDescription: Select rows from a DataFrame based on values in a column in pandas


code:
with open(logfilename, 'w') as log:
    ...

rawDescription: Won't write output to logfile on Unix/Linux but does on Windows


code:
def weeks():
    total_weight_lost = 0
    for week in xrange(1, 4):
        total_weight_lost += int(input("How much weight did you lose in week {}?".format(week)))
    return total_weight_lost

rawDescription: How to get user inputted values for keys in dictionary with for loop?

description: Get user inputted values for keys in dictionary with for loop


code:
name_list = input ("Please list 5 names here:")
name_list = name_list.split()
print ("The names in your list are:", name_list)
print ("The sorted list is:", name_list.sort())  #sorting list
print(name_list[2])   # printing 3rd element of the list as indices start from 0

rawDescription: Python 3.3 list assistance

description: Python 3.3 list assistance


rawDescription: Find duplicates in string, and return single result for only duplicates


code:
def izip_keys(xs, ys, key):
    xs = {key(x): x for x in xs}
    ys = {key(y): y for y in ys}

    for k in set(xs.keys() + ys.keys()):
        yield xs.get(k, None), ys.get(k, None)

rawDescription: Python: Fast and minimalistic way to zip and pair matching elements in two lists


code: addRectFilled(pict, x+100, (h-(maxLength/10))-volumes[n], 30, volumes[n], blue)

rawDescription: How to colour maixum and minimun of each bar in bar graph in python?

description: Colour maixum and minimun of each bar in bar graph in python


code:
x = input("Who to check for? ")
for i in myList:
    if i.name == x:
        print("Name: {0}\nEmail: {1}".format(i.name, i.email))
        break
else:
    # this is only run if 'break' was not executed inside of the loop
    print("{0} is not on the manifest.".format(x))

rawDescription: How to check if instance object's attribute within a list is equal to a value

description: Check if instance object's attribute within a list is equal to a value


code:
with open('highscores.txt', 'rb') as f:
    reader = csv.reader(f)
    scores = (row[-1] for row in reader)
    intscores = [int(score) for score in scores]

rawDescription: How to display top 10 highscores from a comma separated value (.txt) file in Python (Pygame)

description: Display top 10 highscores from a comma separated value (.txt) file in Python (Pygame)


code:
# ~/.pythonrc
# enable syntax completion
try:
    import readline
except ImportError:
    print("Module readline not available.")
else:
    import rlcompleter
    readline.parse_and_bind("tab: complete")

rawDescription: How do I add tab completion to the Python shell?

description: Add tab completion to the Python shell


code:
import myscript
import myscript2

myscript.function_from_script1()
myscript2.function_from_script2()

rawDescription: Python - how do I call external python programs?


code:
class node(object):
    def __init__(self, value, children = []):
        self.value = value
        self.children = children

    def __str__(self, level=0):
        ret = "\t"*level+repr(self.value)+"\n"
        for child in self.children:
            ret += child.__str__(level+1)
        return ret

    def __repr__(self):
        return '<tree node representation>'

rawDescription: Printing a Tree data structure in Python


code:
'''Set 1 - this
is another
mul\'tiline
string'''
'''Set 2 - this
is' a\\nother
mul\'''tiline
st''ring'''

rawDescription: Python regular expression on single quoted string with escaped single quotes


rawDescription: indexing spherical subset of 3d grid data in numpy

description: Indexing spherical subset of 3d grid data in numpy


rawDescription: splitting an array into two smaller arrays in python

description: Splitting an array into two smaller arrays in python


code:
from dateutil import parser
s = "2012-02-20T17:41:01Z"
parser.parse(s)
parser.parse(s).strftime('%B %d, %Y')

rawDescription: Get the date from span tags

description: Get the date from span tags


code:
rel = np.diff(input, axis=1) / input[:, :-1]
win = as_strided(rel, shape=(rel.shape[0], rel.shape[1]-79, 80),
                 strides=rel.strides + rel.strides[1:])

rawDescription: Pandas time series operations

description: Pandas time series operations


code: backname = name[::-1]

rawDescription: How do I slice a sequence to get the last item?

description: Slice a sequence to get the last item


rawDescription: Column filtering on trace file

description: Column filtering on trace file


code:
set_sim(['Player9','Player4'], .02)
set_sim(['Player3','Player4'], .8)
set_sim(['Player12','Player4'], 1.5)
get_other_players('Player4')

rawDescription: How to make array of array of dictionaries in python

description: Make array of array of dictionaries in python


rawDescription: Move some part of column to another python


code:
ax = (
    df.set_index('E', append=True)  # set E as part of the index
      .stack()                      # pull A - D into rows
      .to_frame()                   # convert to a dataframe
      .reset_index()                # make the index into reg. columns
      .rename(columns={'level_2': 'quantity', 0: 'value'})  # rename columns
      .drop('level_0', axis='columns')   # drop junk columns
      .pipe((seaborn.boxplot, 'data'), x='E', y='value', hue='quantity', order=[1, 2])
)
seaborn.despine(trim=True)

rawDescription: Python Side-by-side box plots on same figure


code: lst = [int(item) for item in lst]

rawDescription: How to remove quotation list in python

description: Remove quotation list in python


code:
def rubikstring(s):
    import string
    cumu = ''
    for c in s:
        if c in string.ascii_letters:
            if cumu: yield cumu
            cumu = ''
        cumu += c
    if cumu: yield cumu

rawDescription: Most efficient way of splitting strings like rubik's cube notations in python?


code:
from heapq import merge
from itertools import groupby, ifilter

def get_click_entries(key):
    with open('clicks.csv', 'rb') as f_clicks:
        for entry in ifilter(lambda x: int(x[0]) == key, csv.reader(f_clicks)):
            entry.insert(4, '')  # add empty missing column
            yield entry

# First create a set holding all column 0 click entries

with open('clicks.csv', 'rb') as f_clicks:
    csv_clicks = csv.reader(f_clicks)
    click_keys = {int(cols[0]) for cols in csv_clicks}

with open('buys.csv', 'rb') as f_buys, \
    open('clicks.csv', 'rb') as f_clicks,   \
    open('merged.csv', 'wb') as f_merged:

    csv_buys = csv.reader(f_buys)
    csv_clicks = csv.reader(f_clicks)
    csv_merged = csv.writer(f_merged)

    for k, g in groupby(csv_buys, key=lambda x: int(x[0])):
        if k in click_keys:
            buys = sorted(g, key=lambda x: (x[1], x[2]))
            clicks = sorted(get_click_entries(k), key=lambda x: (x[1], x[2]))
            csv_merged.writerows(merge(buys, clicks))       # merge the two lists based on the timestamp
            click_keys.remove(k)
        csv_merged.writerows(g)

    # Write any remaining click entries

    for k in click_keys:
        csv_merged.writerows(get_click_entries(k))

rawDescription: Need to merge 2 large csv files row by row in python


code: output_list, key_list = my_function(...)

rawDescription: Python No Action on 2nd Statement After 'IF'


code:
print ("Pig Latin") #welcoming message for the program.

word = input("Input a word in English ") #user input defined variable

def pigtranslator(): #function that does translation from english to pig language
  if 1 > 0: #true
    wordlen = word.len #assigns the length of word to a variable
    translation == word[1:wordlen] + word[0] + 'ay' #translates the word
    print (trasnlation) #prints the translation

  else:
    print("The word you've entered is not correct. Please enter a new word")

return

pigtranslator()

rawDescription: Why does my function not run once I run the module and input?


rawDescription: How can the symmetric difference between two lists of two-element sublists be obtained?


code:
import operator
min(data, key=operator.itemgetter(1))

rawDescription: tuple pairs, finding minimum, python

description: Tuple pairs, finding minimum, python


code:
from .forms import HOUR_CHOICES

hour_display = dict(HOUR_CHOICES).get(form.hour.data)

rawDescription: Get selected text from a form using wtforms SelectField


code: camera = Camera(simple_camera, total_level_width, total_level_height)

rawDescription: Add scrolling to a platformer in pygame

description: Add scrolling to a platformer in pygame


rawDescription: How to access a specific class instance by attribute in python?

description: Access a specific class instance by attribute in python


code:
from collections import OrderedDict

d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
sorted_dict = OrderedDict(sorted(d.items(), key=lambda t: t[0]))

rawDescription: Ordered Dictionary is not sorting

description: Ordered Dictionary is not sorting


rawDescription: Find index in a list of dictionaries

description: Find index in a list of dictionaries


rawDescription: Access ORM models from different classes in Odoo/OpenERP


code:
(None and True) is None
[] and True
[] and False

rawDescription: Python numpy.nan and logical functions: wrong results


code: varObj = datasetObj.varlist['ID']

rawDescription: How to find the index value of a variable in SPSS Python

description: Find the index value of a variable in SPSS Python


code:
# Read Dataframe
df = pd.read_csv('product.csv')

rawDescription: Pandas: Create New Column using Values in Subgroup of Other Columns


code:
x = 10000
y = 10
print([(item, item+(x//y-1)) for item in range(1, x, x//y)])

rawDescription: Python split equally

description: Python split equally


code:
import gzip
gzip.GzipFile(fileobj=io.BytesIO(), mode='w').writable()

rawDescription: Pass io.BytesIO object to gzip.GzipFile and write to GzipFile


code:
numList = [1,4,10]
sum(numList)

rawDescription: Input to list and operate on it

description: Input to list and operate on it


code:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'wsgi', 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'wsgi', 'static', 'media')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'yourjdproject', 'static'),)
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'yourjdproject', 'templates'),)

rawDescription: Deploying a local django app using openshift


rawDescription: Counting qualitative values based on the date range in Pandas


code:
wav = wave.open("piano2.wav")
string_wav = wav.readframes(wav.getnframes())
print(audioop.avg(string_wav, wav.getsampwidth()))
# wav.rewind()
print(audioop.max(string_wav, wav.getsampwidth()))

rawDescription: What type of file is the "sound fragment" parameter for audioop?


rawDescription: round exponential float to 2 decimals

description: Round exponential float to 2 decimals


code:
with open("pages_Romance") as f:
    urls = f.readlines()

# Do stuff with urls
urls.remove(unwanted_line)
# etc.

with open("pages_Romance", "w") as f:
    f.writelines(urls)

rawDescription: Deleting a line just after reading it

description: Deleting a line just after reading it


code:
def menu_helper(self, menu, menu_id, name, help, handler, sep=True):
    menu_obj = wx.Menu()
    if sep:
        menu_obj.AppendSeparator()
    menu_item = menu_obj.Append(menu_id, name, help)
    self.Bind(wx.EVT_MENU, handler, menu_item)
    self.MainMenu.Append(menu_obj, menu)

rawDescription: Automating a wxPython main menu setup?

description: Automating a wxPython main menu setup


code:
result = [key for key, value in my_dict.items() if value >= n]
result.sort()
return result

rawDescription: How to return a list of words that occur n or more times in a text?

description: Return a list of words that occur n or more times in a text


code:
import sys
sys.coinit_flags = 0

import pythoncom
import win32com.client

# ... outside the thread function ...
x = win32com.client.Dispatch("someCOMobject")

# ... inside the thread function ...
pythoncom.CoInitialize(pythoncom.COINIT_MULTITHREADED)
# com calls here for x
pythoncom.CoUninitialize()

rawDescription: How to launch win32 applications in separate threads in Python

description: Launch win32 applications in separate threads in Python


code:
def foo(cursor):
    ...

def foo(cur):
        cur.execute(...)

def bar(cur):
    cur.execute(...)
    foo(cur)

with Transaction() as cursor:
    foo(cursor)

with Transaction() as cursor:
    bar(cursor)

rawDescription: Sharing MySQLdb transactions across functions


code:
def _walk (self, starting_node) :
    while starting_node is not self._nil :
        for x in self._walk(starting_node.left):
            yield x
        yield starting_node
        starting_node = starting_node.right

rawDescription: Building a generator from a recursive algorithm


rawDescription: How can I create a list of players in python

description: Create a list of players in python


code:
def generate_image(fr,to,lat1,lon1,lat2,lon2):
    return spatial_matrix.plot_spatial_data(data_array,data_array.shape[0],data_array.shape[1],float(lon1)/10000,float(lon2)/10000,float(lat1)/10000,float(lat2)/10000,fr,to)

rawDescription: Passing values between modules in Python


code: (gender, age), val = height_by_gender_and_agegroup(person)

rawDescription: returning multiple values in python

description: Returning multiple values in python


code:
setlst = {tuple(x[-3:]) for x in lst}
newlst = list(map(list, setlst))

rawDescription: A set of unique lists

description: A set of unique lists


code:
@menus.route('/', methods=["PUT", "POST"])
def new():
    return jsonify(request.get_json(force=True))

rawDescription: Flask request and application/json content type


code:
try:
    import bandana
except ImportError:
    pass  # Hat-wearing functions are optional
else:
    def wear(hat):
        bandana.check(hat)
        ...

rawDescription: Python: Define a function only if package exists


code:
import logging
import types

def log_newline(self, how_many_lines=1):
    # Switch handler, output a blank line
    self.removeHandler(self.console_handler)
    self.addHandler(self.blank_handler)
    for i in range(how_many_lines):
        self.info('')

    # Switch back
    self.removeHandler(self.blank_handler)
    self.addHandler(self.console_handler)

def create_logger():
    # Create a handler
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)
    console_handler.setFormatter(logging.Formatter(fmt="%(name)s %(levelname)-8s: %(message)s"))

    # Create a "blank line" handler
    blank_handler = logging.StreamHandler()
    blank_handler.setLevel(logging.DEBUG)
    blank_handler.setFormatter(logging.Formatter(fmt=''))

    # Create a logger, with the previously-defined handler
    logger = logging.getLogger('logging_test')
    logger.setLevel(logging.DEBUG)
    logger.addHandler(console_handler)

    # Save some data and add a method to logger object
    logger.console_handler = console_handler
    logger.blank_handler = blank_handler
    logger.newline = types.MethodType(log_newline, logger)

    return logger

if __name__ == '__main__':
    logger = create_logger()
    logger.info('Start reading database')
    logger.info('Updating records ...')
    logger.newline()
    logger.info('Finish updating records')

rawDescription: How to insert newline in python logging?

description: Insert newline in python logging


rawDescription: Detect whether sequence is a multiple of a subsequence in Python


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".razrada")))

rawDescription: Selenium and phantomjs not opening javascript page


code:
class MyException(Exception):
    pass

rawDescription: Python metaclasses configure classes. But can we configure metaclasses?


code:
from nltk.corpus import gutenberg
emma = gutenberg.raw(fileids='austen-emma.txt')
comma_separated = RegExConcordanceIndex(emma)
comma_separated.print_concordance(r"(?<=, )[A-Za-z]+(?=,)", demarcation='**')  # matches are enclosed in double asterisks

rawDescription: Can you do regex with concordance?

description: Do regex with concordance


code:
def scatter_plot_with_correlation_line(x, y, graph_filepath):
    plt.gca().cla()
    plt.scatter(x, y)
    axes = plt.gca()
    m, b = np.polyfit(x, y, 1)
    X_plot = np.linspace(axes.get_xlim()[0],axes.get_xlim()[1],100)
    plt.plot(X_plot, m*X_plot + b, '-')
    plt.savefig(graph_filepath, dpi=300, format='png', bbox_inches='tight')

rawDescription: Python matplotlib keeps the previous line after plotting new one


code: [s for s in l if "_L" in s]

rawDescription: match the pattern at the end of a string?

description: Match the pattern at the end of a string


code:
mask = [True] * len(orig_str) # True means keep this char
for match in matches:
    # mark all matches' positions in the mask
    wordlen = max(len(word) for word in match.groups() if word)
    mask[match.start():match.start()+wordlen] = [False] * wordlen

new_str = "".join(c for (c,i) in zip(orig_str, mask) if i)
# new_str:
# 'ts is a test sg '

rawDescription: Python regex for quickly removing any possible instances of substrings?


rawDescription: Loop through dictionary with django

description: Loop through dictionary with django


code:
x = []
while True:
    data = input()
    if data.lower() == "done":
        break
    if data not in x:
        x.append(data)

rawDescription: How to remove duplicate from string/mixed list

description: Remove duplicate from string/mixed list


code:
def capitalize(sentence):    # sentence is a string
  w = sentence.split()       # splits sentence into words eg. "hi there" to ['hi', there']
  ww = ""                   # initializes new string to empty
  for word in w:                 # loops over the list w
    ww += word.capitalize() + " "      # and capitalizes each word and adds to new list ww
  return ww                               # returns the new list

rawDescription: Capitalization of the first letters of words in a sentence using python code


code:
import re

re.search(r"(- |^)([^-]*)(,|$)", "Advertising - Roseville Chase").group(2)
Out[97]: 'Roseville Chase'

re.search(r"(- |^)([^-]*)(,|$)", "Roseville Chase").group(2)
Out[98]: 'Roseville Chase'

rawDescription: Grab everything after character if its present


code: u_val = data[1:1+ni,0].copy()

rawDescription: Python Changing Array Values in While Loop


rawDescription: Finding Deltas - Difference between elements in a Python list


code:
import re

def unuuencode (iterator, collector=None, ignore_length_errors=False):
    """
    Yield lines from iterator except when they are in an uuencode blob.

    If collector is not None, append to it the uuencoded blobs as a list
    of a list of lines, one for each uuencoded blob.
    """
    state = None  # one of { None, 'in_blob', 'closing', 'closed' }
    collectitem = None
    regex = re.compile(r'^begin\s+[0-7]{3,6}\s+.*?(?:\r?\n)?$')

    for line in iterator:
        if state == None:
            if regex.match(line):
                if collector != None:
                    collectitem = [line]
                state = 'in_blob'
                continue
            else:
                yield line

        else:
            stripped = line.rstrip('\r\n')

            if state == 'in_blob' and line.startswith('`'):
                state = 'closing'

            if state == 'closing':
                if stripped != '`':
                    raise ValueError('Expected "`" but got "%s"' % line)
                state = 'closed'
            elif state == 'closed':
                if stripped != 'end':
                    raise ValueError('Expected "end" but got "%s"' % line)
                state = None
            else:
                expect = ord(line[0:1])-32
                actual = len(stripped)
                seen = (len(stripped)-1)*6/8
                if seen != expect:
                    if not ignore_length_errors:
                        raise ValueError('Wrong prefix on line: %s '
                            '(indicated %i, 6/8 %i, actual length %i)' % (
                                line, expect, seen, actual))
                if line[0:1] != 'M':
                    state = 'closing'

            if collectitem:
                collectitem.append(line)

            if state is None:
                if collectitem:
                    collector.append(collectitem)
                    collectitem = None

            continue

rawDescription: Python - delete uuencoding lines

description: Python - delete uuencoding lines


code:
MEDIA_ROOT = os.path.join(BASE_DIR, "../media_root/Boothie/pics")
MEDIA_URL = '/media/'

rawDescription: upload_to value changes photo.name attribute

description: Upload_to value changes photo.name attribute


code: URL = "".join([e for e in text if e.endswith((".",".com",".net",".org",".edu",".gov"))])

rawDescription: Criteria for combining two list items

description: Criteria for combining two list items


code:
d = defaultdict(set)
path = "path/"
for fle in (glob.glob("*.csv")):
    with open(os.path.join(path, fle)) as f:
        r = csv.reader(f,delimiter=",")
        header = next(r)
        h1 = header.index("h1")
        h2 = header.index("h2")
        for row in r:
            d[fle].update([row[h1], row[h2]])

rawDescription: Get values from corresponding row CSV Python


code:
num1 = 0xff
num2 = 0xab
num = num1*256 + num2
print("{:x}".format(num))

rawDescription: Read multiple bytes in Hexadecimal file using python


code:
import math
import sys

f = lambda x: math.sqrt(2.0 * x + 0.25) - 0.5
g = lambda x: f(x) % 1 == 0

inp = map(int, sys.stdin.read().split()[1:])

print(" ".join("1" if g(x-1) else "0" for x in inp))

rawDescription: Infinite Sequence. Cannot process answer in 1 second


code:
import itertools

def do_it(source):
  name, items = None, []
  for item in itertools.chain.from_iterable(source):
    if is_name(item):
      if name:
        yield [name] + items
        name, items = None, []
      name = item
    else:
      items.append(item)
  yield [name] + items

rawDescription: Python: Linking Lists Together

description: Python: Linking Lists Together


rawDescription: Python overloading multiple getitems / index requests


code:
writefile() # write file with scores
print ('file written\n----')
print ('read file and print contents below')
readfile()  # read file with score

rawDescription: Write dictionary data to file

description: Write dictionary data to file


code:
@list_route(methods=['get'], url_path='retrieve_by_username/(?P<username>\w+)')
def getByUsername(self, request, username ):
    user = get_object_or_404(User, username=username)
    return Response(UserSerializer(user).data, status=status.HTTP_200_OK)

rawDescription: Django-REST: Get User by username instead of primary-key


code:
import klepto
d = klepto.archives.dir_archive('saveme', serialized=True, cached=False)
d.update(globals())
d.keys()

rawDescription: Delete a Variable that has been Pickled

description: Delete a Variable that has been Pickled


code: vals = list(x['custtypeA_nondp'] for x in s)

rawDescription: create a list from a functions output?

description: Create a list from a functions output


rawDescription: Tabulate data frame with groupby and size methods


code:
from collections import OrderedDict
d = OrderedDict(result)

rawDescription: How to sort keys only with same values?

description: Sort keys only with same values


code:
def aux():
    return "VoG - Sucess"

class VariabilityOfGradients(object):
    aux = staticmethod(aux)

rawDescription: Can't pickle static method - Multiprocessing - Python


code:
def find(file, name):
    length = len(name)
    part = file.read(length)
    i = 0
    while True:
        if part == name:
            break
        char = file.read(1)
        if not char:
            return
        part = part[1:] + char
        i += 1
    return i, i + length, part

rawDescription: How to find substring in file?

description: Find substring in file


code:
from __future__ import print_function
import os
import sys

if __name__ == '__main__':
    if os.path.exists('obj.serialized'):
        # load a file 'obj.serialized' from disk and
        # spool through iterable
        with open('obj.serialized', 'r') as handle:
            _generator = s_load(handle)
            for element in _generator:
                print(element)
    else:
        # or create it first, otherwise
        with open('obj.serialized', 'w') as handle:
            for i in xrange(100000):
                s_dump_elt({'i' : i}, handle)

rawDescription: create working data structure in file

description: Create working data structure in file


rawDescription: Convert a list of tuples (3 elements each) to a dict {a: {b: set(c)}}


code:
mystring = "abcdefghijklmnopqrstuvwxyz"

import itertools

for L1, L2, L3, L4, L5, L6, L7, L8, L9, L10 in itertools.combinations_with_replacement(mystring, 10):
    strr = "".join([L3, L7, L2, L1, L4, L5, L6, L10, L8, L9])
    if hashlib.md5(strr).hexdigest() == 'a50e38475041f76219748ee22c4377d4':
        print ('key = {}'.format(strr))
        break

rawDescription: Key Bruteforcing

description: Key Bruteforcing


code:
def rev_list(l):
    if not l: return []
    return rev_list(l[1:]) + [l[0]]

rawDescription: How do I convert a for loop to a recursive method?

description: Convert a for loop to a recursive method


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout

kv = '''
#:import Label kivy.uix.label.Label
#:import randint random.randint

<TestWidget>
    cols: 3
    Button:
        text: 'add first'
        on_press:
            root.add_widget(Label(text=str(randint(0, 10))), index=len(root.children)-3)
            root.add_widget(Label(text=str(randint(0, 10))), index=len(root.children)-3)
            root.add_widget(Label(text=str(randint(0, 10))), index=len(root.children)-3)
    Widget
    Button:
        text: 'add last'
        on_press:
            root.add_widget(Label(text=str(randint(0, 10))))
            root.add_widget(Label(text=str(randint(0, 10))))
            root.add_widget(Label(text=str(randint(0, 10))))
'''
Builder.load_string(kv)

class TestWidget(GridLayout):
    pass

class TestApp(App):
    def build(self):
        return TestWidget()

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

rawDescription: How to .put() data in the first item in a JsonStore() in Python Kivy


code:
ANIMAL_TYPES = ('cow', 'african swallow', 'dog')
ANIMAL_TYPE_CHOICES = tuple(enumerate(ANIMAL_TYPES, start=1))

class Animal(object):

    def __init__(self, *args, **kwargs):
        self.choose_speak = {i: getattr(self, 'speak_{}'.format(
            name.replace(' ', '_'))) for (i, name) in ANIMAL_TYPE_CHOICES}

    animal_type = 1

    def speak_cow(self):
        return 'moo'

    def speak_african_swallow(self):
        return 'squawk'

    def speak_dog(self):
        return 'woof'

    def speak(self):
        return self.choose_speak[self.animal_type]()

animal = Animal()
animal.speak()

rawDescription: Choosing a method based on a field value in a Django model


code:
def manageprocs(proclist):
    """
    Check a list of subprocesses tuples for processes that have ended and
    remove them from the list.

    Arguments:
        proclist: a list of (process, input filename, output filename)
                tuples.
    """
    nr = '# of conversions running: {}\r'.format(len(proclist))
    logging.info(nr)
    sys.stdout.flush()
    for p in proclist:
        pr, ifn, ofn = p
        if pr is None:
            proclist.remove(p)
        elif pr.poll() is not None:
            logging.info('Conversion of {} to {} finished.'.format(ifn, ofn))
            proclist.remove(p)
    sleep(0.5)

rawDescription: How to process sub-batches of asynchronous jobs?

description: Process sub-batches of asynchronous jobs


code:
def setr(self, r):
    self.r = r
    self.d = None

def getd(self):
    if not self.d is None:
        return self.d
    self.d = self.r * 2 # Our expensive calculation
    return self.d

rawDescription: Object attributes that are linked to others: how to maintain consistency?


code: process_names = [proc.name for proc in psutil.process_iter()]

rawDescription: Python - get process names,CPU,Mem Usage and Peak Mem Usage in windows


code:
from collections import defaultdict
from datetime import datetime

basket = [['cheese', '2015/04/16', 'junk'],['apple', '2015/04/15', 'other junk'],['apple', '2015/03/15', 'dessert'],['cheese', '2017/04/16', 'pie'],['banana', '2015/04/16', ''],['cheese', '2017/04/10', '']]

d = defaultdict(list)
for item in basket:
    d[item[0]].append(item[1:])

print([[key, max(values, key=lambda x: datetime.strptime(x[0], "%Y/%m/%d"))] for key, values in d.items()])

rawDescription: Remove older elements from a list

description: Remove older elements from a list


code:
import datetime
from io import StringIO
import pandas

datafile = StringIO("""\
jday,value
2013-01,1
2013-02,2
2013-100,8
2013-200,9
""")

dateparser = lambda x: datetime.datetime.strptime(x, '%Y-%j')
df = pandas.read_csv(datafile, parse_dates=True, date_parser=dateparser, index_col=[0])

rawDescription: Pandas datetime with Julian Day

description: Pandas datetime with Julian Day


code:
call_price = call_price if call_price != None else 0

if country_code not in collected_statistics:
    collected_statistics[country_code] = {'CallDuration' : [call_duration],
                                          'CallPrice' : [call_price]}
else:
    collected_statistics[country_code]['CallDuration'] += [call_duration]
    collected_statistics[country_code]['CallPrice'] += [call_price]

rawDescription: Python Adding multiple data points in a dict from CSV file


code:
set1 = [np.array([1, 0, 0]), np.array([-1, 0, 0]), np.array([0, 1, 0])]
count = 0
count
s1 = np.row_stack((set1))
count2

rawDescription: Finding sets of vectors that sum to zero


rawDescription: Why can I call all these methods that aren't explicitly defined in a class?


rawDescription: How to flatten tuple created using zip transformation in PySpark

description: Flatten tuple created using zip transformation in PySpark


code: desired_list = [list(tup)+[value] for tup in tuple_list]

rawDescription: How to append one value to every tuple within a list?

description: Append one value to every tuple within a list


rawDescription: import csv matrix to create a weighted and directed network in networkx python

description: Import csv matrix to create a weighted and directed network in networkx python


code:
subjects= parent_object['subject_set']
for i in list(subjects):
    if i['number'] in ('0000','0001'): #some subjects you want to delete
        subjects.remove(i)

rawDescription: How can i edit the json in python and save

description: Edit the json in python and save


code:
def make_vars2(L):
    return dict(enumerate(L, start=1))

t = make_vars2(L)
print(t[1])
# (1, 0, 0)

rawDescription: How to iteratively create new variables to store the ith value of a list

description: Iteratively create new variables to store the ith value of a list


code: df.sort(['a', 'b'], ascending=[True, False])

rawDescription: How to sort a dataFrame in python pandas by two or more columns?

description: Sort a dataFrame in python pandas by two or more columns


code:
rapport.append(Paragraph('  Toto is a naugthy boy ', styles['Left']))
rapport.append(Paragraph('  Toto is a naugthy boy ', styles['Left']))

rawDescription: Defining our own colors (RGB ?) for Intra-paragraph markup color in reportlab


code:
sod_hng_hhl_lst = [ ('Adam', 'widgets', 5769),
                    #... etc
                  ]

rawDescription: spliting list and adding values

description: Spliting list and adding values


code:
list(locators)
yMaxValue
locator

rawDescription: Compare and grab items attributes

description: Compare and grab items attributes


code: root.bind('<KP_Enter>', func)

rawDescription: How can I bind the Enter key to my tkinter window

description: Bind the Enter key to my tkinter window


code: d['name'] = line.find('div', {'class':'torrentname'}).find('a').text

rawDescription: Removing Tags from HTML Parsed with BeautifulSoup


code: guess_my_number(1, 10)

rawDescription: "Guess my number" game with a while loop


code:
class requireMeta(type):

    _requiredFunc = 'function'

    def __new__(cls, *args):
        # base classes, dictionary of functions
        bases, funcs = args[1], args[2]
        # skip the check for the base class
        # which inherits from object
        if not bases[0].__name__ == 'object':
            try:
                # run requireSuper for the function 'function'
                cls.requireSuper(funcs[cls._requiredFunc])
            except KeyError:
                # if it doesn't exist, complain.
                warnings.warn("Function: {} must be defined!".format(cls._requiredFunc))
        return super(requireMeta, cls).__new__(cls, *args)

    @staticmethod
    def requireSuper(func):
        """
        Functionality is the same as described already.
        """
        f_name = func.func_name
        other_names = func.func_code.co_names
        if not all(val in other_names for val in [f_name, 'super']):
            warnings.warn("Super must be defined on function: " + f_name)
        return func

rawDescription: How to enforce (with a warning) that parent functions are called by the children that override them?

description: Enforce (with a warning) that parent functions are called by the children that override them


rawDescription: Translating a gridded csv file with numpy


code:
def zoo_desc(args):
    y = int(args[2])
    describe_me = zoo[y]
    print ('{}, {}'.format(describe_me[0], describe_me[1]))

def zoo_list(args):
    for index, entry in enumerate(zoo):
        print ('{}: {}'.format(index, entry[0]))

handlers = {
        'zoo list': zoo_list, # List the animals in the zoo.
        'zoo desc': zoo_desc  # Describe the indexed animal, aka 'zoo desc x'
        }

zoo = [
('cat', 'a cute feline'),
('mouse', 'a cute rodent'),
('rat', 'an uncute rodent')
]

x = input()
while (x):
    for a in handlers:
        if x.startswith(a):
            handlers[a](x.split()) # When we call a handler, we also pass it the arguments

    x = input()

rawDescription: python: input for function from command line

description: Python: input for function from command line


code:
if request.META['HTTP_USERNAME']:
    blah
else:
    blah

rawDescription: How to check contents of incoming HTTP header request

description: Check contents of incoming HTTP header request


rawDescription: Truncating division in Python 3.2

description: Truncating division in Python 3.2


code:
for item in your_list:
   if item[0] == m and item[1] == m:
       return item[2]

rawDescription: Converting a list of lists into a multi-dimensional list in python


code:
key = lambda i: (int(i[0]), i[1])
tuple(chain.from_iterable(sorted(d.items(), key=key)))

rawDescription: How can I convert a dictionary to a tuple in python?

description: Convert a dictionary to a tuple in python


code:
import multiprocessing.connection
import subprocess
import socket
import sys, os

## Listen for connection from remote process (and find free port number)
port = 10000
while True:
    try:
        l = multiprocessing.connection.Listener(('localhost', int(port)), authkey="secret")
        break
    except socket.error as ex:
        if ex.errno != 98:
            raise
        port += 1  ## if errno==98, then port is not available.

proc = subprocess.Popen((sys.executable, "subproc.py", str(port)), stdout=subprocess.PIPE, stderr=subprocess.PIPE)

## open connection for remote process
conn = l.accept()
conn.send([1, "asd", None])
print(proc.stdout.readline())

rawDescription: Python multiprocessing: How can I RELIABLY redirect stdout from a child process?


code:
for z in zones:
    z_lines = z.splitlines()
    # Regex patterns to make the required parameters
    key = re.findall('\"(.*)\"', z_lines[0])[0]
    secret = re.findall('\"(.*)\"', z_lines[2])[0]
    name = re.findall('\"(.*)\"', z_lines[5])[0]
    master = re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', z_lines[15])[0]

rawDescription: Extracting BIND parameters to build a JSON query


code:
def f(df):
    mask = (df.hasTattoo == "Y").cumsum() <= 1
    return df[mask]

df.groupby("person").apply(f)

rawDescription: Using pandas to drop all observations in a group after a condition has been met


code:
import urllib
import mimetypes

def guess_type_of(link, strict=True):
    link_type, _ = mimetypes.guess_type(link)
    if link_type is None and strict:
        u = urllib.urlopen(link)
        link_type = u.headers.gettype() # or using: u.info().gettype()
    return link_type

rawDescription: How to check the url is either web page link or file link in python

description: Check the url is either web page link or file link in python


code:
try:
    from urlparse import urljoin  # Python2
except ImportError:
    from urllib.parse import urljoin  # Python3

rawDescription: Resolving a relative url path to its absolute path


code:
scheduled = Logged([], obj_name="scheduled")
scheduled.append
scheduled.append(3)
scheduled.extend([1,2])
isinstance(scheduled, list)
scheduled

rawDescription: Generic object "watcher" proxy to wrap collection objects to log state-changes (add/del)


code:
with open('example1.csv', 'w') as result:
    writer = csv.writer(result, delimiter=",")
    writer.writerow(('Correct?', 'Successes', 'Failures'))
    for row in list_results:
        columns = [c.strip() for c in row.strip(', ').split(',')]
        writer.writerow(columns)

rawDescription: csv: writer.writerows() splitting my string inputs

description: Csv: writer.writerows() splitting my string inputs


code:
import numpy as np
import itertools as IT
import matplotlib.pyplot as plt
N = 50
nbin = 10

xs = [np.array([i,i,i+1,i+1]) for i in range(N)]
ys = [np.array([i,i+1,i,i+1]) for i in range(N)]
masses = np.arange(N)

heatmap = 0
xedges = np.linspace(0, N, nbin)
yedges = np.linspace(0, N, nbin)

for x, y, mass in IT.izip(xs, ys, masses):
    hist, xedges, yedges = np.histogram2d(
        x, y, bins=[xedges, yedges], weights=np.ones_like(x)*mass)
    heatmap += hist

extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
heatmap = np.flipud(np.rot90(heatmap))
fig, ax = plt.subplots()
ax.imshow(heatmap, extent=extent, interpolation='nearest')
plt.show()

rawDescription: Create a stacked 2D histogram using different weights


code:
A = np.zeros(1, dtype='i4, f4, f4')
A+A

rawDescription: Array operations on heterogeneous numpy arrays


code:
def periodic(scheduler, interval, action, actionargs=()):
  scheduler.enter(interval, 1, periodic,
                  (scheduler, interval, action, actionargs))
  action(*actionargs)

rawDescription: Schedule a repeating event in Python 3

description: Schedule a repeating event in Python 3


code:
input = raw_input("Please enter your numbers separated by commas: ")
inputList = input.split(',')              # creates a list from comma delimeters
intList = [int(i) for i in inputList]     # converts to int list
uniqueList = set(intList)                 # removes duplicates
sortedList = sorted(uniqueList)           # converts to ints and sorts

rawDescription: How do I sort, get rid of numbers and organize?

description: Sort, get rid of numbers and organize


rawDescription: decoding json in python

description: Decoding json in python


code:
for row in get_log().findAll('tr'):
    for cell in row.findAll('td'):
        print (cell.text)
        logfile.write('{}\n'.format(cell.text))
        i += 1
    if i == 400:
        break

rawDescription: Limiting BeautifulSoup output

description: Limiting BeautifulSoup output


code:
import ctypes
from ctypes.wintypes import BYTE, WORD, DWORD, WCHAR

kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

class OSVERSIONINFO(ctypes.Structure):
    _fields_ = (('dwOSVersionInfoSize', DWORD),
                ('dwMajorVersion',      DWORD),
                ('dwMinorVersion',      DWORD),
                ('dwBuildNumber',       DWORD),
                ('dwPlatformId',        DWORD),
                ('szCSDVersion',        WCHAR * 128))
    def __init__(self, *args, **kwds):
        super(OSVERSIONINFO, self).__init__(*args, **kwds)
        self.dwOSVersionInfoSize = ctypes.sizeof(self)
        kernel32.GetVersionExW(ctypes.byref(self))

class OSVERSIONINFOEX(OSVERSIONINFO):
    _fields_ = (('wServicePackMajor', WORD),
                ('wServicePackMinor', WORD),
                ('wSuiteMask',        WORD),
                ('wProductType',      BYTE),
                ('wReserved',         BYTE))

def errcheck_bool(result, func, args):
    if not result:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

kernel32.GetVersionExW.errcheck = errcheck_bool
kernel32.GetVersionExW.argtypes = (ctypes.POINTER(OSVERSIONINFO),)

def get_os_major_version():
    info = OSVERSIONINFO()
    return info.dwMajorVersion

rawDescription: Python ctypes - Getting 0 with GetVersionEx function


code:
import json

decoded = json.loads(encoded)

rawDescription: How to convert a JSON string into a Python data structure

description: Convert a JSON string into a Python data structure


code:
def remove_sensitive(data):
    for key in data:
        if key == "Name":
            data[key] = "Not Stored!"
    return data

rawDescription: Python remove or replace key

description: Python remove or replace key


rawDescription: Simplify this dictionary of lists into a single list containing all/only unique values


code:
def powers(n):
    return [2**i for i in range(1, n+1)]

rawDescription: I need a function that start with a positive integer(n) and returns a list of powers of 2, starting with 2


code:
new_dict = {}
for k, v in some_dict.iteritems():
    new_dict.setdefault(v, []).append(k)

rawDescription: Find all Key-Elements by the same Value in Dicts


code:
s = 'I love %(x)s and %(y)s, he loves %(x)s and %(y)s.'
s % {"x" : "apples", "y" : "oranges"}

rawDescription: python about multiple %s in a string

description: Python about multiple %s in a string


code:
import matplotlib.pyplot as plt
import matplotlib as mpl

plt.viridis()

fig=plt.figure()
c_ax=plt.subplot(199)

cb = mpl.colorbar.ColorbarBase(c_ax,orientation='vertical')

c_ax.yaxis.set_ticks_position('left')

plt.savefig('my_colorbar.png')

rawDescription: Matplotlib colorbar ticks on left/opposite side


code:
rmax = ax.get_rmax()
theta_startstop = [2*[-np.pi/10],2*[np.pi/4.2]]
r_startstop = [[0,0.1*rmax],[0.9*rmax,rmax]]
notchcolor = ['red', 'blue']
for i in range(len(r_startstop)):
    ax.plot(np.array(theta_startstop[i]), np.array(r_startstop[i]),
            lw=3, c=notchcolor[i])
ax.set_rmax(rmax)

rawDescription: matplotlib: polar plots with a 'notch'

description: Matplotlib: polar plots with a 'notch'


code:
textA = 'The first paragraph of the book is written well'
textB = 'the book is written well'
text_diff = textA.lower().replace(textB.lower(), '')

rawDescription: how to change index value in python lists

description: Change index value in python lists


code: result = ','.join(set(text.split(',')))

rawDescription: How to get rid of duplicate entries in a comma separated string

description: Get rid of duplicate entries in a comma separated string


code:
def some_dark_magic_with_iterable(iterable, nelems):
    try:
        while True:
            res = []
            while len(res) < nelems:
                res.append(iterable.next())
            yield res
    except StopIteration:
        if res:
            yield res

rawDescription: Take a few elements from an iterable, do something, take a few elements more, and so on


code:
import sys
if ("--parameter2" in sys.argv) and ("--parameter1" not in sys.argv):
    parser.error("parameter1 must be given if parameter2 is given")

rawDescription: python, argparse: enable input parameter when another one has been specified

description: Python, argparse: enable input parameter when another one has been specified


code:
import glob
import pandas as pd

for filename in glob.glob('*.txt'):
    df = pd.read_csv(filename)
    df['total_sum'] = df[["column1", "column2", "column3"]].sum(axis=1)  # sum total reads
    df.plot(kind='bar')

rawDescription: How to unpack a pandas Panel created with a dictionary?

description: Unpack a pandas Panel created with a dictionary


code: self.font = tkFont.Font(size = PIXEL_HEIGHT)

rawDescription: Python/Tkinter: expanding fontsize dynamically to fill frame


rawDescription: How to remove ugly row in pandas.dataframe

description: Remove ugly row in pandas.dataframe


code:
from multiprocessing import Pool
pool = Pool(4)
all(pool.map(foo, l))

rawDescription: Python: parallelizing any/all statements


code:
# assign what we've done above to df_down
df_down = df.groupby(s).std().set_index(s.index[4::5])

df_up = df_down.reindex(range(20)).bfill()

rawDescription: Pandas' equivalent of resample for integer index


rawDescription: How to add a value to a key in dictionary in Python

description: Add a value to a key in dictionary in Python


code:
[[[num, position, text[op]]
  for (num, position, text), op in zip(chunk, [slice(-4, None), slice(None), slice(4)])]
 for chunk in results]

rawDescription: Python: slicing elements of lists in lists in lists differently depending on sublist


code: [(i,j) for (i,j) in zip(a,x) if i >= 4]

rawDescription: Find the indices of elements greater than x


code:
from sklearn.feature_extraction.text import CountVectorizer
countvec = CountVectorizer()
countvec.fit_transform(df.title)

rawDescription: Efficient way to create term density matrix from pandas DataFrame


code:
class CustomUserChangeList(ChangeList):
    def __init__(self, request, model, list_display, list_display_links,
                 list_filter, date_hierarchy, search_fields, list_select_related,
                 list_per_page, list_max_show_all, list_editable, model_admin):
        list_per_page = get_user_list_limit()
        super(CustomUserChangeList, self).__init__(request, model, list_display, list_display_links,
            list_filter, date_hierarchy, search_fields, list_select_related,
            list_per_page, list_max_show_all, list_editable, model_admin)

rawDescription: Django contrib admin views limit customization


code:
{'data': {'address': {'city': 'anycity',
                      'postal': 'somepostal',
                      'street': 'some road'},
          'id': 1,
          'title': 'home'}}

rawDescription: python: serialize a dictionary into a simple html output

description: Python: serialize a dictionary into a simple html output


rawDescription: Trying to find a best fit line for multiple noisy sine waves


code:
import sys

file_name = 'parsers.lex_parser'
class_name = 'LexParser'

__import__(file_name)
Parser = getattr(sys.modules[file_name], class_name)

rawDescription: Dynamically import and create class instance


code:
def f(op, x, y):
    return op(x, y)

def add(x, y):
    return x + y

f(add, 10, 7) #gives 17

rawDescription: lambda in python

description: Lambda in python


code:
# This setup script builds a single-file Python inprocess COM server.
#
import modulefinder
import win32com, sys
for p in win32com.__path__[1:]:
    modulefinder.AddPackagePath("win32com",p)
for extra in ["win32com.shell"]:
    __import__(extra)
    m = sys.modules[extra]
    for p in m.__path__[1:]:
        modulefinder.AddPackagePath(extra, p)

from distutils.core import setup
import py2exe
import sys
# If run without args, build executables, in quiet mode.
if len(sys.argv) == 1:
    sys.argv.append("py2exe")
    sys.argv.append("-q")

class Target:
    def __init__(self, **kw):
        self.__dict__.update(kw)
        # for the versioninfo resources
        self.name = "Python TestServer"

################################################################
# pywin32 COM pulls in a lot of stuff which we don't want or need.

CImtg = Target(
    description = "Sample COM Server",
    # what to build.  For COM servers, the module name (not the
    # filename) must be specified!
    modules = ["imtg_server"],
    # we only want the inproc server.
    )

excludes = ["pywin", "pywin.debugger", "pywin.debugger.dbgcon",
            "pywin.dialogs", "pywin.dialogs.list"]

options = {
    "bundle_files": 1, # create singlefile exe
    "packages": ["imtg_server"],
    "compressed": 1, # compress the library archive
    "excludes": excludes,
    "dll_excludes": ["w9xpopen.exe"] # we don't need this
    }

setup(
    options = {"py2exe": options},
    zipfile = None, # append zip-archive to the executable.
    com_server = [CImtg]
    )

rawDescription: Python Com Server unable to create instance when wrapped with py2exe - error object has no attribute


rawDescription: extracting numbers from a string in a list via regex

description: Extracting numbers from a string in a list via regex


code:
from matplotlib import pyplot as plt
ax = plt.axes()
ax.text(0.5, 0.5, r'{\tiny tiny text} normal text {\Huge HUGE TEXT}')

rawDescription: Python: Matplotlib: how to print ONE text with different sizes in it?


rawDescription: How to parse json text data with python

description: Parse json text data with python


code: {{ sqs.spelling_suggestion }}

rawDescription: django-haystack: how to access the spelling suggestions on the template?

description: Django-haystack: how to access the spelling suggestions on the template


code:
def get_input(board):
    # my conditions go here
    return direction

rawDescription: Use program to input in a different program?


code:
times = df.loc[mask, 'Time']
# 1    19
# 7    31
# 9    36
# Name: Time, dtype: int64

rawDescription: Iterate through rows in pandas dateframe in a cleaner way using .iterrows() and keep track of rows inbetween specific values


code:
import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-k', action='store_true')
group.add_argument('-r', action='store_true')
group.add_argument('-b', action='store_true')
group.add_argument('-p', action='store_true')
parser.parse_args()

rawDescription: need help for python command line argument using argparse

description: Need help for python command line argument using argparse


code:
@app.route('/', methods = ['POST'])
def choose():
    print( request.form.get('SNOWY OWL',None),"CLICKED!")
    return render_template('index.html')

rawDescription: How do I use Flask to pass a Python function input from an HTML form?

description: Use Flask to pass a Python function input from an HTML form


code:
parser.add_argument('--io', nargs=2, type=int, metavar=('input', 'output'), help='set input (1 to 64) -> output (1 to 4).')
# ...
args = parser.parse_args(argv[1:])

input, output = args.io
if input < 1 or 64 < input:
    raise ValueError("input:{!r} must be between 1 and 64.".format(input))
if output < 1 or 4 < output:
    raise ValueError("output:{!r} must be between 1 and 4.".format(output))

rawDescription: python-argparse: assign a choice to each argument

description: Python-argparse: assign a choice to each argument


code: (individual, (area_id, datetime))

rawDescription: PySpark - Combining Session Data without Explicit Session Key / Iterating over All Rows


code:
cols = df.columns.tolist()
numeric_list_of_cols = [cols.index(i) for i in list_of_columns]

rawDescription: pandas get numpy ndarray using series.values

description: Pandas get numpy ndarray using series.values


code:
import sys

def is_not_digit(s):
    return not s.isdigit()

def drop_digits(s):
    return filter(is_not_digit, s)

filepath = raw_input('Input file: ')
with open(filepath) as f:
    sys.stdout.writelines(drop_digits(line) for line in f)

rawDescription: How to remove numeric character in my input text?

description: Remove numeric character in my input text


code: test = sorted(test, key=lambda x: len(x) if type(x)==list else 1)

rawDescription: Sort order of lists in multidimensional array in Python


code:
s = u'Tannh‰user'
"".join((c if ord(c) < 128 else '_' for c in s))

rawDescription: Regular expression that finds and replaces non-ascii characters with Python


code: df

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

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


code:
indexed_sentence = []
for x in Sentence:
    indexed_sentence.append(Sentence.index(x))

rawDescription: Replace the words in a list with the position of each word


code:
from geopy.geocoders import Nominatim
g = Nominatim()
location = g.reverse("43.0667, -89.4")  # Reverse lookup of Madison, WI
print(location.raw['address']['state'])

rawDescription: Is there a way to pull coordinates that fall in a certain state out of an array of lats and lons in python


code: print(list(['{:02X}'.format( int(i, 16) ^ 0xBA)  for i in initial_list]))

rawDescription: How to XOR hex values in a list with another fixed hex value


code:
x = build_cdf({"a":0.2, "b":0.3, "c":0.5});
y = [sample_from_cdf(x) for i in range(0,100000)];
print (len([t for t in y if t == "a"]))   # 19864
print (len([t for t in y if t == "b"]))   # 29760
print (len([t for t in y if t == "c"]))   # 50376

rawDescription: Sampling keys due to their values

description: Sampling keys due to their values


code: from processors import makesoup

rawDescription: Python 3: module in same directory as script: "ImportError: No module named"


code:
part_names = []
for part in ASM_list[0].parts:
    part_names.append(part.name)

rawDescription: Python extract properties from list of listed objects


code:
t 1
n1   t t 2
n2   t t t 3
n3

rawDescription: How to find index of a character after space in python

description: Find index of a character after space in python


code:
[
    [[regex(p, s) for p in patterns] for s in strings]
    for strings, patterns in zip(a, b)
]

rawDescription: list comprehension on multiple lists of lists

description: List comprehension on multiple lists of lists


code:
fs_multitexture = '''
$HEADER$

// New uniform that will receive texture at index 1
uniform sampler2D texture1;

void main(void) {

    // multiple current color with both texture (0 and 1).
    // currently, both will use exactly the same texture coordinates.
    gl_FragColor = frag_color * \
        texture2D(texture0, tex_coord0) * \
        texture2D(texture1, tex_coord0);
}
'''

rawDescription: Kivy, Mask Widget Canvas

description: Kivy, Mask Widget Canvas


code:
processes = []
for i in range(4):
    p = Process(target=fonction, args=((process_id),filearg[file],t0))
    p.start()
    proc = psutil.Process(p.pid)
    proc.set_cpu_affinity([i])
    processes.append(p)

while True:
    for i, p in enumerate(processes):
        if not p.is_alive():
            # this process finished. Replace with a new one.
            p.join()
            new_p = Process(...)
            new_p.start()
            proc = psutil.Process(new_p.pid)
            proc.set_cpu_affinity([i])
            processes[i] = new_p

rawDescription: p.join() in Python 2

description: P.join() in Python 2


code:
clf = [clf_nb, clf_dt]

cross_clf = [ crossV(x) for x in clf ]

df = pd.concat( cross_clf )

rawDescription: How to use a for loop to append the data frame generated from a function in python

description: Use a for loop to append the data frame generated from a function in python


code:
s.index.names = [None, "Gene"]
gene = s.reset_index("Gene")[["Gene"]]
gene
gene.join(df)

rawDescription: Adding list of values to rows, turning the dataframe into long format afterwards


rawDescription: Combining two lists into a list of lists


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

# Your "list of 600 values"...
x = np.linspace(0, 10, 600)

# Evaluate a polynomial at each location in `x`
y = -1.3 * x**3 + 10 * x**2 - 3 * x + 10

plt.plot(x, y)
plt.show()

rawDescription: Transform polynomial graph - Multiply by a list of values


code:
from collections import MutableMapping
import random

class RandomChoiceDict(MutableMapping):
    """
    Dictionary-like object allowing efficient random selection.

    """
    def __init__(self):
        # Add code to initialize from existing dictionaries.
        self._keys = []
        self._values = []
        self._key_to_index = {}

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

    def __setitem__(self, key, value):
        try:
            index = self._key_to_index[key]
        except KeyError:
            # Key doesn't exist; add a new one.
            index = len(self._keys)
            self._key_to_index[key] = index
            self._keys.append(key)
            self._values.append(value)
        else:
            # Key already exists; overwrite the value.
            self._values[index] = value

    def __delitem__(self, key):
        index = self._key_to_index.pop(key)
        # Remove *last* indexed element, then put
        # it back at position 'index' (overwriting the
        # one we're actually removing) if necessary.
        key, value = self._keys.pop(), self._values.pop()
        if index != len(self._key_to_index):
            self._keys[index] = key
            self._values[index] = value
            self._key_to_index[key] = index

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

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

    def random_key(self):
        """Return a randomly chosen key."""
        if not self:
            raise KeyError("Empty collection")
        index = random.randrange(len(self))
        return self._keys[index]

    def popitem_random(self):
        key = self.random_key()
        value = self.pop(key)
        return key, value

rawDescription: How to get a random value in a very large python dictionary

description: Get a random value in a very large python dictionary


code:
ax2.set_xlim(xmin, xmax)
ax2.set_ylim(ymin, ymax)

rawDescription: With MatPlotLib, how do I apply autoscaled axes from one graph to a separate graph?


code:
import wsgiref.simple_server
remote_server = wsgire.simple_server('localhost', 8000, app)
# app here is just your Flask() application!

# as before, set timeout to zero so that you can go right back
# to your event loop if there are no requests to handle
remote_server.timeout = 0

def process_remote_requests():
    remote_server.handle_request()

rawDescription: Building an HTTP API for continuously running python process


rawDescription: NumPy append vs Python append

description: NumPy append vs Python append


code:
mylist = ['a','b','c','d']
mydict = {}
for val in mylist:
    mydict.setdefault(val,[])
    mydict[val].append(1)

rawDescription: Dictionary value initialization on lookup


code:
text_node = doc.createTextNode('some my text')
elem.appendChild(text_node)
elem.setAttribute('key', 'my value')

rawDescription: Copy and Write XML Node in Python

description: Copy and Write XML Node in Python


code:
app.wsgi_app = SharedDataMiddleware(
    app.wsgi_app,
    {'/static': os.path.join(os.path.dirname(__file__), 'static')},
    cache=False)

rawDescription: Zombie SharedDataMiddleware on Python Heroku


code: f = fs.getfirst('failas')

rawDescription: How does cgi.FieldStorage store files?

description: How does cgi.FieldStorage store files


code:
x = 'foo,bar'.split(',')
print('\n'.join(x))

rawDescription: How to return more than one value over multiple lines

description: Return more than one value over multiple lines


code: pd.Index(ts).dayofyear  # may work

rawDescription: How to find the number of the day in a year based on the actual dates using Pandas?

description: Find the number of the day in a year based on the actual dates using Pandas


rawDescription: Post picture to Tumblr using Python

description: Post picture to Tumblr using Python


code:
data = random.rand(10,10)

plot(data[:,0],data[:,1])

rawDescription: Python - Plotting a graph from an array where the data in the array is from a data file


code:
import numpy as np
arr = np.array(lst)
zip(*np.where(arr==arr.max()))

rawDescription: getting all the tiles with the maximum value in a 2d grid (a multidimensional list)

description: Getting all the tiles with the maximum value in a 2d grid (a multidimensional list)


code:
import pandas as pd

customer = pd.DataFrame({'Email': [
    "bob@example.com",
    "jim@example.com",
    "joe@gmail.com"], 'First Name': [
    "Bob",
    "Jim",
    "Joe"]})

blacklist = pd.DataFrame({'Domain': ["gmail.com", "outlook.com"]})

invalid_emails = tuple(blacklist['Domain'])

df = customer[customer['Email'].apply(lambda s: not s.endswith(invalid_emails))]

print(df)

rawDescription: Python Pandas - something like ISIN but "contains" vs "exact" match


code:
def bitfield(n):
    return [int(digit) for digit in bin(n)[2:]] # [2:] to chop off the "0b" part

rawDescription: Integer to bitfield as a list

description: Integer to bitfield as a list


code: a % b

rawDescription: Find the division remainder of a number

description: Find the division remainder of a number


code:
whitelist = {'city', 'name', 'region', 'zipcode', 'phone', 'address'}
{k: dict1[k] for k in dict1.viewkeys() & whitelist if dict1[k]}

rawDescription: check if dictionary key has empty value

description: Check if dictionary key has empty value


code:
from Crypto.PublicKey import RSA
RSAkey = RSA.generate(1024)
getattr(RSAkey.key, 'n')
getattr(RSAkey.key, 'p')
getattr(RSAkey.key, 'q')

rawDescription: Using RSA in Python

description: Using RSA in Python


code:
array([[ True,  True, False, False, False, False],
       [ True,  True, False, False, False, False],
       [False, False,  True,  True, False, False],
       [False, False,  True,  True, False, False],
       [False, False, False, False,  True,  True],
       [False, False, False, False,  True,  True]], dtype=bool)

rawDescription: Fill scipy / numpy matrix based on indices and values


code:
import ipaddress
ipaddress.IPv4Address('1.2.3.4').packed
ipaddress.IPv4Address(b'\x01\x02\x03\x04')
str(ipaddress.IPv4Address(b'\x01\x02\x03\x04'))

rawDescription: converting IP string to hex for dpkt.IP

description: Converting IP string to hex for dpkt.IP


code:
mainPanel = wx.lib.scrolledpanel.ScrolledPanel(self, -1,style=wx.SIMPLE_BORDER)
mainPanel.SetupScrolling()
panel1 = wx.lib.scrolledpanel.ScrolledPanel(mainPanel, -1, style=wx.SIMPLE_BORDER)
panel2 = wx.lib.scrolledpanel.ScrolledPanel(mainPanel, -1, style=wx.SIMPLE_BORDER)
panelSizer = wx.BoxSizer(wx.HORIZONTAL)
panelSizer.Add(panel1)
panelSizer.Add(panel2)
mainPanel.SetSizer(panelSizer)

rawDescription: Adding many scrolledpanels to one scrolledPanel in wxPython


code:
{
    "sensor_info": {
        "name" : "fish tank",
        "unpack_commands" : "floatle:32, floatle:32"
    },

    "database_query" : "INSERT INTO fish_tank (pH, temperature, timestamp) VALUES (%s, %s, TIMESTAMP(NOW(5)))",
}

rawDescription: Storing python dictionary in json file and substitute values upon reading


code:
class MyLineEdit(QLineEdit):
    def __init__(self, *args):
        QLineEdit.__init__(self, *args)
        self.char = ""

    def event(self, event):
        if (event.type() == QEvent.KeyPress):
            self.char = "%c" % (event.key()) #this line above the next
            self.emit(SIGNAL("keyPressed"))
            return True

        return QLineEdit.event(self, event)

rawDescription: Use keypress to input text in QLineEdit AND emit signal in PyQt4


code: ball = sphere(pos=(1,2,1), radius=0.5)

rawDescription: Making Random 3-D Shapes in Python

description: Making Random 3-D Shapes in Python


code:
def create_matrix(self, particle_id=None):
    if particle_id is not None:
        ...

rawDescription: Python args and kwargs arguments confusion


code:
def save(self, *args, **kwargs):
    new_url = re.sub('watch\?v=','v/',self.video_url)
    if new_url:
        self.video_url = new_url
        super(Video, self).save(*args, **kwargs)

rawDescription: django - using regex to strip and replace a urlfield

description: Django - using regex to strip and replace a urlfield


rawDescription: How to iterate for specific elements in a list?

description: Iterate for specific elements in a list


code:
# call foo without arguments, using defaults
def fooDefault():
    foo()

# call foo with keyword arguments
def fooKw():
    foo(a=10, b=20, c=30, d=40)

rawDescription: Why do argument-less function calls execute faster?


code:
for t in threading.enumerate():
    for item in t.__dict__:
       if isinstance(item, tuple):  # Each thread's `local` state is kept in a tuple stored in its __dict__
           print("Thread's local is %s" % t.__dict__[item])

rawDescription: Python: Getting all the items out of a `threading.local`


code:
class MRRecalculateSupportsPipeline(base_handler.PipelineBase):

    def run(self, user_key):
        # ...
        yield mapreduce_pipeline.MapreducePipeline('user_recalculate_supports',
                'myapp.mapreduces.user_recalculate_supports_map',
                'myapp.mapreduces.user_recalculate_supports_reduce',
                'mapreduce.input_readers.DatastoreInputReader', output_writer_spec=None,
                mapper_params={"""..."""})

rawDescription: Mapreduce on GAE Python - Cause ReducePipeline to issue callback on finalize?


code: range(len(s))

rawDescription: Longest string in alphabetic order

description: Longest string in alphabetic order


code:
for n in start_list:
    square_list.append(n)

rawDescription: Python, issue with for loop and List can't figure it out


code: scipy.sparse.spdiags(v, 0, len(v), len(v)) * A

rawDescription: How to best row-scale a SciPy sparse matrix?

description: Best row-scale a SciPy sparse matrix


rawDescription: django-tables2 edit yesno parameter for all BooleanColumn

description: Django-tables2 edit yesno parameter for all BooleanColumn


code:
@view_config(name='login_widget',
             renderer='templates/account_login_widget.pt')
def login_widget(request):
    return {'username': ...}

rawDescription: ajax widgets in pyramid and chameleon

description: Ajax widgets in pyramid and chameleon


code: Counter(t for u in l['users'] for p in u['photos'] for t in p['tags'])

rawDescription: Python dictionary add in value / optimize


rawDescription: Python : correct use of set_completion_display_matches_hook


code: player_test = Player()

rawDescription: Why cant I access a property of an instance from another class?


code:
def main():
    """To print a names numeric value"""
    name = input("Enter your full name here: ")
    return sum( ord(c) - 96 for c in name.replace(' ', '').lower())

rawDescription: Numerical value of a name

description: Numerical value of a name


code:
D = np.sum((qX[:, None, :] - trainX[None, :, :2]) ** 2, -1)
ind = np.argpartition(D, k, axis=1)[:, :k]
predictions = trainX[ind, 2].mean(1)

rawDescription: Calculating distance between a set of points using np matrix calculations


code:
import webapp2

class MainPage(webapp2.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write('Hello, WebApp World!')

app = webapp2.WSGIApplication([('/', MainPage)])

""" Old code:
def main():
  run_wsgi_app(app)

if __name__ == '__main__':
  main()
"""

rawDescription: threadsafe cannot be enabled with CGI handler

description: Threadsafe cannot be enabled with CGI handler


code:
groups = df.groupby(["A","B"])

print(groups.get_group(('Banana', 'OtherBrand')))

print(groups.get_group(('Banana', 'BananaBrand')))

rawDescription: How to identify "keys" of a tuple/list of 3-item tuples?

description: Identify "keys" of a tuple/list of 3-item tuples


code:
5 % 5  # last index + 1
-1 % 5  # first index - 1
3 % 5  # middle + 1

rawDescription: Binding list indices with modulus, want to make a circular list


code:
import dis
def comprehension(f, iterable): return [f(i) for i in iterable]
dis.dis(comprehension)
dis.dis(comprehension.__code__.co_consts[1])

rawDescription: Python 3: Most efficient way to create a [func(i) for i in range(N)] list comprehension


code: a = b = c

rawDescription: What is the purpose of the '==' operator when comparing values vs '='?


code:
def try_these(start_obj, *args) :
        obj = start_obj
        for trythat in args :
            if obj is None :
                return None
            try :
                if isinstance(trythat, str) :
                    obj = getattr(obj, trythat)
                else :
                    method, opts = trythat
                    obj = getattr(obj, method)(*opts)
            except :
                return None
        return obj
src = try_these(soup, ('find', ({'id':'item-pic'},),),
                      'img',
                      ('get', ('src',),) )

rawDescription: Elegant way to try/except a series of BeautifulSoup commands?


code: my_dic.update((key, []) for key in my_dic)

rawDescription: clearing a dictionary but keeping the keys

description: Clearing a dictionary but keeping the keys


code:
from bs4 import BeautifulSoup
from urlparse import urlparse, parse_qs
html = 'NIHAO'
parse_qs(urlparse(soup.find("a", text="NIHAO")['href']).query)['sort'][0]

rawDescription: Beautifulsoup extract string partially

description: Beautifulsoup extract string partially


code:
hello = r'\n'
hello
len(hello)
list(hello)

rawDescription: I do not understand Python raw string

description: I do not understand Python raw string


rawDescription: Get the directory path of absolute file path in Python


rawDescription: Aggregating data and getting sum and counts


code:
from zope import interface

class ITest(interface.Interface):
    required_attribute = interface.Attribute(
        """A required attribute for classes implementing this interface.""")
    def required_method():
        """A required method for classes implementing this interface."""

class ITestFactory(interface.Interface):
    """Creates objects providing the ITest interface"""
    def __call__(a, b):
        """Takes two parameters"""

class Test(object):
    interface.implements(ITest)
    interface.classProvides(ITestFactory)

    def __init__(self, a, b):
        self.required_attribute = a*b

    def required_method():
        return self.required_attribute

rawDescription: Can zope.interface define how a class' __init__ method should look?


code: np.triu(A.T,1) + A

rawDescription: Convert triangle matrix to square (Python | NumPy)?


code:
import csv
import collections
import itertools

grid = collections.Counter()

with open("connect.csv", "r", newline="") as fp:
    reader = csv.reader(fp)
    for line in reader:
        # clean empty names
        line = [name.strip() for name in line if name.strip()]
        # count single works
        if len(line) == 1:
            grid[line[0], line[0]] += 1
        # do pairwise counts
        for pair in itertools.combinations(line, 2):
            grid[pair] += 1
            grid[pair[::-1]] += 1

actors = sorted(set(pair[0] for pair in grid))

with open("connection_grid.csv", "w", newline="") as fp:
    writer = csv.writer(fp)
    writer.writerow([''] + actors)
    for actor in actors:
        line = [actor,] + [grid[actor, other] for other in actors]
        writer.writerow(line)

rawDescription: Turning project data into a relationship matrix