code:
import sqlite3
import datetime

# connect to db
con = sqlite3.connect('myfile.db', detect_types=sqlite3.PARSE_DECLTYPES)

date_i_want = datetime.date(2001, 1, 6)
cur.execute('SELECT * FROM data WHERE date = ?', (date_i_want,))
row = cur.fetchone()

rawDescription: Python question relating to dated values in a csv file


code: grid_copy = copy.deepcopy(grid)

rawDescription: Python - function changing input list, although I made a copy


code:
for idx, a in enumerate(foo):
    foo[idx] = a + 42

rawDescription: Change value of currently iterated element in list in python


code:
class exampleitem(Item):
    ex1 = Field()
    ex2 = Field()
    ex3 = Field()

    def keys(self):
        return ['ext1', 'ext2', 'ext3']

rawDescription: How to order xml with item fields in scrapy?

description: Order xml with item fields in scrapy


code:
import json
from jinja2 import Template

json_str = '''[{"first_name": "John", "last_name": "Smith", "user_id": 4,
    "address": null}, {"first_name": "Jane", "last_name": "Heart",
    "user_id": 5, "address": null}, {"first_name": "Dom",
    "last_name": "Robinsons", "user_id": 6, "address": null},
    {"first_name": "Pete", "last_name": "Hand", "user_id": 7,
    "address": null}]'''

users = json.loads(json_str)

tmpl = Template('''

   {% for user in users %}

{{ user['first_name'] }}

   {% endfor %}

''')

print(tmpl.render(users = users))

rawDescription: Jinja2 - How to loop a json list?

description: Jinja2 - How to loop a json list


code:
from sqlalchemy.orm import validates
class MyClass(Base):
    # ...
    data = Column(BLOB)

    @validates("data")
    def _set_data(self, key, value):
        return func.compress(value)

rawDescription: mysql Compress() with sqlalchemy

description: Mysql Compress() with sqlalchemy


code: b = BoxLayout(orientation='vertical', size_hint_y=None, height=0)

rawDescription: Increase kivy scrollview window size with increase widget entries


code:
fig_object = pickle.load(open('sinus.pickle','rb'))
fig_object.show()

rawDescription: Matplotlib save file to be reedited later in ipython


rawDescription: Passing unique dictionary addresses to class instances


code:
from scipy.signal import filter_design, filtfilt

# a signal whose power at 50Hz varies over time
sfreq = 128.
nsamples = 454912
time = np.arange(nsamples) / sfreq
sinusoid = np.sin(2 * np.pi * 50 * time)
pow50hz = np.zeros(nsamples)
pow50hz[nsamples / 4: 3 * nsamples / 4] = 1
x = pow50hz * sinusoid + np.random.randn(nsamples)

# Chebyshev notch filter centered on 50Hz
nyquist = sfreq / 2.
b, a = filter_design.iirfilter(3, (49. / nyquist, 51. / nyquist), rs=10,
                               ftype='cheby2')

# filter the signal
xfilt = filtfilt(b, a, x)

fig, ax2 = plt.subplots(1, 1)
ax2.hold(True)
ax2.plot(time[::10], x[::10], label='Raw signal')
ax2.plot(time[::10], xfilt[::10], label='50Hz bandpass-filtered')
ax2.set_xlim(time[0], time[-1])
ax2.set_xlabel('Time')
ax2.legend(fancybox=True)

rawDescription: Efficiently compute 50Hz content of signal


code:
conn = engine.connect()
conn.execute("SET DateStyle='somestring'")
# work with conn

rawDescription: How to specify the PostgreSQL DateStyle property with SQLAlchemy ORM

description: Specify the PostgreSQL DateStyle property with SQLAlchemy ORM


code:
foo = MagicalEncryptor()
foo.ciphertext = foo.encrypt(data)
key = foo.key

bar = key.decryptor()
data = bar.decrypt(ciphertext)

rawDescription: Pythonic solution to cryptographic agility that avoids violating Liskov's substitution principle


code:
def newtons_method(n):
    n = float(n)  #Force float arithmetic
    nPlusOne = n - (pow(n,3) + n - 1)/(3*pow(n,2) +1)
    while 1:
        yield nPlusOne
        n = nPlusOne
        nPlusOne = n - (pow(n,3) + n - 1)/(3*pow(n,2) +1)

approxAnswer = newtons_method(1.0)   #1.0 can be any initial guess...

rawDescription: fixed point iteration algorithm

description: Fixed point iteration algorithm


code: parse_requests(line, user_agent_vals)

rawDescription: Is it better to use globals or pass in arguments to map functions?


rawDescription: Nested dictionaries in classes

description: Nested dictionaries in classes


code: sum(len(sent) for sent in inaugural.sents()) / len(inaugural.sents())

rawDescription: Average sentence length for every text in corpus (python3 & nltk)


code:
# 2D case
combine_arrays((x,y))
# 3D case
combine_arrays((x,y,z))

rawDescription: Combine multi-dimentional data in numpy

description: Combine multi-dimentional data in numpy


code:
def myClick(self):
    x = self.myvalue.get()
    value = int(x)
    self.grades = [] # <---- to hold grade Entry objects.
    for n in range(self.value):
        Label(self.Frame2,text="Grade"+str(n+1)).place(x=10,y=30+(30*n))
        grade = Entry(self.Frame2, width=10)
        grade.place(x=70,y=30+(30*n))
        self.grades.append(grade) # <---

def getValues(self):
    total = 0
    for grade in self.grades: # <--- iterate over entry objects.
        try:
            total += float(grade.get())
        except ValueError:
            print('Invalid value for grade: {}'.format(grade.get()))
    avg = total / len(self.grades)
    print('Average = {}'.format(avg))

rawDescription: Used a for loop to create a certain number of entry boxes but can only .get last value from last entrybox


code:
import datetime

# your dictionnary
data = {...}

start = datetime.datetime.fromtimestamp(0)
step = datetime.timedelta(seconds=3600)

stop = datetime.datetime.now()
while start <= stop:
    key = start.strftime('%d/%m/%Y %H:%M:%S')
    if key not in data:
        data[key] = 0
    start+= step

rawDescription: Is there a way to "fill in" a series of datetime stamps?


rawDescription: Scraping a page with awkwardly formatted JSON in python


code:
comprehension = [
    [first_element for second_element in second
     if first_element == second_element]  # a list with some number
                                          # of first_elements in it
     for first_element in first]  # the outer list

rawDescription: Comprehensive `for...in` different from standard loops


code:
from collections import namedtuple
class Point(namedtuple('Point', 'x y z')):
    def __add__(self, other):
            return Point((i + j for i, j in zip(self, other)))
    def __mul__(self, other):
            return sum(i * j for i, j in zip(self, other))
    def __sub__(self, other):
            return Point((i - j for i, j in zip(self, other)))
    @property
    def mod(self):
            from math import sqrt
            return sqrt(sum(i*i for i in self))

rawDescription: Forcing immutability on an object

description: Forcing immutability on an object


code:
aeval = Interpreter()
time_start = time.time()
expr = aeval.parse(userinput_function)
for item in database_xy:
    aeval.symtable['x'] = item['x']
    item['y_aeval'] = aeval.run(expr)
time_end = time.time()

rawDescription: Evaluating a mathematical expression (function) for a large number of input values fast


rawDescription: Python: how to make a recursive generator function


code:
from datetime import datetime
datetime.strptime("31/12/2009", "%d/%m/%Y").strftime("%Y/%m/%d")

rawDescription: Convert DD/MM/YYYY HH:MM:SS into MySQL TIMESTAMP


code: qs['t'] = ['tokenHashed']

rawDescription: Updating Query In URL With Urlib In Python


code:
def capture(f):
    locals = sys._getframe(1).f_locals
    preexisting = locals.get(f.__name__)
    if preexisting is not None and hasattr(preexisting, 'functions'):
        preexisting.functions.append(f)
        return preexisting

    @functools.wraps(f)
    def _wrapper(*args, **kwargs):
        return (func(*args, **kwargs) for func in _wrapper.functions)
    _wrapper.functions = [f]
    return _wrapper

rawDescription: Capture functions within a closure scope


code: stdin, stdout, stderr = ssh.exec_command("""python -c 'import os; print os.path.isfile("r/a/etc/portal/db/secrets/db.shared")'""")

rawDescription: Not able get the return value of command print os.path.isfile(filename) from with in paramiko connection


code:
import os

with open("output.txt", "w") as a:
    for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'):
       for filename in files:
         f = os.path.join(path, filename)
         a.write(str(f) + os.linesep)

rawDescription: Python: List all the file names in a directory and its subdirectories and then print the results in a txt file


code: re.findall(regex, line)

rawDescription: Python parsing list of string

description: Python parsing list of string


code:
class Tree(object):
    ...
    def in_order(self):
        if self.left is not None:
            for value in self.left.in_order():
                yield value
        yield self.value  #  <-- yielding the value of the node, not the node itself
        if self.right is not None:
            for value in self.right.in_order():
                yield value

...

tree = Tree(...)

in_order_values = list(tree.in_order())

rawDescription: Python in order traversal to a flat list


code:
[a['href'] for a in sample1.find_all('a', href=True)]
[a['href'] for a in sample2.find_all('a', href=True)]

rawDescription: Python: Parse all elements under a div

description: Python: Parse all elements under a div


code:
def sorting(numbers_array):
    return sorted(numbers_array, key=abs)

sorting((-20, -5, 10, 15))

rawDescription: Sorting by absolute value without changing to absolute value


rawDescription: Finding a palindrome from anagrams

description: Finding a palindrome from anagrams


rawDescription: getting datetime from python string when tzinfo is present

description: Getting datetime from python string when tzinfo is present


rawDescription: What is the best way make an array out of my data in python?


code:
def my_function(a=10, b=None):
    if b is None:
        b = a

rawDescription: function default value not defined

description: Function default value not defined


code:
def set_pos_matrix(self, pos_matrix_):
    self.pos_matrix = list(list(l) for l in pos_matrix_)
    # Avoiding copying problems by creating copy of list and lists in list

rawDescription: Instance variable gets modified automatically


code:
import httplib2
from apiclient.discovery import build

from model import Credentials

def create_service(service, version, creds=None):
  """Create a Google API service.

  Load an API service from a discovery document and authorize it with the
  provided credentials.

  Args:
    service: Service name (e.g 'mirror', 'oauth2').
    version: Service version (e.g 'v1').
    creds: Credentials used to authorize service.
  Returns:
    Authorized Google API service.
  """
  # Instantiate an Http instance
  http = httplib2.Http()

  if creds:
    # Authorize the Http instance with the passed credentials
    creds.authorize(http)

  return build(service, version, http=http)

rawDescription: Push a Timeline Card to a given User ID

description: Push a Timeline Card to a given User ID


code:
import bz2
import urllib.parse
another_message = 'BZh91AY%26SY%80%F4C%E8%00%00%02%13%80%40%00%04%00%22%E3%8C%00+%00%22%004%D0%40%D04%0C%B7%3B%E6h%B1AIM%3D%5E.%E4%8Ap%A1%21%01%E8%87%D0'
bz2.decompress(urllib.parse.unquote_to_bytes(another_message.replace('+', '%20'))).decode('ascii')

rawDescription: Python Challenge level 17 in Python 3

description: Python Challenge level 17 in Python 3


code: H = self.__class__()

rawDescription: inheriting networkx Graph and using nx.connected_component_subgraphs

description: Inheriting networkx Graph and using nx.connected_component_subgraphs


rawDescription: Finding numbers with a certain format

description: Finding numbers with a certain format


code:
import itertools
from scipy.spatial.distance import cdist

# making sure that IDs are integer
example_array = np.asarray(example_array, dtype=np.int)
# we assume that IDs start from 1, so we have n-1 unique IDs between 1 and n
n = example_array.max()

indexes = []
for k in range(1, n):
    tmp = np.nonzero(example_array == k)
    tmp = np.asarray(tmp).T
    indexes.append(tmp)

# calculating the distance matrix
distance_matrix = np.zeros((n-1, n-1), dtype=np.float)
for i, j in itertools.combinations(range(n-1), 2):
    # use squared Euclidean distance (more efficient), and take the square root only of the single element we are interested in.
    d2 = cdist(indexes[i], indexes[j], metric='sqeuclidean')
    distance_matrix[i, j] = distance_matrix[j, i] = d2.min()**0.5

# mapping the distance matrix to labeled IDs (could be improved/extended)
labels_i, labels_j = np.meshgrid( range(1, n), range(1, n))
results = np.dstack((labels_i, labels_j, distance_matrix)).reshape((-1, 3))

print(distance_matrix)
print(results)

rawDescription: Calculating distances between unique Python array regions?


rawDescription: How to label certain x values

description: Label certain x values


code:
for x in range(N):
    x = input("")
    try:
        the_list.append(int(x))
    except ValueError:
        the_list.append(x)

rawDescription: Python Lists input- Integers and Strings


code:
nowy = open("newnum.txt","w")
for i in range(0,len(n),3):
    nowy.write("{} {} {}\n".format(n[i],n[i+1],n[i+2]))
nowy.close()

rawDescription: Split array by rows

description: Split array by rows


code: (meanx, meany) = pts.mean(axis=0)

rawDescription: Extracting polygon given coordinates from an image using OpenCV


code: d

rawDescription: Biopython class instance - output from Entrez.read: I don't know how to manipulate the output


code:
average =          np.sum(bin_middles * counts * 1) / sum(counts)
weighted_average = np.sum(bin_middles * counts * weights) / sum(counts)

rawDescription: Weighted mean in numpy/python

description: Weighted mean in numpy/python


rawDescription: Tkinter: How to make a button center itself?


rawDescription: Replace character in HTML tag with REGEX


code: self.st = [Node(0) for i in range(N * 4)]

rawDescription: Simple code in python causing unexpected behaviour


code:
class Selector(set):
    def tag(self, *tags):
        tags = set(tags)
        def decorator(func):
            if hasattr(func, "_tags"):
                func._tags.update(tags)
            else:
                func._tags = tags
            @functools.wraps(func)
            def wrapper(*args, **kwargs):
                return func(*args, **kwargs) if self & func._tags else None
            wrapper._tags = func._tags
            return wrapper
        return decorator

rawDescription: Decorator to tag functions as callable

description: Decorator to tag functions as callable


code: instance_method(arg1, arg2)

rawDescription: Different way to create an instance method object in Python


rawDescription: Is there a simple string parser for Python?


code: composed_sql = sql.format(fields=fields_string, values=values_string)

rawDescription: Python sql query insert data in columns

description: Python sql query insert data in columns


rawDescription: How to delete everything after a certain character in a string?

description: Delete everything after a certain character in a string


code: sum(len(line.split()) for line in My_list)

rawDescription: Getting word count from a python list

description: Getting word count from a python list


code:
def show_word(self):
    """ Shows the word behind the cell """
    self.hidden = not self.hidden
    self.button["text"] = str(self)

    if mem.choice1 is None:
        mem.choice1 = self
    elif mem.choice2 is None:
        mem.choice2 = self
    else:
        choice1, choice2 = mem.choice1, mem.choice2
        mem.choice1, mem.choice2 = self, None
        self.check(choice1, choice2)

def check(self, choice1, choice2):
    """ Checks if the chosen words are a pair """
    if choice1.word != choice2.word:
        for cell in (choice1, choice2):
            cell.hidden = True
            cell.button['text'] = str(cell)

rawDescription: Something wrong without any error - Includes Tkinter


code:
import json
json.loads(u'"Ñ"') == json.loads(u'"\\u00d1"')

rawDescription: Python: how to prevent Unicode representation for Latin1 characters?


code:
def procRDD(rdd, cache=True, part=False, hashp=False, npart=16):
    rdd = rdd if not part else rdd.repartition(npart)
    rdd = rdd if not hashp else rdd.partitionBy(npart)
    return rdd if not cache else rdd.cache()

rawDescription: Spark iteration time increasing exponentially when using join


code: y = "mo.group({:})".format(i)

rawDescription: How to print out the command used to execute code without executing it in Python

description: Print out the command used to execute code without executing it in Python


rawDescription: Unable to handle linspace properly

description: Unable to handle linspace properly


rawDescription: Query current directory in Python (the one the script is running from)


code: dummy = f.write("my text")

rawDescription: How to make Python file-writing faster with IDLE?

description: Make Python file-writing faster with IDLE


code:
d = collections.defaultdict(list)

for line in L:
    name, value = line.rsplit(' ',1)
    d[name].append(value)

rawDescription: Extract partial duplicates from a list of lists; return single match with record of origin of each duplicate; Python


code: P = C/(1 - PM - MktFrac - PayFrac)

rawDescription: Calculate product price based on multiple percentage factors


code:
def savetxt_sparse_compact(fname, x, fmt="%.6g", delimiter=','):
    with open(fname, 'w') as fh:
        for row in x:
            line = delimiter.join("0" if value == 0 else fmt % value for value in row.A[0])
            fh.write(line + '\n')

rawDescription: How to format in numpy savetxt such that zeros are saved only as "0"

description: Format in numpy savetxt such that zeros are saved only as "0"


code:
from itertools import groupby
l_two = [key for key, value in groupby(l_one)]

rawDescription: How to reduce lines with list comprehensions in Python?

description: Reduce lines with list comprehensions in Python


code:
@property
def x(self):
    return self._x

@x.setter
def x(self, x):
    self._x = x
    # self._y remains unchanged
    self._position[0] = x

rawDescription: property of class doesnt restrict the attribute

description: Property of class doesnt restrict the attribute


code:
acad_hist = [{'crse_id': u'GRG 302P0', 'grade': u''}, {'crse_id': u'URB 3010', 'grade': u'B+'}, {'crse_id': u'GRG 302P0', 'grade': u'D'}]

grade_list = ['CR', 'D-', 'D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+']
#let's turn grade_list into something more efficient:
grade_list = dict(zip(grade_list, range(len(grade_list)))) # 'CR' == 0, 'D-' == 1

courses = {} # keys will be crse_id, values will be grade.
for course in acad_hist:
    cid = course['crse_id']
    g = course['grade']
    if cid not in courses:
        courses[cid] = g
    else:
        if grade_list.get(courses[cid], 0) < grade_list.get(g,0):
            courses[cid] = g

rawDescription: Evaluating and removing duplicate dicts from a Python list


code:
import re
def replace_keep_case(word, replacement, text):
    def func(match):
        g = match.group()
        if g.islower(): return replacement.lower()
        if g.istitle(): return replacement.title()
        if g.isupper(): return replacement.upper()
        return replacement
    return re.sub(word, func, text, flags=re.I)
    # return re.compile(word, re.I).sub(func, text) # prior to Python 2.7

rawDescription: What's the best way to regex replace a string in python but keep its case?


code:
#file base.py
def f1(input1):
    ...
    return res1

def f2(res1, input2):
    ...
    return res2

def f3(res2):
    ...
    return res3

if __name__ == '__main__':
    r1 = f1('directoryPath')
    r2 = f2(r1, 'fileName')
    r3 = f3(r2)

rawDescription: How to create a light GUI with TkInter

description: Create a light GUI with TkInter


rawDescription: List with hex escaped values to readable string in Python


rawDescription: Python List Variable - Is it using the memory location or something?


code:
def get_value(mapping, key, default_func, *args):
    try:
        return mapping[key]
    except KeyError:
        return default_func(*args)

# ...

test_model_data = {
    'fk1': get_value(kwargs, 'fk1', fk1_factory, i),
    'fk2': get_value(kwargs, 'fk2', fk2_factory, i),
    # etc.
}

rawDescription: Using function value as kwargs.get() default


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

# create the figure
fig = plt.figure()
ax = fig.add_subplot(111)
im = ax.imshow(np.random.random((50,50)))
plt.show(block=False)

# draw some data in loop
for i in range(10):
    # wait for a second
    time.sleep(1)
    # replace the image contents
    im.set_array(np.random.random((50,50)))
    # redraw the figure
    fig.canvas.draw()

rawDescription: Python real time varying heat map plotting


code:
name = "Joel"
print('hello ' + name)
print('hello {0}'.format(name))

rawDescription: Python Newbie Combine Text

description: Python Newbie Combine Text


code:
s = "a b c d"
w = s.split()
zip(w, w[1:])

rawDescription: making a list of tuples from a string,,

description: Making a list of tuples from a string,,


code:
import re

soup.find(text=re.compile("^hello"))  # find text starting with "hello"
soup.find(text="hello world!!")  # find text with an exact "hello world!!" text
soup.find(text=lambda text: text and "!!" in text)  # find text havin "!!" inside it

rawDescription: Scraping elements without an id or class from a web page using Python BeautifulSoup


rawDescription: Status bar for csv file read

description: Status bar for csv file read


code: dist = np.linalg.norm(a[1:2] - a, axis=1)

rawDescription: Is "norm" equivalent to "Euclidean distance"?


code: b = b + 's' if not b.endswith('s') else b

rawDescription: Most Pythonic and efficient way to insert character at end of string if not already there


code:
file = open('words.txt', 'r')

def reloadfile():
    file.close()
    file = open('words.txt', 'r')

rawDescription: How to make process to do some action upon user request in Python?

description: Make process to do some action upon user request in Python


code:
#!python3
s1 = b'\xce\xd2\xca\xc7\xc3\xc0\xb9\xfa\xc8\xcb'
s2 = b'\xe6\x88\x91\xe6\x98\xaf\xe7\xbe\x8e\xe5\x9b\xbd\xe4\xba\xba'
s3 = b'\x11b/f\x8e\x7f\xfdV\xbaN'
s4 = b'\x11b\x00\x00/f\x00\x00\x8e\x7f\x00\x00\xfdV\x00\x00\xbaN\x00\x00'

u1 = s1.decode('chinese')
u2 = s2.decode('utf8')
u3 = s3.decode('utf-16le')
u4 = s4.decode('utf-32le')

assert(u1==u2==u3==u4)

rawDescription: Python 2.7 and unicode

description: Python 2.7 and unicode


rawDescription: Python Mock not asserting calls

description: Python Mock not asserting calls


code:
for paragraph_text in "Hi. \nMy name is Alice.\n Let's code".split("\n"):
    body.append(paragraph(paragraph_text.strip()))

rawDescription: Python Docx Carriage Return

description: Python Docx Carriage Return


code:
import struct
from functools import partial
from itertools import imap

def to_bytes(number):
    # This can only pack an unsigned long long
    # so we need to split the number into those
    packer = partial(struct.pack, ">Q")

    # How many unsigned long longs needed to hold the number
    iterations = (number.bit_length() // 64) + 1

    # Get the parts
    sections = ((number >> i*64) & 0xFFFFFFFFFFFFFFFF for i in reversed(xrange(iterations)))

    # And map "packer" over them
    return b"".join(imap(packer, sections)).lstrip("\x00")

rawDescription: Converting integers to bytes

description: Converting integers to bytes


code:
import win32gui
import win32ui
hwnd = win32gui.FindWindow(None, windowname)
wDC = win32gui.GetWindowDC(hwnd)
dcObj=win32ui.CreateDCFromHandle(wDC)
cDC=dcObj.CreateCompatibleDC()
dataBitMap = win32ui.CreateBitmap()
dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
cDC.SelectObject(dataBitMap)
cDC.BitBlt((0,0),(w, h) , dcObj, (0,0), win32con.SRCCOPY)
dataBitMap.SaveBitmapFile(cDC, bmpfilenamename)
# Free Resources
dcObj.DeleteDC()
cDC.DeleteDC()
win32gui.ReleaseDC(hwnd, wDC)
win32gui.DeleteObject(dataBitMap.GetHandle())

rawDescription: screenshot not showing all windows in python screenshot imagegrab

description: Screenshot not showing all windows in python screenshot imagegrab


code: from __future__ import print_function

rawDescription: How can I apply a list as a variable number of arguments to the python print built-in?

description: Apply a list as a variable number of arguments to the python print built-in


code:
from mongoengine import *

class TestModel(Document):
    name = StringField(max_length=50)
    zip_file = BinaryField()

rawDescription: Saving and retrieving Blob data from MongoDB


code:
class AttachmentHandler(webapp.RequestHandler):
  def get(self):
    email = EmailMessageModel.get(self.request.get('email'))
    index = self.request.get('index')
    if index:
      index = int(index)
      filename = email.attachmentNames[index]
      self.response.headers['Content-Type'] = str(mimetypes.guess_type(filename)[0]) or 'application/octet-stream'
      self.response.out.write(email.attachmentContents[index])

rawDescription: Writing and image attachment to datastore as an avatar: Is it possible?


rawDescription: Clicking Specific button with Selenium

description: Clicking Specific button with Selenium


code: states2 = list_func(states2)

rawDescription: Loops/Functions and State abbreviations

description: Loops/Functions and State abbreviations


code: ci = np.bincount(i, weights= cij)

rawDescription: Vectorized version of for-loop + numpy.where


rawDescription: how to transform element then insert into numpy array

description: Transform element then insert into numpy array


code: y = [value for value in line.split()]

rawDescription: Python: How to separate string with comma


code:
# mainscript
if __name__ == '__main__':
    from mainmodule import main
    main()

rawDescription: PyQt lineEdit is empty when called from another script


code:
from PySide import QtCore

plugins=os.path.join(os.path.dirname(QtCore.__file__), "plugins\\imageformats")
static_files += Tree(plugins, 'plugins\\imageformats')

rawDescription: Support QtCore library path in PyInstaller


code:
options = search.QueryOptions(ids_only=True)
query   = search.Query(query_string=query_string, options=options)

rawDescription: Python Google App Engine: How to move SearchResults data into my template


code:
for label in ax.get_xticklabels():
    label.set_rotation('vertical')

rawDescription: Matplotlib Xticklabels not working

description: Matplotlib Xticklabels not working


code:
@cache.cached(timeout=100000)
def viewfunc():
    return render_template('viewtemplate.html')

rawDescription: Generate a static page from a Jinja template and serve it with Flask


code:
import array
timeit(hugeequal1, hugeequal2, 1000)
timeit(array.array('l', hugeequal1), array.array('l', hugeequal2), 1000)

rawDescription: Is there a faster way to test if two lists have the exact same elements than Pythons built in == operator?


code:
def random_fruit():
    while True:
        yield random.choice(["mango", "pomelo", "guava", "grapefruit", "watermelon"])
DoDict = {'do1': random_fruit().next}

rawDescription: How can I insert a random element into a dictionary and have it randomised whenever I call it?

description: Insert a random element into a dictionary and have it randomised whenever I call it


code:
def __init__(self, **kwargs):
    arg_vals = {
        'param1': 'default1',
        # ...
    }
    arg_vals.update(kwargs)
    for kw,arg in arg_vals.iteritems():
        setattr(self, kw, arg)

rawDescription: Improving __init__ where args are assigned directly to members


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

data = np.random.random((10, 10))

fig, ax = plt.subplots()
ax.imshow(data, extent=[10, 30, np.pi, -2*np.pi])
plt.show()

rawDescription: adding line plot to imshow and changing axis marker

description: Adding line plot to imshow and changing axis marker


code:
l = [{'name': 'abc', 'id' : 1}, {'name': 'bc', 'id' : 1}, {'name': 'c', 'id' : 1}, {'name': 'bbc', 'id' : 2}]
from collections import defaultdict
from itertools import chain
d = defaultdict(list)
T = 2
for dct in l:
    d[dct["id"]].append(dct)

print(list(chain.from_iterable(v for v in d.values() if len(v) > T)))
[{'name': 'abc', 'id': 1}, {'name': 'bc', 'id': 1}, {'name': 'c', 'id': 1}]

rawDescription: python efficient group by

description: Python efficient group by


code:
def main():
    num_file = open('numbers.txt', 'r')
    total = 0

    for num in num_file:
        print(num.rstrip('\n'), end='')
        try:
            total = total + int(num)
        except ValueError as e:
            # Catch errors if file contains a line with non number
            pass

    num_file.close()
    print('\nSum: {0}'.format(total))
    print('End of file')

main()

rawDescription: Printing integers on the same line reading from a text file


rawDescription: Regexp split string with additional conditions


code: ids = [a.get_id() for a in structure.get_atoms()]

rawDescription: Extract Columns from a Protein Data Bank (PDB) Text File


code: H *= (np.dot(V_over_WH.T, W) / W.sum(axis=0)).T

rawDescription: non-negative matrix factorization failing to converge

description: Non-negative matrix factorization failing to converge


rawDescription: python regular expression with "OR" and $ end of line

description: Python regular expression with "OR" and $ end of line


code:
N = 1000
with open('/tmp/out', 'w') as f:
    result = []
    for x in range(10**7):
        result.append('Hi\n')
        if len(result) >= N:
            f.write(''.join(result))
            result = []

rawDescription: python improving time of find line and remove line in 3Gb file

description: Python improving time of find line and remove line in 3Gb file


code:
directions = {
    "north east": (+1, -1),
    "north west": (-1, -1),
    "south east": (+1, +1),
    "south west": (-1, +1),
}

def new_position(old, direction):
    x, y = old
    dx, dy = directions[direction]
    return x + dx, y + dy

position = 100, 100
direction = "north east"

while True:
    print(position)
    position = new_position(position, direction)

rawDescription: How to change the value of an int, and recover and use the new value?

description: Change the value of an int, and recover and use the new value


rawDescription: Converting set of string values to numeric values


code:
def serve_image():
    id = request.args(0)
    filename = get_image_filename_from(id)
    stream = open(filename,'rb')
    return response.stream(stream, attachment=True, filename=filename)

rawDescription: Web2py: Serve images from action call or web service call


code:
for u in User.objects.all():
 try:
  UserProfile(user=u).save() # Add other params as needed.
 except:
  pass

rawDescription: Django - how to write users and profiles handling in best way?


code:
import numpy
a = numpy.random.random(10)
a + 1
(a + 1) * 0.25 / 4

rawDescription: how to speed up enumerate for numpy array / how to enumerate over numpy array efficiently?

description: Speed up enumerate for numpy array / how to enumerate over numpy array efficiently


code: x

rawDescription: Numpy loadtxt rounding off numbers

description: Numpy loadtxt rounding off numbers


code:
from datetime import timedelta
def my_time_delta(d1,d2):
    """
    Returns time delta as the following tuple:
        ("before|after|same", "years", "months", "days")
    """
    if d1 == d2:
        return ("same",0,0,0)

    # d1 before or after d2?
    if d1 > d2:
        ba = "after"
        d1,d2 = d2,d1 # swap so d2 > d1
    else:
        ba = "before"

    years  = d2.year - d1.year
    months = d2.month - d1.month
    days   = d2.day - d1.day

    # adjust for -ve days/months
    if days < 0:
        # get last day of month for month before d1
        pre_d1 = d1 - timedelta(days=d1.day)
        days = days + pre_d1.day
        months = months - 1

    if months < 0:
        months = months + 12
        years  = years - 1

    return (ba, years, months, days)

rawDescription: Finding the amount of time difference between dates in python


code:
scale_val = 1
ax.format_coord = lambda x, y: 'r=%d,c=%d' % (scale_val * int(x + .5),
                                             scale_val * int(y + .5))

rawDescription: In a matplotlib figure window (with imshow), how can I remove, hide, or redefine the displayed position of the mouse?


code: ['phabaa', 'phabea', 'phabia', 'phaboa', 'phabua', 'phabya', 'phabrca', 'phebaa', 'phebea', 'phebia', 'pheboa', 'phebua', 'phebya', 'phebrca', 'phibaa', 'phibea', 'phibia', 'phiboa', 'phibua', 'phibya', 'phibrca', 'phobaa', 'phobea', 'phobia', 'phoboa', 'phobua', 'phobya', 'phobrca', 'phubaa', 'phubea', 'phubia', 'phuboa', 'phubua', 'phubya', 'phubrca', 'phybaa', 'phybea', 'phybia', 'phyboa', 'phybua', 'phybya', 'phybrca', 'phrcbaa', 'phrcbea', 'phrcbia', 'phrcboa', 'phrcbua', 'phrcbya', 'phrcbrca', 'sdabaa', 'sdabea', 'sdabia', 'sdaboa', 'sdabua', 'sdabya', 'sdabrca', 'sdebaa', 'sdebea', 'sdebia', 'sdeboa', 'sdebua', 'sdebya', 'sdebrca', 'sdibaa', 'sdibea', 'sdibia', 'sdiboa', 'sdibua', 'sdibya', 'sdibrca', 'sdobaa', 'sdobea', 'sdobia', 'sdoboa', 'sdobua', 'sdobya', 'sdobrca', 'sdubaa', 'sdubea', 'sdubia', 'sduboa', 'sdubua', 'sdubya', 'sdubrca', 'sdybaa', 'sdybea', 'sdybia', 'sdyboa', 'sdybua', 'sdybya', 'sdybrca', 'sdrcbaa', 'sdrcbea', 'sdrcbia', 'sdrcboa', 'sdrcbua', 'sdrcbya', 'sdrcbrca', 'nnabaa', 'nnabea', 'nnabia', 'nnaboa', 'nnabua', 'nnabya', 'nnabrca', 'nnebaa', 'nnebea', 'nnebia', 'nneboa', 'nnebua', 'nnebya', 'nnebrca', 'nnibaa', 'nnibea', 'nnibia', 'nniboa', 'nnibua', 'nnibya', 'nnibrca', 'nnobaa', 'nnobea', 'nnobia', 'nnoboa', 'nnobua', 'nnobya', 'nnobrca', 'nnubaa', 'nnubea', 'nnubia', 'nnuboa', 'nnubua', 'nnubya', 'nnubrca', 'nnybaa', 'nnybea', 'nnybia', 'nnyboa', 'nnybua', 'nnybya', 'nnybrca', 'nnrcbaa', 'nnrcbea', 'nnrcbia', 'nnrcboa', 'nnrcbua', 'nnrcbya', 'nnrcbrca', 'mmabaa', 'mmabea', 'mmabia', 'mmaboa', 'mmabua', 'mmabya', 'mmabrca', 'mmebaa', 'mmebea', 'mmebia', 'mmeboa', 'mmebua', 'mmebya', 'mmebrca', 'mmibaa', 'mmibea', 'mmibia', 'mmiboa', 'mmibua', 'mmibya', 'mmibrca', 'mmobaa', 'mmobea', 'mmobia', 'mmoboa', 'mmobua', 'mmobya', 'mmobrca', 'mmubaa', 'mmubea', 'mmubia', 'mmuboa', 'mmubua', 'mmubya', 'mmubrca', 'mmybaa', 'mmybea', 'mmybia', 'mmyboa', 'mmybua', 'mmybya', 'mmybrca', 'mmrcbaa', 'mmrcbea', 'mmrcbia', 'mmrcboa', 'mmrcbua', 'mmrcbya', 'mmrcbrca', 'ghabaa', 'ghabea', 'ghabia', 'ghaboa', 'ghabua', 'ghabya', 'ghabrca', 'ghebaa', 'ghebea', 'ghebia', 'gheboa', 'ghebua', 'ghebya', 'ghebrca', 'ghibaa', 'ghibea', 'ghibia', 'ghiboa', 'ghibua', 'ghibya', 'ghibrca', 'ghobaa', 'ghobea', 'ghobia', 'ghoboa', 'ghobua', 'ghobya', 'ghobrca', 'ghubaa', 'ghubea', 'ghubia', 'ghuboa', 'ghubua', 'ghubya', 'ghubrca', 'ghybaa', 'ghybea', 'ghybia', 'ghyboa', 'ghybua', 'ghybya', 'ghybrca', 'ghrcbaa', 'ghrcbea', 'ghrcbia', 'ghrcboa', 'ghrcbua', 'ghrcbya', 'ghrcbrca']

rawDescription: Python script to generate words from letters and two letter combination


code: ssq = np.sum(res**2, axis=1)

rawDescription: numpy sum of squares for matrix

description: Numpy sum of squares for matrix


code:
d = defaultdict(list)
for item in data:
    d[item['CustName']].append({'PartNum': item['PartNum']})
print(d)

rawDescription: rebuild python array based on common elements

description: Rebuild python array based on common elements


code:
import argparse

parser = argparse.ArgumentParser()
grp1 = parser.add_mutually_exclusive_group(required=True)
grp2 = parser.add_mutually_exclusive_group()

group_1_options = {"action":"store_const",'dest':"vehicle"}

grp1.add_argument('--car', const="car", **group_1_options)
grp1.add_argument('--van', const='van', **group_1_options)

rawDescription: Advice for using argparse

description: Advice for using argparse


code: mask

rawDescription: Dropping rows fast from a multi-indexed data frame conditional on the level 1 index


code:
def func():
    pass
func = some_decorator(func)

rawDescription: How is this called and how can be done ( `function_name.decorator` )?


code:
seq_pow2(4)
seq_pow2(8)
seq_pow2(16)

rawDescription: Iterate through a dynamic number of for loops (Python)


code:
# We want to make an HTTP/1.1 request, but the addinfourl
# class isn't prepared to deal with a persistent connection.
# It will try to read all remaining data from the socket,
# which will block while the server waits for the next request.
# So make sure the connection gets closed after the (only)
# request.
headers["Connection"] = "close"

rawDescription: Remove HTTP "Connection" header, Python urllib2


code:
with open('c:/HashFiles/Part1.txt') as inf, open('c:/HashFiles/hashes.txt','w') as outf:
    for i in xrange(N):
        inf.next()       # skip a line

    for line in inf:
        data = line.split(',')
        hash = data[4]
        outf.write(hash + '\n')

rawDescription: parsing/extracting data from a text file. Unable to make it work

description: Parsing/extracting data from a text file. Unable to make it work


code: df.ix[df['B'].idxmax(), 'A']

rawDescription: Position of maximum value in column in pandas


code: {{ "hey there  world"|spacify }}

rawDescription: Django templates stripping spaces?

description: Django templates stripping spaces


code:
class MyForm(ModelForm):
    class Meta:
        model = MyClass
        fields = ('my_field')
        widgets = {
            'my_field': TextInput(attrs={'class': 'mycssclass'}),
        }

rawDescription: Define CSS style in Django model field

description: Define CSS style in Django model field


code:
import cv2
import numpy as np
from matplotlib import pyplot as plt
from numba import jit

# Show plot
img = cv2.imread('wave.jpg',0)
edges = cv2.Canny(img,100,200)

# http://stackoverflow.com/a/29799815/1698058
# Get index of matching value.
@jit(nopython=True)
def find_first(item, vec):
    """return the index of the first occurence of item in vec"""
    for i in range(len(vec)):
        if item == vec[i]:
            return i
    return -1

bounds = [750, 1500]
# Now the points we want are the lowest-index 255 in each row
window = edges[bounds[1]:bounds[0]:-1].transpose()

xy = []
for i in range(len(window)):
    col = window[i]
    j = find_first(255, col)
    if j != -1:
        xy.extend((i, j))
# Reshape into [[x1, y1],...]
data = np.array(xy).reshape((-1, 2))
# Translate points back to original positions.
data[:, 1] = bounds[1] - data[:, 1]

rawDescription: OpenCV: fit the detected edges

description: OpenCV: fit the detected edges


code:
from pyspark.sql.functions import udf
from pyspark.sql.types import *

schema = StructType([
    StructField("foo", FloatType(), False),
    StructField("bar", FloatType(), False)
])

def udf_test(n):
    return (n / 2, n % 2) if n and n != 0.0 else (float('nan'), float('nan'))

test_udf = udf(udf_test, schema)
df = sc.parallelize([(1, 2.0), (2, 3.0)]).toDF(["x", "y"])

foobars = df.select(test_udf("y").alias("foobar"))
foobars.printSchema()
## root
##  |-- foobar: struct (nullable = true)
##  |    |-- foo: float (nullable = false)
##  |    |-- bar: float (nullable = false)

rawDescription: Apache Spark -- Assign the result of UDF to multiple dataframe columns


code:
plt.scatter(df.kipp_macht[df.events == 1], df.luftb_hydgr_add[df.events == 1],
            'b+', label='pos')
plt.scatter(df.kipp_macht[df.events == 0], df.luftb_hydgr_add[df.events == 0],
            'rx', label='neg')

rawDescription: Ploting matrix in matplotlib, while taking indexed data for positive and negative values, returns wrong plot axis or data


rawDescription: Comparing elements in the value at two keys


rawDescription: SCons - convert all images in a directory


code:
import copy
x = [1,2,3, [4,5]]
y = copy.copy(x)
id(x)
id(y)
x.append(10)
x
y
x[3].append(20)
x
y
z = copy.deepcopy(x)
z
x[3].append(50)
x
z

rawDescription: Using list.reverse() on a copy changes the original


code:
# Create a class decorator
def decorate_foo( fooclass ):

    def bar( self ):
        return 0

    fooclass.bar = bar

# Create a class to decorate
class Foo: pass

# Decorate the class
decorate_foo( Foo )

# Use the decorated class
f = Foo()
f.bar()

rawDescription: Two classes: one for the django model and one for representing the data outside of django


code:
while np.sum(current - prev) > 0 and iter_num < max_iter:
    iter_num = iter_num+1
    prev = np.copy(current)
    current = cv2.dilate(current, kernel3)
    tmp = np.copy(current)
    current[np.where(thresh_lo == 0)] = 0

rawDescription: Image processing issues with blood vessels


rawDescription: tkinter frame border not displaying

description: Tkinter frame border not displaying


code:
stack = []
result = []
for elem in inputstring.split('|'):
    if not elem: continue
    stack.append(elem)
    result.append('|' + '|'.join(stack))

rawDescription: re string position list builder

description: Re string position list builder


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

from itertools import zip_longest
my_dict=OrderedDict((i,j) for i,*j in grouper(l,4))
my_dict

rawDescription: Python 3.4: List to Dictionary

description: Python 3.4: List to Dictionary


code:
class Generator(object):
    def __init__(self, data):
        self.data = data

    def __iter__(self):
        for x in self.data:
            yield x

rawDescription: Python: the mechanism behind list comprehension


code: newprefix = list(prefix)

rawDescription: How to make a shallow copy of a list in Python

description: Make a shallow copy of a list in Python


code: newimage = np.where(np.in1d(oldimage, vct).reshape(oldimage.shape), 0, oldimage)

rawDescription: NumPy - Image (matrix) thresholding using an intensity value matrix.


code:
point, script = [word.strip() for word in line.split('#')[0].split(';')]
point
script

rawDescription: Pythonic way of parsing this string?

description: Pythonic way of parsing this string


rawDescription: Dynamically add methods to a class in Python 3.0


code:
someList = ['foo', 'bar', 'baz']
someList += [['spam']] * 5
someList
someList[-1].append('ham')
someList
someList[-1] is someList[-2]

rawDescription: Pythonic way to add several identical values to a list


code:
def combination(string, n):
    result = []

    for i in range(0,len(string)-n+1):
        result.append(string[i:i+n])

    for i in range(len(string)-n+1,len(string)):
        result.append( string[i:i+n] + string[0:n-len(string)+i] )

    return result

rawDescription: Searching for a function similar to combinations() or how could i create one, given some 'rules'


code:
for row1 in master:
    for row2 in subsetCopy:
        if row1[0] != row2[0]:
            count=count+1
            untagged.writerow(row1)

rawDescription: Comparing two CSV files and exporting non-matches using Python


code:
to_remove = []
for index, s in enumerate(list):
    if s == "b" or s == "c":
         to_remove.append(index)

for index in reversed(to_remove):
    del list[index]

rawDescription: how to correctly modify the iterator of a loop in python from within the loop

description: Correctly modify the iterator of a loop in python from within the loop


code:
smallest_rectangle = min(list_of_rectangles,key=lambda rect:rect.area)
backpack_with_small_shoes = min(backpacks,key=lambda b: b.wearer.shoe_size)

rawDescription: Putting a pointer as a value in a method call [python]


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

np.random.seed(314)
p = pd.Series(np.random.randn(200) / 100 + 0.001)
b = pd.Series(np.random.randn(200) / 100 + 0.001)

keys = ['Portfolio', 'Benchmark']
cum = pd.concat([p, b], axis=1, keys=keys).add(1).cumprod()
cum['Active'] = cum.Portfolio - cum.Benchmark

mdd, sd, ed = max_draw_down_relative(p, b)

f, a = plt.subplots(2, 1, figsize=[8, 10])

cum[['Portfolio', 'Benchmark']].plot(title='Cumulative Absolute', ax=a[0])
a[0].axvspan(sd, ed, alpha=0.1, color='r')

cum[['Active']].plot(title='Cumulative Active', ax=a[1])
a[1].axvspan(sd, ed, alpha=0.1, color='r')

rawDescription: Maximum Active Drawdown in python

description: Maximum Active Drawdown in python


code:
import random
flips = [(slice(None, None, None),
         slice(None, None, random.choice([-1, None])),
         slice(None, None, random.choice([-1, None])))
         for _ in xrange(a.shape[0])]

rawDescription: The most effective way to random flip every image in a numpy array


code:
s = ['ab', 'abc', 'abcd', 'acd', 'bc', 'bd', 'd']
find_prefixes(s)
prefixes = find_prefixes(s)
find_prefix_suffixes(s, prefixes)

rawDescription: Left factoring using Python

description: Left factoring using Python


code:
class AstypeContext(object):

    def __init__(self, dset, dtype):
        self._dset = dset
        self._dtype = numpy.dtype(dtype)

    def __enter__(self):
        self._dset._local.astype = self._dtype

    def __exit__(self, *args):
        self._dset._local.astype = None

rawDescription: Creating reference to HDF dataset in H5py using astype


code:
import pandas as pd

# Read your data from a .csv file
df = pd.read_csv('yourdata.csv')

# Pivot table
mat = pd.pivot_table(df,index='col1',columns='col2',values='weight')

# Rebuild the index
index = mat.index.union(mat.columns)

# Build the new full matrix and fill NaN values with 0
mat = mat.reindex(index=index, columns=index).fillna(0)

# Make the matrix symmetric
m = mat + mat.T

rawDescription: Transform the relationship data with weight into a Matrix in python


code:
@classmethod
def clear_instance(cls):
    del cls.instance

rawDescription: Singleton destructor for unit testing in Python


code:
Mohammed
Ahmed
Mansour
Sami
Sameer
Ukhlof
Asfar
Virus
Ameer
AbuAlameer
Ismail
Belal
Heba
Mama
Papa

rawDescription: Python Copy specified lines from text file


rawDescription: How do I print a key without value from a dictionary that has multiple keys

description: Print a key without value from a dictionary that has multiple keys


code:
import numpy as np
size=6
X = np.random.random((size, 2))
print('Orig\n',X)
startIndex = 3
endIndex = 5
Slice=X[startIndex:endIndex].copy()
length = min(endIndex-startIndex,size-endIndex) # to check overlap
X[startIndex:startIndex+length]=X[-length:]
Left=X[:size-len(Slice)]
print('Slice\n',Slice)
print('LeftOver\n',Left)

rawDescription: Numpy: is this the fastest way to slice+'leftover' a mulltidim array?


code:
from apiclient.discovery import build

api_root = 'https://<APP_ID>.appspot.com/_ah/api'
api = 'api_name'
version = 'api_version'
discovery_url = '%s/discovery/v1/apis/%s/%s/rest' % (api_root, api, version)
service = build(api, version, discoveryServiceUrl=discovery_url)

rawDescription: how to access google datastore from an installed application on PC written in Python?

description: Access google datastore from an installed application on PC written in Python


rawDescription: Python: select most frequent using group by


code:
def pair(arg):
    # For simplity, assume arg is a pair of integers
    # separated by a comma. If you want to do more
    # validation, raise argparse.ArgumentError if you
    # encounter a problem.
    return [int(x) for x in arg.split(',')]

rawDescription: How to create argument of type "list of pairs" with argparse?

description: Create argument of type "list of pairs" with argparse


rawDescription: How to randomly change positions of non-zero entries of an array where certain rows are excluded

description: Randomly change positions of non-zero entries of an array where certain rows are excluded


code: np.array([[set(bi).issubset(set(ai))] for ai, bi in zip(map(tuple, a), map(tuple, b))])

rawDescription: NumPy check if 2D array is subset of 2D array


code:
df = pd.DataFrame({'viewed':foo, 'presented':bar}).reset_index()
df.columns = ['id', 'viewed', 'presented']

rawDescription: Pandas: Adding row by row while iterating a dictionary


code:
def reverse_list(seq):
    for index in range(len(seq)-1, -1, -1):
        yield seq[index]

rawDescription: Creating a function which reverses iterator


code:
from collections import Counter
start = Counter({w: int(n) for w, n in bar})
total = start + Counter(foo.lower().split())
# Counter({'is': 6, 'this': 4, 'a': 1, 'string': 1})

rawDescription: Weighted count of words in string using python


code:
#!/usr/bin/env python
from subprocess import Popen, PIPE

cmd = ["python", "test.py"]
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)
stdout_text, stderr_text = p.communicate(input="1\n\n")

print("stdout: %r\nstderr: %r" % (stdout_text, stderr_text))
if p.returncode != 0:
    raise RuntimeError("%r failed, status code %d" % (cmd, p.returncode))

rawDescription: How do I get all of the output from my .exe using subprocess and Popen?

description: Get all of the output from my .exe using subprocess and Popen


rawDescription: Is there a multi-dimensional version of arange/linspace in numpy?


code:
if mv in 'nN':
    Me.Position.Y += 10

rawDescription: python if statement always

description: Python if statement always


code: sums = {k: sum(i for i in v if isinstance(i, int)) for k, v in d.items()}

rawDescription: Python how to get sum of numbers in a list that has strings in it as well


code:
class DataitemSerializer(serializers.ModelSerializer):
        class Meta:
            model = Dataitem
            depth = 1 # Will include fields from related models
                      # e.g. the mod FK to AssetModel

rawDescription: Writable nested serializer in django-rest-framework?


rawDescription: How to perform arithmetic operations involving row and column in dataframe?

description: Perform arithmetic operations involving row and column in dataframe


code: l = [i for i in range(10) if i % 3 == 0 or i % 5 == 0]

rawDescription: l.append[i], object is not subscriptable?

description: L.append[i], object is not subscriptable


code:
#!/usr/bin/env python
from datetime import datetime
import parsedatetime as pdt # $ pip install parsedatetime

cal = pdt.Calendar()
for time_str in ['1 second', '2 minutes','3 hours','5 weeks','6 months','7 years']:
    diff = cal.parseDT(time_str, sourceTime=datetime.min)[0] - datetime.min
    print("{time_str:<10} -> {diff!s:>20} <{diff!r}>".format(**vars()))

rawDescription: How can I parse free-text time intervals in Python, ranging from years to seconds?

description: Parse free-text time intervals in Python, ranging from years to seconds


code:
def UploadForm(Form):
 someField = fields.CharField()
 def __init__(self, *args, **kwargs):
  #call our superclasse's initializer
  super(UploadForm,self).__init__(*args,**kwargs)
  #define other fields dinamically:
  self.fields["uploadedFile.name"]=fields.CharField()

rawDescription: How to use non valid identifiers as django form field names

description: Use non valid identifiers as django form field names


code:
c = C(None)
c.x
c.x = 15
c.x

rawDescription: Override a field in parent class with property in child class


code:
if U == 0:
   multiplier = 1 + U/100.0    # since U is 0 in this branch, U/100.0 == 0
elif U > 0:
   multiplier = 1 + U/100.0
else:
   multiplier = 1 + U/100.0    # distributive property of division

rawDescription: How to compute a percentage increase/decrease multiplier in python without if statements

description: Compute a percentage increase/decrease multiplier in python without if statements


code:
proc_memory = p.memory_values
if index <= len(self.memory) - len(proc_memory):
    self.memory[index:index + len(proc_memory)] = proc_memory

rawDescription: unpacking class variables as a list

description: Unpacking class variables as a list


code:
import pandas
collection=['1.csv','2.csv','3.csv','4.csv']

result = pandas.read_csv(collection[0])
for i in collection[1:]:
  csv = pandas.read_csv(i)
  result = result.merge(csv, on='field1')

if result:
  result.to_csv('output2.csv',index=False)

rawDescription: Python for loop to read csv using pandas


code:
import csv
import collections
...
with open(path) as f:
    entries = collections.Counter()
    total_scores = collections.Counter()
    for name,score in csv.reader(f):
        total_scores[name] += int(score)
        entries[name] += 1

rawDescription: Sorting data from a csv alphabetically, highest to lowest and average


code:
def add_page_to_index(index, url, content):
    [add_to_index(index, word, url) for word in content.split()]

rawDescription: python mapping a function

description: Python mapping a function


rawDescription: Slice vs Stride while reversing string

description: Slice vs Stride while reversing string


code:
Hello
World

rawDescription: Access to a variable defined in main

description: Access to a variable defined in main


code:
env = {'SSH_ASKPASS':'/path/to/myprog', 'DISPLAY':':9999'}
p = subprocess.Popen(['ssh', '-T', '-v', 'user@myhost.com'],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    env=env,
    preexec_fn=os.setsid
)

rawDescription: How to call ssh by subprocess module so that it uses SSH_ASKPASS variable

description: Call ssh by subprocess module so that it uses SSH_ASKPASS variable


code:
Tutor.objects.filter(
    available_times__weekday=datetime.weekday(),
    available_times__start_time__lte=time.time(),
    available_times__end_time__gt=time.time()
)

rawDescription: Maintaining teacher availability timings in database


rawDescription: Group by multiple keys and summarize/average values of a list of dictionaries


code:
Pipe1 = Pipe(scrollx)

if Pipe1.drawn == True:
    Pipe1.update()
else:
    Pipe1 = Pipe(scrollx)
    Pipe1.draw(screen)

rawDescription: Python - Pygame random obstacle height issues


code:
from django.contrib.auth.views import login
# ...
url(r"^login/$", csrf_exempt(login), {"template_name": "users/login.html"}, "login"),

rawDescription: Set django.contrib.auth.views.login as csrf_exempt


code:
mat = np.random.randn(3,6)
mat.reshape(2,9)

rawDescription: Storing these vectors but which data structure to use in Python


code: numpy.array([1, 2.0])

rawDescription: How to type check each element of 1 dimensional ndarray

description: Type check each element of 1 dimensional ndarray


code:
new_array = np.array(array, dtype = [("name", object),
                                     ("N1", int),
                                     ("N2", int),
                                     ("N3", float)])

rawDescription: Numpy - assign column data types (dtype) to existing array


code:
def wum(aList):
    pass

rawDescription: Trying to find the T(n) function and complexity in this bit of Python


code:
from itertools import groupby
f = '''\
A: 1
A: 2
A: 3
B: 4
B: 5
A: 6
C: 7
D: 8
A: 9
A: 10
A: 11
'''.splitlines(True)
coalesce = (g for key, g in groupby(f, key=lambda x: x[:1] == "A") if key)
[[res.partition(':')[-1].strip() for res in group] for group in coalesce]

rawDescription: Using `itertools.groupby()` to get lists of runs of strings that start with `A`?


code:
def tree(dg):
    def walk(root, start):
        children = dg.successors(root)
        if children:
            cur = start+1
            res = [start]
            for c in children:
                l = walk(c, cur)
                res.append(l)
                cur = l[-1]+1
            res.append(cur)
            return res
        else:
            return [start, start+1]

    roots = [i for i in dg.nodes() if dg.in_degree(i) == 0]
    assert(len(roots) == 1)
    root = roots[0]

    return walk(root, 1)

rawDescription: Tree interval representation in python

description: Tree interval representation in python


code:
BLOCK_SIZE = 16
key = b"1234567890123456"

def pad(data):
    length = BLOCK_SIZE - (len(data) % BLOCK_SIZE)
    return data + chr(length)*length

def unpad(data):
    return data[:-ord(data[-1])]

def encrypt(message, passphrase):
    IV = Random.new().read(BLOCK_SIZE)
    aes = AES.new(passphrase, AES.MODE_CBC, IV)
    return base64.b64encode(IV + aes.encrypt(pad(message)))

def decrypt(encrypted, passphrase):
    encrypted = base64.b64decode(encrypted)
    IV = encrypted[:BLOCK_SIZE]
    aes = AES.new(passphrase, AES.MODE_CBC, IV)
    return unpad(aes.decrypt(encrypted[BLOCK_SIZE:]))

rawDescription: CryptoJS and Pycrypto working together

description: CryptoJS and Pycrypto working together


code:
s = pd.Series(np.arange(5),dtype=np.float32)
s.isin([2, 4])

rawDescription: Python equivalent of the R operator "%in%"


code:
with open('infile') as f1, open('outfile', 'w') as f2:
    data = f1.read()
    match = re.search(r'my.*Alex', data, re.DOTALL)
    if match:
        f2.write(match.group())

rawDescription: Grep a range of words from a text file python


code:
import subprocess
import shlex
import time
PIPE = subprocess.PIPE

proc = subprocess.Popen(shlex.split('ls -lR /'), stdout=PIPE)
time.sleep(1)
print(proc.poll())
# None

proc.terminate()
time.sleep(1)
print(proc.poll())
# -15

description: Multiprocessing.Process subprocess.Popen completed


code: translation = ndb.Key('Question', '1', 'Translation', 'es').get()

rawDescription: What would be the appropiate design for storing content in multiple languages in Google App Engine?


code:
from itertools import groupby

def reduced(it):
    for value, group in groupby(it):
        yield next(group)
        for i in group:
            yield i
            break

rawDescription: pythonic way of removing similar items from list

description: Pythonic way of removing similar items from list


code:
a, b = map(int, s.split('x'))
res = a * b

rawDescription: Resolve variables from a string

description: Resolve variables from a string


code:
def replace_in_file(filename, oldtext, newtext):
    with open(filename, 'r') as file, open(filename + ".temp", 'w') as temp:
        lines = file.read()
        new_lines = lines.replace(oldtext, newtext)
        temp.write(new_lines)

rawDescription: How should I replace parts from a text file through Python?


rawDescription: Access a specific sizer from wxFormBuilder in Python


code: max((int(num), i) for i, num in enumerate(the_list[2::3]))

rawDescription: Find Largest Number From Selected List Elements In Python


code:
import collections
A, B, C, D, E = 'ABCDE'
lst = [A, B, C, D, A, A, A, B, E, C, C, E, D, A, B]
collections.Counter(lst).most_common()

rawDescription: Python: fast way to create a list of reps


code:
# << Setup >>
driver.get(url("/PointsBlocking/"))
assertExpectedConditionTrue(driver, "By.XPATH", "//td")

if not driver.find_element_by_id("BlockedOnlyCheckbox").is_selected():
    assertExpectedConditionTrue(driver, "By.ID", "BlockedOnlyCheckbox")
    driver.find_element_by_id("BlockedOnlyCheckbox").click()
    assertCheckBoxEnabled(driver, "BlockedOnlyCheckbox")

waitForNonStaleElement(driver, "By.XPATH", "//td")

try:
    assertExpectedConditionTrue(driver, "By.XPATH", "//td", "No data available in table", 1)
except (TimeoutException):
    while True:
        try:
            assertExpectedConditionFalse(driver, "By.XPATH", "//td", "No data available in table", 1)
        except (TimeoutException):
            break

        assertExpectedConditionTrue(driver, "By.XPATH", "//td")
        pointName = waitForNonStaleElementText(driver, "By.XPATH", "//td")

        try:
            assertExpectedConditionTrue(driver, "By.XPATH", "//tbody/tr[1]/td[5]/div/button[@class='btn active btn-success btn-small point-button']", None, 1)
        except NoSuchElementException:
            assertExpectedConditionTrue(driver, "By.XPATH", "//tbody/tr[1]/td[5]/div/button[@class='btn btn-small point-button']")
            waitForNonStaleElementClick(driver, "By.XPATH", "//tbody/tr[1]/td[5]/div/button[@class='btn btn-small point-button']")

        tmp = waitForNonStaleElementText(driver, "By.XPATH", "//td")

        if pointName == tmp:
            assertExpectedConditionTrue(driver, "By.XPATH", "//tbody/tr[1]/td[6]/div/button[@class='btn btn-small point-button']")
            waitForNonStaleElementClick(driver, "By.XPATH", "//tbody/tr[1]/td[6]/div/button[@class='btn btn-small point-button']")
            waitForNonStaleElementClick(driver, "By.XPATH", "//td")

rawDescription: StaleElementReferenceException occurs when clicking on the buttons of a changed table (Python > Selenium Webdriver)


code:
"""Retrieve the certificate from the server at the specified address,
   and return it as a PEM-encoded string.
   If 'ca_certs' is specified, validate the server cert against it.
   If 'ssl_version' is specified, use it in the connection attempt."""

rawDescription: Disable SSL certificate validation in Python


code: import xxx as yyy

rawDescription: How to import multiple files with same name in python

description: Import multiple files with same name in python


code:
tempDF
tempDF['date'] = tempDF['date'].apply(lambda x:x.replace(hour=12,minute=0))
tempDF

rawDescription: Changing time components of pandas datetime64 column


code: auth_parse.parse_args("John Smith")

rawDescription: How to use argparse during runtime to conditionally get further input?

description: Use argparse during runtime to conditionally get further input


code:
def cleanUpWords(string):
    only_alpha = ''.join(c for c in string if c.isalpha() or c == ' ')
    single_spaces = ' '.join(only_alpha.split())
    return single_spaces

rawDescription: Trying to use output of one function to influence the next function to count words in text file


code:
class TextField(pygame.sprite.Sprite):
    # [... define init here ...]
    def update(self, key):
        if key=="return":
            return self.value

# [... create txt, etc ...]
a = txt.update("return")

rawDescription: Changing a variable inside a class

description: Changing a variable inside a class


code:
class States(object):
    def __init__(self):
         self.started = False
         self.loading = False
         self.active = False
         self.ended = False

rawDescription: python define a state object

description: Python define a state object


rawDescription: python dictionary values sorting

description: Python dictionary values sorting


code:
import os.path
PROJECT_ROOT=os.path.abspath(os.path.dirname(__file__))
PROTECTED_MEDIA_ROOT=os.path.join(PROJECT_ROOT, 'protected_uploads')

rawDescription: protecting user uploaded files django

description: Protecting user uploaded files django


code:
class Dialog_02(QtGui.QMainWindow):
    def __init__(self, parent):
        super(Dialog_02, self).__init__(parent)
        # ensure this window gets garbage-collected when closed
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
    ...

    def closeAndReturn(self):
        self.close()
        self.parent().show()

class Dialog_01(QtGui.QMainWindow):
    ...

    def callAnotherQMainWindow(self):
        self.hide()
        self.dialog_02 = Dialog_02(self)
        self.dialog_02.show()

rawDescription: PyQt: How to hide QMainWindow

description: PyQt: How to hide QMainWindow


rawDescription: Having trouble with the same origin policy


code:
class AmazonDataType(dict):
    """
    Base for all Amazon datatypes.
    """

    def __init__(self, *args, **kwargs):
        self._prefix = kwargs.pop('prefix', self.__class__.__name__)

        super(AmazonDataType, self).__init__(*args, **kwargs)

    def __getattr__(self, key):
        return self.__getitem__(key)

    def __setattr__(self, key, value):
        return self.__setitem__(key, value)

    def dict(self):
        result = {}

        for key, value in self.items():
            if key.startswith('_'):
                continue

            key = self.fields.get(key, key)

            if isinstance(value, AmazonDataType):
                for skey, svalue in value.dict().items():
                    result['%s.%s' % (self._prefix, skey)] = svalue
            else:
                result['%s.%s' % (self._prefix, key)] = value

        return result

rawDescription: Most efficient way to add prefix to Python dictionary keys


rawDescription: Is there a function to transpose matrices (lists of lists) in python? if rows not equal column


code: foundQTreeWidgetItem  = self.findItemWidget(findQWidget) # Don't part argument currentQTreeWidgetItem use in recursive loop

rawDescription: How to get QTreeWidgetItem if its ItemWidget is known

description: Get QTreeWidgetItem if its ItemWidget is known


code: pd.merge(df1.reset_index(), df2.reset_index(), on=['a','b'], suffixes=['_1','_2'])

rawDescription: Index of matching rows in Pandas DataFrame [Python]


code:
def my_method():
    print(method.__name__) # this will always print `foo`
    result = method()

rawDescription: Bind method to object runtime late binding


code:
bs = b'\x81' # one byte string, whose value is 129 (0x81)
arr = BitArray(bs)
mask = BitArray('0b01111111')
byte = (arr[0:8] & mask).int
print(byte, repr("{:07b}".format(byte)))

rawDescription: Ascii string of bytes packed into bitmap/bitstring back to string?


code:
variable = {
    'hosts': 1,
    'version': 2,
    'licenses': {
        'john': 2,
        'mike': 1,
    }
}

rawDescription: Python: Retrieve result from inner dictionary


rawDescription: Django urlresolvers reverse for dynamically generated ids


code:
for line in iter(output.stdout.readline, ''):
    print(line)

rawDescription: How to print the output of shell instantly by python script

description: Print the output of shell instantly by python script


code: ID | name | votes | percentage

rawDescription: how can i display data in Tkinter treeview fetched from Mysql table using python

description: Display data in Tkinter treeview fetched from Mysql table using python


code:
import bisect
import re

def lettergrade(score, breakpoints = [40, 50, 60, 80], grades = 'EDCBA'):
    """
    >=80 -> A
    >=60 -> B
    >=50 -> C
    >=40 -> D
    else -> E
    """
    i = bisect.bisect(breakpoints, score)
    return grades[i]

grade = input("Entrez votre note : ")
a, b = map(int, re.split(r'sur|/', grade))
print(lettergrade(100.0*a/b))

rawDescription: Getting integers out of Python list

description: Getting integers out of Python list


code: _, b_rows = numpy.where(a_rownames == b_rownames[:, numpy.newaxis])

rawDescription: Manipulation with arrays in numpy

description: Manipulation with arrays in numpy


code:
sum = 0
for x in L:
    sum += x

rawDescription: Python programming functional vs. imperative code


code:
yToFind = 140
yreduced = np.array(y) - yToFind
freduced = interpolate.UnivariateSpline(x, yreduced, s=0)
freduced.roots()

rawDescription: Interpolation in SciPy: Finding X that produces Y


code:
import numpy as np

np.array([a,b])[:,None] - np.array([c,d,e])[None,:]

rawDescription: Perform cross-difference in numpy

description: Perform cross-difference in numpy


rawDescription: creating one string from two in python

description: Creating one string from two in python


code:
import re
re.findall(r'\b[A-Z]{2,}\b', var)

rawDescription: Looking for a good way to split a string on all-capital words


code: Xout_2d, Yout_2d = numpy.meshgrid(Xout,Yout)

rawDescription: How to plot contours from multidimensional data in MatPlotLib (NumPy)?

description: Plot contours from multidimensional data in MatPlotLib (NumPy)


code:
user_says.set(input_get + "\n\n")
ia_says.set(ia_answers)

rawDescription: Discussion with tkinter

description: Discussion with tkinter


code:
def borderCheck(values):
    #check if the footprint center is on a nonzero value
    if values[13] != 0:
        #replace border voxels with the mean of nonzero neighbours
        if 0 in values:
            return np.sum(values)/np.count_nonzero(values)
        else:
            return values[13]
    else:
        return 0

result = ndimage.generic_filter(B, borderCheck, footprint=np.ones((3, 3, 3)))

print(np.allclose(B_new, result))
# True

rawDescription: border/edge operations on numpy arrays

description: Border/edge operations on numpy arrays


code:
dataToRead = struct.unpack("H", socket.read(2))[0]
data = socket.read(dataToRead)

rawDescription: How to use Python and Google's Protocol Buffers to deserialize data sent over TCP

description: Use Python and Google's Protocol Buffers to deserialize data sent over TCP


code:
Phrase = input('Type message to encrypt: ')
shiftValue = int(input('Enter shift value: '))

# encoding to cypher, in single line
stringCoded = ''.join(chr(ord(c)+shiftValue) if c.isalpha() else c for c in Phrase)

print(stringCoded)

rawDescription: Selecting specific int values from list and changing them


code:
class AddressBook(object):

    ...

    def add_contact(self, contact=None):
        if contact is None:
            contact = Contact.from_input()
        self.contacts.append(contact)

rawDescription: Python - When to create a Class and when to create a Function


code: Record.objects.filter( Q(parameter__icontains="wd2") | ~Q(parameter__icontains="wd") )

rawDescription: Django queries: how to make contains OR not_contains queries


code:
u = User.objects.filter(userjob__job__name='a').filter(userjob__job__name='c')
jobs = u.userjob_set.all()

rawDescription: Django search multiple filters

description: Django search multiple filters


code:
from django.test import TestCase
from django.conf import settings
from django.utils.importlib import import_module

class SessionTestCase(TestCase):
    def setUp(self):
        # http://code.djangoproject.com/ticket/10899
        settings.SESSION_ENGINE = 'django.contrib.sessions.backends.file'
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore()
        store.save()
        self.session = store
        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key

rawDescription: How do I modify the session in the Django test framework

description: Modify the session in the Django test framework


code: results = MyModel.all(keys_only=True).filter('foo =', 'bar').fetch(20)

rawDescription: The App Engine datastore can either return entire entities or only entity keys from a query?


code:
from glob import glob

randomdir = random.choice(glob("*/"))

rawDescription: How to execute bash from within a python file?

description: Execute bash from within a python file


code:
from django.forms import modelformset_factory

OtherFormSet = modelformset_factory(Other)

# Creating an empty formset
formset = OtherFormSet()

# Creating a formset from a queryset
formset = OtherFormSet(queryset=Other.objects.filter(something='foobar'))

# Validating and saving
formset = OtherFormSet(request.POST)
if formset.is_valid():
    formset.save()

rawDescription: django form twice on same template

description: Django form twice on same template


code: p = subprocess.Popen('ps ax | grep bash | wc -l', stdout=subprocess.PIPE, shell=True)

rawDescription: How can I combine three subprocess.popen into one line?

description: Combine three subprocess.popen into one line


code:
import collections
result = collections.defaultdict(list)
i = ((1,'MCA', 'Science'),(2,'physic', 'Science'),(3,'chemsitry', 'Science'),(4,'punjabi', 'arts'),(5,'hindi', 'arts'))
for id,name,subject in i:
    result[subject].append({'id':str(id), 'name':name})

rawDescription: python group by data based on one field of list

description: Python group by data based on one field of list


code:
current = Configuration.query().get() or Configuration()
current.displayName = self.request.get('newDisplayName')
current.starting = self.request.get('newStartingDate')
current.put()

rawDescription: How to store and update a configuration in Google App Engine (Python)

description: Store and update a configuration in Google App Engine (Python)


code:
def user_input(self, row, column):
    print("row: %s column: %s" % (row, column))

rawDescription: How to determine which button is pressed on a single tkinter object?

description: Determine which button is pressed on a single tkinter object


code:
query = """INSERT INTO `data` (frame, sensor_row, sensor_col, value) VALUES (%s, %s, %s, %s ) """
values = []
rows, cols, frames = numpy.nonzero(data)
for row, col, frame in zip(rows, cols, frames):
    values.append((frame, row, col, data[row,col,frame]))

cur.executemany(query, values)

rawDescription: How can I improve my INSERT statement performance?

description: Improve my INSERT statement performance


code: infileData = list(map(int, infile.read().strip().split()))

rawDescription: python using data from a list, where by you call the data from its index number

description: Python using data from a list, where by you call the data from its index number


code:
connection = {}
with open("test.txt") as f:
    for line in f:
        a,b,c = map(int, line.split())
        connection[(a,b)] = c

rawDescription: Reading multiple lines in a file, and separating their values at the same time, to store it in dictionary


code:
# import the UpdateOne bulk helper
from pymongo import UpdateOne

# Outside loop of writing sourcing data
operations = []

# Inside loop of sourcing data, add to the queue

operations.append(
    UpdateOne(
        { "_id": puz_dict["_id"] },
        {
            "$setOnInsert": { "username": puz_dict["username"] },
            "$push": { "puzzles": puz_dict["puzzles"] },
            "$inc": { "attempts": puz_dict["attempts"] }
        },
        upsert = True
    )
)

# Only write to server 1 in 1000 and clear the queue
if ( len(operations) % 1000 == 0 ):
    coll.bulk_write(operations)
    operations = []

# Finish the loop

# Then only write again if there will still queued operations
# remaining on loop  completion

if ( len(operations) > 0 ):
    coll.bulk_write(operations)

rawDescription: Checking for existence of _id using and updating subdocument Pymongo


code:
class Foo(object):
    def bar(self):
        return 'Method bound to {!r}, from class Foo'.format(self)
    def __repr__(self):
        return '<Instance of type {!r}>'.format(type(self))
Foo.bar

rawDescription: Not sure what the Python documentation says about user-defined method objects here


code:
a = Info( type='AAA',    value=80000,   x=16.4,   y=164.2 )
b = Info( type='A',      value=78,      x=1.5,    y=11.3  )
c = Info( type='ABBCD',  value=554,     x=11.7,   y=10.1  )
d = Info( type='AFFG',   value=1263,    x=121.3,  y=12.8  )

tups = [a,b,c,d]

for t in tups:
    print(prettyprint_namedtuple(t,(10, 9, 8, 6)))

rawDescription: Namedtuple formatted/pretty print in Python


code: abbrevDict = dict(map(reversed, firstArray))

rawDescription: Comparing Two Arrays resulting into Third Array


code:
['<Eckhard_Christian>', '<hasGender>', '<male>', '<id_1d3s2ia_p3m_zkjp59>']
['<Peter_Pinne>', '<created>', '<In_Your_Arms_(Love_song_from_"Neighbours")>', '<id_1jmz109_1gi_t71dyx>']
['<Blanchester_Ohio>', '<hasWebsite>', '<http://www.blanchester.com/>', '<id_v9bcjt_ice_fraki6>']
['<Hub_(bassist)>', '<hasGender>', '<male>', '<id_10tunwc_p3m_zkjp59>']

rawDescription: Splitting strings in python in user defined manner


rawDescription: Random sampling one element without making it a list in Python


code:
for a, b in combinations(nums, r=2):
    pass

rawDescription: Combinations in of nested lists in python based on a one key attribute


code:
class Foo(object):
    pass

Foo.__class__.__bases__

rawDescription: unittesting: patching an objects __base__

description: Unittesting: patching an objects __base__


code:
class memoized(object):
    """Decorator function that adds the memoization"""

    def __init__(self, func):
        self.func = func
        self.memo = {}

    def __call__(self, current, target, count):
        key = (current, target, count)
        if key not in self.memo:
            self.memo[key] = self.func(current, target, count)
        return self.memo[key]

rawDescription: Permutation of phone numbers starting at button x, ending at button y, and z numbers long


code:
from array import *

# Set up Array
firstArray = array('i', [0,0,0,0,0,0])
secondArray = array("i",[0,0,0,0,0,0])

# Program Greeting
print("This program prompts the client for 6 numbers.")
print("If a number is over 100, move it to a second array.")
print()

# Load numbers from client
for i in range(0,5,1):
    number = int(input("Enter a number: "))
    firstArray[i] = number

# Move numbers over 100 to 2nd array
print("Searching through the array and moving numbers.")
secArrayCntr = 1
for i in range(0,5,1):
    if firstArray[i] > 100: # If it's over 100 than it can't be <1
        secondArray[secArrayCntr] = firstArray[i]
        secArrayCntr = secArrayCntr + 1

# Print First Array
print("Displaying the first array.")
for i in range(0,5,1):
    print(firstArray[i])

# Print Second Array
print("Displaying ", secArrayCntr, " numbers over 100.")
for i in range(1, secArrayCntr, 1):
    print(secondArray[i])

rawDescription: Trying to call range in Array (Lists) in Python 3


code:
components = list(nx.connected_components(G)) # list because it returns a generator
components.sort(key=len, reverse=True)

rawDescription: Find and count the number of isolated and semi-isolated nodes in a network


code:
from math import pow
map(pow, [2,3,4], [2,3,4])

rawDescription: How do you subtract list a from list b in Python?

description: Subtract list a from list b in Python


rawDescription: Subtracting depending on an if function in python


code:
from pyparsing import *

test = """\
#
here
are
some
strings
#
and
some
others
 #
 with
 different
 levels
 #
 of
  #
  indentation
  #
 #
#"""

# newlines are significant for line separators, so redefine
# the default whitespace characters for whitespace skipping
ParserElement.setDefaultWhitespaceChars(' ')

NL = LineEnd().suppress()
HASH = '#'
HASH_SEP = Suppress(HASH + Optional(NL))

# a normal line contains a single word
word_line = Word(alphas) + NL

indent_stack = [1]

# word_block is recursive, since word_blocks can contain word_blocks
word_block = Forward()
word_group = Group(OneOrMore(word_line | ungroup(indentedBlock(word_block, indent_stack))) )

# now define a word_block, as a '#'-delimited list of word_groups, with
# leading and trailing '#' characters
word_block <<= (HASH_SEP +
                 delimitedList(word_group, delim=HASH_SEP) +
                 HASH_SEP)

# the overall expression is one large word_block
parser = word_block

# parse the test string
parser.parseString(test).pprint()

rawDescription: pyparsing with starting and ending string being the same

description: Pyparsing with starting and ending string being the same


code:
style = selection.attrib['style']
properties = dict([item.split(":") for item in style.split("; ")])

del properties['border-bottom']

selection.attrib['style'] = "; ".join([key + ":" + value for key, value in properties.items()])

print(lxml.html.tostring(selection))

rawDescription: python lxml: syntax for selectively deleting inline style attributes?

description: Python lxml: syntax for selectively deleting inline style attributes


code:
return find_path(dct, next_, depth)
# ^^^^
# Return

rawDescription: Mutable Default Argument Returns None

description: Mutable Default Argument Returns None


code:
lst = ['this is a sentence', 'this is one more sentence']
[i.count(' ') for i in lst]

rawDescription: Finding how many of a certain character in each element in a list


code:
#start processing the items
result_infos = [run_item(proc, item) for item in items]
#gather the results (blocking)
results = gather_results(result_infos)

rawDescription: Threading in Python for each item in list


rawDescription: will the memory overflow if python processing too many bigtext

description: Will the memory overflow if python processing too many bigtext


code:
import matplotlib.pyplot as plt

cols = ['Column {}'.format(col) for col in range(1, 4)]
rows = ['Row {}'.format(row) for row in ['A', 'B', 'C', 'D']]

fig, axes = plt.subplots(nrows=4, ncols=3, figsize=(12, 8))

for ax, col in zip(axes[0], cols):
    ax.set_title(col)

for ax, row in zip(axes[:,0], rows):
    ax.set_ylabel(row, rotation=0, size='large')

fig.tight_layout()
plt.show()

rawDescription: Row and column headers in matplotlib's subplots


code:
def search(myBigFancyX, myBigFancyList):

    counter = 0
    for number in myBigFancyList:
        if number == myBigFancyX:
            counter += 1
    return counter

if __name__ == "__main__":

    l = [4, 10, 4, 2, 9, 5, 4 ]
    x = int(input("Enter an element to search for in the list: "))

    occurances = search(x, l)
    if occurances == 0:
        print("element does not occur in the list")
    else:
        print("the number of occurrences in L: ", occurances)

rawDescription: how do I get a function to take two arguments?

description: Get a function to take two arguments


code:
def solve_host():
    global items
    global constraints
    p = KSP('weight', list(items), constraints = constraints)
    result = p.solve('glpk', iprint = -1)

rawDescription: How to solve 3D multi bin-packing with OpenOpt

description: Solve 3D multi bin-packing with OpenOpt


code:
def convert(types, values):
    return [t(v) for t, v in zip(types, values)]

rawDescription: Sorting CSV in Python

description: Sorting CSV in Python


code:
...
next_response = session.get('https://domain.com/someOtherPage')

rawDescription: Python httplib2: HTTPS login fails

description: Python httplib2: HTTPS login fails


code:
df2 = pd.DataFrame(df.firms.str.split(',').tolist())
firms = df2.stack().unique().tolist()

rawDescription: replacing quotes inside a pandas df to count unique terms

description: Replacing quotes inside a pandas df to count unique terms


code:
import dis
dis.dis(lambda: str(100000))
dis.dis(lambda: '%s' % 100000)

rawDescription: str performance in python

description: Str performance in python


code: print(word_len_dict("The dogs run quickly forward to the park"))

rawDescription: Adding more than one value to dictionary when looping through string


code:
data = {"media": [{"type":"flash", "swfsrc":"http://shopperspoll.webfactional.com/media/flashFile.swf", "height": '100', "width": '100', "expanded_width":"160", "expanded_height":"120", "imgsrc":"http://shopperspoll.webfactional.com/media/laptop1.jpg"}]}

import json
json_encoded = json.dumps(data)

rawDescription: urllib's urlencode returning weird encoded results

description: Urllib's urlencode returning weird encoded results


code:
def student_data(name, age, student_number, enrolled):
   my_str=str(name)+','+str(age)+','+str(student_number)+','+str(enrolled)
   return my_str

rawDescription: Concatenating objects of different types into a string (Python)


code:
head = soup.find('head')
head.insert(1, meta)

rawDescription: Inserting into a html file using python

description: Inserting into a html file using python


code: ['MINUSERPIXELVALUE = 1','MAXUSERPIXELVALUE= 4']

rawDescription: creating elevation/height field gdal numpy python

description: Creating elevation/height field gdal numpy python


code: vi .bash_profile

rawDescription: How to set up Python and Homebrew?

description: Set up Python and Homebrew


code:
kwargs = {}
kwargs['years'] = 10
some_date = today + relativedelta(**kwargs)

rawDescription: Python - convert string to argument (or dynamically choose increment duration type for date)?


code:
from collections import defaultdict

v = defaultdict(list)

for key, value in sorted(d.iteritems()):
    v[value].append(key)

rawDescription: Grouping Python dictionary keys as a list and create a new dictionary with this list as a value


code: bananas = [fruit for fruit in fruits if fruit.name=='banana']

rawDescription: Python: Tuples/dictionaries as keys, select, sort


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


rawDescription: Convert .CSV files to .DTA files in Python


code: f = [ctypes.c_int32() for i in range(10)]

rawDescription: Creating a list of ctypes

description: Creating a list of ctypes


code:
fn_groups = groupby(
                filter(
                    starts_with_date,
                    filenames),
                get_name_root
            )

rawDescription: python deleting older files that match an unknown pattern (tricky)

description: Python deleting older files that match an unknown pattern (tricky)


code: charactersBySpeed = sorted (characters, key = -character.speed)

rawDescription: Python - Compare two lists and find matching values and their positions in the list


code: sorted(a)

rawDescription: Python - order list of lists by multiple column indexes


code:
from collections import Counter
basket1 = {"ham":2,"eggs":3}
basket2 = {"eggs":4,"spam":1}
basket_sum = Counter(basket1) + Counter(basket2)
basket_sum

rawDescription: Python Joining two dictionnary with similar content


rawDescription: Sorting panda DataFrames based on criteria


rawDescription: Counting how many times a number appears in a file


code:
import dexml
from dexml import fields

# Participant Class
class Participant(dexml.Model):
    class meta:
        tagname = "ParticipantDetailExt"

    participantId = fields.Integer(tagname='participantId')

# Ticket Class
class Ticket(dexml.Model):
    class meta:
        #namespace = "Namespace Here"
        tagname = "ticketDetail"

    ticketId = fields.String(tagname='ticketId')
    participants = fields.List(Participant, tagname="participants")

t = Ticket.parse('''
<ticketDetail>
        <ticketId>int</ticketId>
      <participants>
        <ParticipantDetailExt>
          <participantId>42</participantId>
        </ParticipantDetailExt>
        <ParticipantDetailExt>
          <participantId>74</participantId>
        </ParticipantDetailExt>
      </participants>
      </ticketDetail>
''')

assert len(t.participants) == 2

rawDescription: How to parse Nested Elements in Python using dexml

description: Parse Nested Elements in Python using dexml


code:
timeit.timeit('match("0-0016ub5j2oi06u30tj30g6790v3nug[hoyj39867i6gy9thvb05y4b896y3n098vty98thn98qg5y4n8ygnqp", "0-0016ub5j2oi06u30tj30g6790v3gug[hoyj39867i6gy9thvb05y4b896y3n098vty98thn98qg5y4n8ygnqp")', setup="""
def match(s1, s2):
    ok = False

    for c1, c2 in zip(s1, s2):
        if c1 != c2:
            if ok:
                return False
            else:
                ok = True

    return ok
""")

rawDescription: Compare strings, allowing one character difference


rawDescription: Converting a string into a list in Python


code:
(r'^article/new/$', views.edit, {}, 'article_new'),
(r'^article/edit/(?P<id>\d+)/$', views.edit, {}, 'article_edit'),

rawDescription: Django edit form based on add form?

description: Django edit form based on add form


code:
lc=[[sparse.coo_matrix(l)] for l in ll]
lc

rawDescription: Read a dense matrix from a file directly into a sparse numpy array?


code:
if original_character.isupper():  # Determine whether it is upper/lower case
    base_a = 'A'                  # use 'A' as a base for uppercase
else:                             #
    base_a = 'a'                  # use 'a' as a base for lowercase

orig_char_ascii = ord(original_character)  # Get the original ascii value

orig_char_alpha_index = orig_char_ascii - ord(base_a) # Get the `0-25` alphabetic
                                                      # index of the character

shift_number = 3  # Set the amount to shift by

new_char_alpha_index = orig_char_alpha_index + shift_number # Add the shift value

new_char_alpha_index = new_char_alpha_index % 26  # Take the modulus to impose
                                                  # periodic boundary conditions
                                                  # i.e. if you had 'z' + 3
                                                  #      'z' + 3 -> 25 + 3 -> 28
                                                  #      28 % 26 = 2,  2 -> 'c'

new_char_ascii_index = ord(base_a) + new_char_alpha_index  # scale back to the ascii
                                                           # value

new_char = chr(new_char_ascii_index)

rawDescription: How to change random letter using number in Python

description: Change random letter using number in Python


code:
def shortStringsByWordLengths(sentences):
    return [' '.join(sorted(sentence.split(), key=len, reverse=True)) for sentence in sentences]

rawDescription: sorting a list of strings by their length not working

description: Sorting a list of strings by their length not working


code: exact_assets_ids = [item.id for item in exact_assets]

rawDescription: Iterate through two lists simultaneously and remove from one if exists in the other


code:
from bs4 import BeautifulSoup
from pprint import pprint

soup = BeautifulSoup(html)
h2s = soup.select("h2") #get all h2 elements
tables = soup.select("table") #get all tables

first = True
title =""
players = []
for i,table in enumerate(tables):
    if first:
         #every h2 element has 2 tables. table size = 8, h2 size = 4
         #so for every 2 tables 1 h2
         title =  h2s[int(i/2)].text
    for tr in table.select("tr"):
        player = (title,) #create a player
        for td in tr.select("td"):
            player = player + (td.text,) #add td info in the player
        if len(player) > 1:
            #If the tr contains a player and its not only ("Goalkeaper") add it
            players.append(player)
    first = not first
pprint(players)

rawDescription: HTML file parsing in Python

description: HTML file parsing in Python


rawDescription: string split() in python 2.6

description: String split() in python 2.6


code:
from multiprocessing import Pool, Lock
from time import sleep

def do_job(i):
    "The greater i is, the shorter the function waits before returning."
    with lock:
        sleep(1-(i/10.))
        return i

def init_child(lock_):
    global lock
    lock = lock_

def main():
    lock = Lock()
    poolsize = 4
    with Pool(poolsize, initializer=init_child, initargs=(lock,)) as pool:
        results = pool.imap_unordered(do_job, range(poolsize))
        print(list(results))

if __name__ == "__main__":
    main()

rawDescription: How to create global lock/semaphore with multiprocessing.pool in Python?

description: Create global lock/semaphore with multiprocessing.pool in Python


rawDescription: Python: "Try" inside shortened for...loop


code:
timeit.timeit('L.sort()', 'import random;L = [(random.randint(0, 100), i) for i in range(3000)]', number=10000)
timeit.timeit('L.sort(key=operator.itemgetter(0))', 'import random;import operator;L = [(random.randint(0, 100), i) for i in range(3000)]', number=10000)

rawDescription: optimizing python code for performance

description: Optimizing python code for performance


code: Counter([(k,len(v)) for k, v in myDict.iteritems()])

rawDescription: Dictionary that counts occurrences of its items


code:
data = {'a': 4, 'b': 1, 'e': 1}
result = [{'name':key, 'value':value} for key,value in data.items()]
result

rawDescription: python: Convert a Counter object to a json object with added key names

description: Python: Convert a Counter object to a json object with added key names


rawDescription: Get list of column names for columns that contain negative values


code:
max_value, max_index = max((x, (i, j))
                           for i, row in enumerate(li)
                           for j, x in enumerate(row))

rawDescription: Maximum value from a list of lists and its index


rawDescription: Python - Create an array from columns in file


code:
import numpy as np
from sortedcontainers import SortedList

def nearest_hi_value(my_vals):
    index = np.argsort(my_vals)
    sl = SortedList(range(len(index)), load=100)
    res = []
    for idx in index.tolist():
        sl.remove(idx)
        idx2 = sl.bisect_left(idx)
        if idx2 > 0:
            res.append(idx - sl[idx2-1])
        else:
            res.append(0)
    result = np.zeros_like(index)
    result[index] = res
    return result

rawDescription: Pandas Series : faster way of computing periods back to preceding high


code:
import pandas as pd
from IPython.display import display
data = pd.read_csv('yourdata.txt')

rawDescription: ipython notebook pandas max allowable columns

description: Ipython notebook pandas max allowable columns


code:
class memoize(object):
    past=[]

    def __init__(self, f):
        past = []
        self.__wrapped__ = self.__f = f

rawDescription: python decorators stacking

description: Python decorators stacking


rawDescription: Python 3 String Method?

description: Python 3 String Method


code:
class Device(object):

    def __init__(self, battery, charger, some_field):
        self.battery = battery
        self.charger = charger
        self.some_field  = some_field

class DeviceView(APIView):
    # then in the DeviceView you could create an instance and pass to the serializer
    def get(self, request, format=None):
        battery = Battery.objects.get(id=1)
        charger = Charger.objects.get(id=1)
        device = Device(battery=battery, charger=charger, some_field='some_text')
        serializer = DeviceSerializer(instance=device)
        return Response(serializer.data)

rawDescription: Django Rest Framework doesn't serialize SerializerMethodField


code:
from flask import Flask, render_template_string
from flask_wtf import Form
from wtforms import StringField
from wtforms.validators import DataRequired
import wikipedia

app = Flask(__name__)
app.secret_key = 'secret'

class WikiForm(Form):
    key = StringField('Search Term', validators=[DataRequired()])

index_html='''

<form method="POST">
    {{ form.csrf_token }}
    {{ form.key.label }}: {{ form.key() }}
    <input type="submit" value="Go"/>
</form>

{% if topics %}

    {% for topic in topics %}
{{ topic }}
{% endfor %}

{% endif %}

'''

@app.route('/', methods=('GET', 'POST'))
def index():
    form = WikiForm()
    if form.validate_on_submit():
        topics = wikipedia.search(form.key.data) or ['No topic found']
        return render_template_string(index_html, topics=topics, form=form)
    return render_template_string(index_html, topics=None, form=form)

app.run(debug=True)

rawDescription: Using Flask, Jinja2, HTML to update page on buttonpress


code:
result = [sublist for sublist in
        (lst[x:x+size] for x in range(len(lst) - size + 1))
        if item not in sublist
    ]

rawDescription: Find all possible sublists of a list

description: Find all possible sublists of a list


code:
urls = (
  '/', 'index',
  '/foo', 'foo'
)

# ...

class foo:
    def GET(self):
        greeting = "Foo"
        return render.foo(greeting=greeting)

rawDescription: LearnPythonTheHardWay Exercise 50

description: LearnPythonTheHardWay Exercise 50


rawDescription: Converting 32-bit integer into array of four 8-bit integers in Python


code: foo(x, y)

rawDescription: Do you change variables AFTER you run a function in python?


code:
# foo.py
class Foo: pass

rawDescription: python modify __metaclass__ for whole program

description: Python modify __metaclass__ for whole program


code: import pickle

rawDescription: Writing and reading variables in a file in Python


code: print = print

rawDescription: Mocking print but allow using it in tests


rawDescription: python select the lowest alphanumeric value with a reference from multiple lists

description: Python select the lowest alphanumeric value with a reference from multiple lists


code:
# In the controller that handles topic messages
form = PostingForm()

# Either mark the field as optional
form.topic.validators.insert(0, Optional())

# or remove the validator entirely
form.topic.validators = []

rawDescription: What's the best practice in WTForms, using one form class or multiple ones?


code:
class Stage(models.Model):
    stage_number = models.CharField()
    stage_name = models.CharField()
    zones = models.ManyToManyField(Zone, through='ZoneStage')

    @property
    def value(self):
        return ZoneSubStage.objects.filter(substage__stage=self).aggregate(Sum('value')).get('value__sum', 0)

rawDescription: django models sum of classes fiels

description: Django models sum of classes fiels


code:
a_dict = {'a': 1, 'b': 2, 'c': 3}
b_dict = {value:key for key, value in a_dict.items()}
a_dict.items()
b_dict.items()
a_dict.keys()
b_dict.values()
a_dict.values()
b_dict.keys()
c_dict = {'a': 1, 'b': 2, 'c': 3, 'd':2}
d_dict = {value:key for key, value in c_dict.items()}
c_dict.items()
d_dict.items()

rawDescription: Where is this variable defined?

description: Where is this variable defined


code:
import re
pattern = re.compile(smallstr)
match = pattern.search(bigstr)
match.span()

rawDescription: Distance from str to the end (python)

description: Distance from str to the end (python)


code:
from lxml.etree import fromstring
tree = fromstring('''<section> Fubar, I'm so fubar, fubar and even more <fref bar="baz">fubare</fref>. And yet more fubar. </section>''')
elem = tree.xpath('/section/fref')[0]
elem.text
elem.tail
elem.getparent().text

rawDescription: Python/ElementTree: Parsing inline elements w/ respect to surrounding text?


code:
l = ["a", "b", "c", "d", "e"]
n=3
duplic = [ li  for li in l for i in range(n)]

rawDescription: How can I duplicate element of a list in python?

description: Duplicate element of a list in python


code:
scores
inner_scores

rawDescription: Recognition of elements in a list - machine learning


code:
for key, value in testcase_statistics_and_messages(ExampleTestCase).items():
    print(key, "==>", value)

rawDescription: Get the docstring of the test methods from a result of unit testing


rawDescription: Matplotlib wont join data points when the x axis isn't equally spaced


code:
factory_one = blank.copy()
day_0  = numpy.searchsorted(time, 0)
day_10 = numpy.searchsorted(time, 10)

rawDescription: How to set limits to specific components of an equation when plotting them?

description: Set limits to specific components of an equation when plotting them


code:
import unittest

class TestMyCode(unittest.TestCase):

    def test_code(self):
        self.assertTrue(True)

rawDescription: Invoking Test Methods with a Method for a unittest.TestCase Subclass Python


rawDescription: pandas groupby - return min() along with time where min() occurs

description: Pandas groupby - return min() along with time where min() occurs


code: rdd.flatMap(lambda kv: ((kv[0], v) for v in kv[1])).map(lambda kv: (kv[1], func(kv)))

rawDescription: Spark: how to generate several elements in map (python)?


code:
t = {"test":1, "asterisk":2}
test2(t)

rawDescription: Is there any benefits for using * or ** in python?


code:
class MyTableWidget(QtGui.QTableWidget):
    myCustomSignal=pyqtSignal()

    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Return or key == Qt.Key_Enter:
            print('clicked enter')
            self.myCustomSignal.emit()
        ...

rawDescription: How to link my QTableWidget subclass to my main program

description: Link my QTableWidget subclass to my main program