code:
import os, sys
print('\u3030')
old_stdout = sys.stdout
fd = os.dup(sys.stdout.fileno())
sys.stdout = open(fd, mode='w', errors='replace')
old_stdout.close()
print('\u3030')

rawDescription: How to print unsupported unicode characters on Windows cmd as e.g. "?" instead of raising exception?

description: Print unsupported unicode characters on Windows cmd as e.g. "?" instead of raising exception


code: dinner_entries = LotteryEntry.objects.filter(user=request.user).values_list('dinner__id', flat=True)

rawDescription: Check if object exists within QuerySet

description: Check if object exists within QuerySet


code:
# Create a new entry
new_entry = gdata.contacts.ContactEntry()
new_entry.title = atom.Title(text='Elizabeth Bennet')
new_entry.content = atom.Content(text='Test Notes')
new_entry.email.append(gdata.contacts.Email(
    rel='http://schemas.google.com/g/2005#work',
    primary='true',
    address='liz@gmail.com'))
new_entry.phone_number.append(gdata.contacts.PhoneNumber(
    rel='http://schemas.google.com/g/2005#work', text='(206)555-1212'))
new_entry.organization = gdata.contacts.Organization(
    org_name=gdata.contacts.OrgName(text='TestCo.'),
    rel='http://schemas.google.com/g/2005#work')

rawDescription: gdata.data.PhoneNumber: How do I get the type of Phone Number?

description: Gdata.data.PhoneNumber: How do I get the type of Phone Number


code:
import sys

def read_until_minus_one():
    buf = []
    seen_minus = False
    while True:
        char = sys.stdin.read(1)
        if not char: # EOF
            break
        if char == '1' and seen_minus:
            buf.pop() # chop the last minus
            break # seen -1
        else:
            seen_minus = (char == '-')
            buf.append(char)
    return ''.join(buf)

print(read_until_minus_one())

rawDescription: How to stop reading input from user after a certain char using raw_input() in Python?

description: Stop reading input from user after a certain char using raw_input() in Python


code: strs = "sample4:15"

rawDescription: Replace character in line inside a file

description: Replace character in line inside a file


code:
for num in numbers:
    print( x[int(num)] )

rawDescription: Caesar cypher in Python

description: Caesar cypher in Python


code:
name = 'input2'
value = root.find('.//vars/var[@name="{}"]'.format(name)).text

rawDescription: How to get the child of child using Python's ElementTree

description: Get the child of child using Python's ElementTree


code:
X,Y = ( np.zeros(1) for _ in range(2) )
X,Y,Z = ( np.zeros(1) for _ in range(3) )
W,X,Y,Z = ( np.zeros(1) for _ in range(4) )
...

rawDescription: numpy multiple ndarray creation at once

description: Numpy multiple ndarray creation at once


code: {s: v for (o, s), v in mydict.iteritems() if o is co1}

rawDescription: Compact Way To Shear Dictionary With Tuple For Key in Python


code:
[(3, 'I_AM_NOWHERE'), (1, 'I_AM_THERE'), (0, 'I_AM_HERE')]
['I_AM_HERE', 'I_AM_THERE', 'I_AM_NOWHERE']

rawDescription: How to find a substring using partial matching

description: Find a substring using partial matching


code:
dictionary = {
    "+": operator.iadd(answer, number),
    "-": operator.isub(answer, number),
    "*": operator.imul(answer, number),
    "/": operator.itruediv(answer, number),
    "^": operator.ipow(answer, number)
}

answer = dictionary[symbol]

rawDescription: How do I access a mathematical operation within a dictionary based on user input?

description: Access a mathematical operation within a dictionary based on user input


code:
a_guess = 1 / (np.pi * max(ydata))
x0_guess = sum(xdata * ydata) / sum(ydata)

rawDescription: Fit points to a Lorentzian curve and find center and half maximum bandwidth in Python


code:
ircsock.send(bytes('"NICK " + nick', 'UTF-8'))
ircsock.send(bytes('"USER " + nick + " " + nick + " " + nick + " :" + nick', 'UTF-8'))

rawDescription: Creating a simple IRC bot in python. Having trouble


code:
from pprint import pprint
from itertools import combinations

def solve(lst, m):

    col, n = {}, len(lst)
    for i, x in enumerate(lst):
        col[i] = [j for j, y in enumerate(x) if y]

    for s in xrange(n, m-1, -1):
        for c in combinations(xrange(n), s):
            values  = set(col[c[0]]).intersection(*(col[k] for k in c[1:]))
            if len(values) >= m:
                yield [lst[k] for k in c]

for x in solve(matrix, 2):
    pprint(x)

rawDescription: Python: How to find greater than N rows with non zero cells in greater than M common columns


code:
def is_hh_mm_time(time_string):
    try:
        time.strptime(time_string, '%H:%M')
    except ValueError:
        return False
    return len(time_string) == 5

rawDescription: How to decide if an string is in hh:mm format in python?

description: Decide if an string is in hh:mm format in python


code: [[x.strip(string.punctuation) for x in y] for y in punc]

rawDescription: Stripping punctuation from a list of lists of words


code:
data = generate_data(10, 10000)
bests1 = run_test(data, choose_best1)
bests2 = run_test(data, choose_best2)

rawDescription: Max value in Dictionary of List of Dictionaries in Python


code:
from functools import lru_cache, partial
import numpy as np

def lru_wrapper(array=None):
    @lru_cache(maxsize=None)
    def foo(key):
        return '%s:' % key, array
    return foo

arr = np.array([1, 2, 3])
func = lru_wrapper(array=arr)

for x in [0, 0, 1, 2, 2, 1, 2, 0]:
    print (func(x))

print (func.cache_info())

rawDescription: using functools.lru_cache on functions with constant but non-hashable objects

description: Using functools.lru_cache on functions with constant but non-hashable objects


code:
b=['m','NN']
dict={'b':['NN','m','big'], 'a':['NN', 'q']}
[k for k, v in dict.items() if all((x in v) for x in b)]

rawDescription: Matching lists when elements are not ordered


code:
import matplotlib as mpl
mpl.rcParams['font.family'] = 'Arial'

rawDescription: Unicode character render

description: Unicode character render


code:
p = argparse.ArgumentParser()
g = p.add_mutually_exclusive_group(required=True)
g.add_argument("-m", "--mac", dest="addresses")
g.add_argument("--nonmac", nargs="*", dest="addresses")
args = parser.parse_args()

rawDescription: N sys.argv[1:] args with optional args XOR 1 argparse arg, with 1 optional arg?


rawDescription: Regex Help, por favor

description: Regex Help, por favor


code:
from time import sleep
from datetime import datetime

start_time = datetime.now()
print('My Start Time', start_time)
sleep(5)

stop_time = datetime.now()
print('My Stop Time', stop_time)

elapsed_time = stop_time - start_time
print('My Elapsed Time', elapsed_time)

rawDescription: Measuring Elapsed time using Python 2.7 time module


code:
from django.db import models
from django.contrib.auth.models import User

class SecurityKey(models.Model):
    key = models.CharField(max_length=32, unique=True)
    user = models.OneToOneField(User)

rawDescription: Security issues with a middleware screener page


code:
df = pd.read_csv('rawdata.txt', converters={'voltage(V) ': binary, 'current(A)': binary})
df.columns = [v.strip() for v in df.columns]

rawDescription: I am trying to get binary data from text and converting to numpy arrays


code:
import random
import string
from Tkinter import *

root = Tk()

def addCheckBox():
    checkBoxName = "".join(random.choice(string.letters) for _ in range(10))
    c = Checkbutton(root, text=checkBoxName)
    c.pack()

b = Button(root, text="Add a checkbox", command=addCheckBox)
b.pack()

root.mainloop()

rawDescription: Dynamically add checkboxes with tkinter in python 2.7


code:
# whitelist
PermissionList.objects.filter(permission=True)
# blacklist
PermissionList.objects.filter(permission=False)

rawDescription: email whitelist/blacklist in python/django

description: Email whitelist/blacklist in python/django


code:
source, local = sources[1], {}
exec(source, func.__globals__, local)
local.popitem()[1]

rawDescription: Is it possible to access inner functions and classes via code objects?


code:
def main():
    dict_filename = 'dictionary.txt'
    print("part 4")
    part4(dict_filename)

def part1(dict_filename):
    vowels = 'aeiouy'
    vowelcount = 0
    dictionary = open(dict_filename,'r')
    for words in dictionary:
        words = words.lower()
        vowelcount = 0
        if len(words) == 8:
            if 's' not in words:
                for letters in words:
                    if letters in vowels:
                        vowelcount += 1
                if vowelcount == 1:
                    print(words)
    return words

def part4(dict_filename):
    dictionary = open(dict_filename,'r')
    naclcount = 0
    for words in dictionary:
        if 'nacl' in words:
            naclcount = naclcount + 1
    return naclcount

main()

rawDescription: This code isn't displaying the correct answer


code:
p=argparse.ArgumentParser()
p.add_argument('--cmd1', action='store_const', const=lambda:'cmd1', dest='cmd')
p.add_argument('--cmd2', action='store_const', const=lambda:'cmd2', dest='cmd')

args = p.parse_args(['--cmd1'])
# Out[21]: Namespace(cmd=<function <lambda> at 0x9abf994>)

p.parse_args(['--cmd2']).cmd()
# Out[19]: 'cmd2'
p.parse_args(['--cmd1']).cmd()
# Out[20]: 'cmd1'

rawDescription: Call function based on argparse

description: Call function based on argparse


code:
syn1 += alpha * l1.T.dot(l2_delta)
syn0 += alpha * l0.T.dot(l1_delta)

rawDescription: Neuro Network on MNIST--Result is not expected


code:
m = pd.melt(df, id_vars="event", var_name="Id", value_name="Name").dropna()
m

rawDescription: Convert a list of dictionaries with varying keys to a dataframe


code: msg = MIMEText('€10'.encode('utf-8'), _charset='utf-8')

rawDescription: Python 3 smtplib send with unicode characters


code:
#                 THIS IS A REALY long DEBUG Message that works and    [   DEBUG]
#                 wraps around great........
#    THIS IS A REALY long INFO Message that works and wraps around     [    INFO]
#    great........
# THIS IS A REALY long WARNING Message that works and wraps around     [ WARNING]
# great........
#         THIS IS A REALY long ERROR Message that works and wraps      [   ERROR]
#         around great........
# THIS IS A REALY long CRITICAL Message that works and wraps around    [CRITICAL]
# great........

rawDescription: Logging Formatting Right Justify Level Name


rawDescription: In place difference between elements of a Numpy array


code: {k: v for k1, k2, v, _ in data for k in (k1, k2)}

rawDescription: Python: dict comprehension with multiple key-value pairs in the same time


code:
def try_parse(string):
    string2 = ""
    for c in string:
        if not c.isdigit() and c != '.':
            break
        string2 += c
    return string2

rawDescription: saving the number into the variable in every run of cycle python

description: Saving the number into the variable in every run of cycle python


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

# Generate some data...
x, y = np.meshgrid(np.linspace(-2,2,200), np.linspace(-2,2,200))
x, y = x - x.mean(), y - y.mean()
z = x * np.exp(-x**2 - y**2)

# Plot the grid
plt.imshow(z)
plt.gray()
plt.show()

rawDescription: Display array as raster image in python

description: Display array as raster image in python


code:
def logsumexp_row_nonzeros(X):
    result = np.empty(X.shape[0])
    for i in range(X.shape[0]):
        result[i] = logsumexp(X.data[X.indptr[i]:X.indptr[i+1]])
    return result

rawDescription: Log-sum-exp trick on a sparse matrix in scipy


rawDescription: Removing a widget by invoking from a button which is set using QSplitter() in PyQt4


rawDescription: Most efficient Django query to return results spanning multiple tables


code:
def some_html():
    return render('my_template.tpl')

rawDescription: How to let js make a request from python and preserve the loaded site in place when answered by python

description: Let js make a request from python and preserve the loaded site in place when answered by python


code:
def long_substr(data):
    substr = ''
    if len(data) > 1 and len(data[0]) > 0:
        for i in range(len(data[0])):
            for j in range(len(data[0])-i+1):
                if j > len(substr) and all(data[0][i:i+j] in x for x in data):
                    substr = data[0][i:i+j]
    return substr

rawDescription: Longest common substring from more than two strings - Python


rawDescription: Unpacking arguments from argparse

description: Unpacking arguments from argparse


rawDescription: Remove or adapt border of frame of legend using matplotlib


code: somedict.get(key, default)

rawDescription: how to print user friendly poker hand in python?

description: Print user friendly poker hand in python


code: nbytes = sys.stdout.write("foo\n")

rawDescription: difference between sys.stdout.write and print when printing variables

description: Difference between sys.stdout.write and print when printing variables


code: H = nx.path_graph( len(idvalue) )

rawDescription: Labelling nodes in networkx

description: Labelling nodes in networkx


code:
N = [["D","C","A","B"],
     [2,3,4,5],
     [6,7,8,9]]

# Swap the last two columns

for item in N:
    item[2], item[3] = item[3], item[2]

# Or as a function

def swap_columns(your_list, pos1, pos2):
    for item in your_list:
        item[pos1], item[pos2] = item[pos2], item[pos1]

rawDescription: Swap columns in a nested list (Python 3)


code:
from bokeh.plotting import figure

def first_plot():

    p = figure(plot_width=400, plot_height=400, responsive = True)
    p.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="navy", alpha=0.5)
    return p

def second_plot():

    p2 = figure(plot_width=400, plot_height=400, responsive = True)
    p2.square([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="olive", alpha=0.5)
    return p2

rawDescription: Embedding multiple bokeh HTML plots into flask


code: pattern = re.compile(r'(?:review: )?(http://url.com/(\d+))\s?', re.IGNORECASE)

rawDescription: Python regex to match multiple times

description: Python regex to match multiple times


code:
# dict must be passed by reference to .format()
print("{foo}, {bar}, {baz}").format(**locals())

rawDescription: Unpythonic way of printing variables in Python?


rawDescription: Is there a SUMIF function to sum across identifiers in a dictionary in Python?


code:
import re
import csv

filtered_messages = ['UpdatePlaybackStatusInfo', 'Assert']
fieldnames = ['ticks', 'foo', 'type', 'bar', 'message']

with open('log.txt') as log:
    with open('output.csv', 'w') as csv_file:
        writer = csv.DictWriter(csv_file, delimiter=',', fieldnames=fieldnames)
        writer.writerow(dict((fn,fn) for fn in fieldnames))
        for line in log:
            match = re.search(r'^Ticks = (?P<ticks>\d+)\s+<(?P<foo>\d+)> <(?P<type>\w+)> <(?P<bar>\d+)>\s+(?P<message>.+)$', line)
            if match is not None and match.group('type') in filtered_messages:
                writer.writerow(match.groupdict())

rawDescription: Need to parse a tool log file in python and then save the results in excel or csv


code:
dist = np.abs(np.subtract.outer(X,Y))
dist

rawDescription: Interleave two numpy arrays based on element distances (python)


code: [item for items in zip(date_list, num_list_1, num_list_2) for item in items]

rawDescription: combine multiple lists horizontally into a single list

description: Combine multiple lists horizontally into a single list


rawDescription: How do i get the output in one line as a string?

description: Get the output in one line as a string


code: ITEM_PIPELINES = {"Project.middleware_module.SortedCSVPipeline.SortedCSVPipeline" : 1000}

rawDescription: Python Scrapy function to be called just before spider_closed signal sent?


code:
import re
data = """car is on fire
found fire crews on scene"""
m = re.search(r'\bfire\b(?!.*\bcrews\b)', data, re.M)
m.group()
m = re.search(r'.*\bfire\b(?!.*\bcrews\b).*', data, re.M)
m.group()

rawDescription: Python regex match world but exclude certain phrase


code:
from tkinter import *

class TextEntryDialog:
    def __init__(self, master):
        self.top = Toplevel(master)
        self.top.title("TextEntryDialog")

        self.textField = Entry(self.top) # parent
        self.textField.pack()

root = Tk()
root.title("MainWindow")
ted = TextEntryDialog(root)
root.mainloop()

rawDescription: Python Tkinter - Close dialog without closing main window


code:
l = [["foo", 2], ["bar", 1], ["foobar", 2]]
mx = max(l, key=itemgetter(1))

maxes = [ele for ele in l if ele[1] == mx[1]]

rawDescription: Python list check if 2 largest values are the same


rawDescription: Why can't I change a list in a method?

description: Why can't I change a list in a method


rawDescription: Python - How to split a string by non alpha characters


code: g.username = user.name

rawDescription: Jinja2 and Flask: Pass variable into parent template without passing it into children


rawDescription: Pythonic way to compute all combinations of products


code:
base = np.arange(size) # Just the base set of indexes
row = 1                # Which block you want
col = 0
block = a[base[:, np.newaxis] + row * size, base + col * size]

rawDescription: Indexes of fixed size sub-matrices of numpy array


code:
ncol = 3 # pick one dimension
nrow = (len(accountList)+ ncol-1) / ncol # make sure enough subplots
fig, ax = plt.subplots(nrows=nrow, ncols=ncol) # create the axes

for i in xrange(len(accountList)):   # go over a linear list of data
  ix = np.unravel_index(i, ax.shape) # compute an appropriate index (1d or 2d)

  accountList[i].plot( ..., ax=ax[ix])   # pandas method plot
  ax[ix].plot(...)   # or direct axis object method plot (/scatter/bar/...)

rawDescription: Stuffing a pandas DataFrame.plot into a matplotlib subplot


code:
class ClassB:
    def listener(self, deleted):
        print('ClassA {} was deleted, notified ClassB {}'.format(id(deleted), id(self)))

def listener1(deleted):
    print('ClassA {} was deleted, notified listener1'.format(id(deleted)))

def listener2(deleted):
    print('ClassA {} was deleted, notified listener2'.format(id(deleted)))

# setup, one ClassA and 4 listeners (2 methods, 2 functions)

a = ClassA()
b1 = ClassB()
b2 = ClassB()
a.registerCallback(b1.listener)
a.registerCallback(b2.listener)
a.registerCallback(listener1)
a.registerCallback(listener2)

# deletion, we delete one instance of ClassB, and one function

del b1
del listener1

# Deleting the ClassA instance will only notify the listeners still remaining

del a

rawDescription: using python WeakSet to enable a callback functionality

description: Using python WeakSet to enable a callback functionality


code:
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get("http://justbet.co.ke/index.php?option=com_justbet&league=1539&Itemid=123")
options = driver.find_elements_by_xpath("//td[@class='optionmore']/a")
print(driver.find_elements_by_xpath("//td[@class='suboption ']"))
for opt in options:
    opt.click()
print(driver.find_elements_by_xpath("//td[@class='suboption ']"))

rawDescription: Selenium PhantomJS webdriver doesnt click


code: lambda: send_email('Tank temperature Overheat',tank_temp)

rawDescription: Python, threading.timer object will not run function timer?


code:
from django.contrib.auth.models import User

class Countries(models.Model):
    user = models.ForeignKey(User)

rawDescription: Django - Need some guidance on how to implement a ManyToMany database


code:
from flask import request, jsonify

@app.route('/clients/', methods=['POST'])
def client_broadcast():
    state = request.form['state']

    # here you can store the message under a key in Memcached, Redis or another in-memory cache server
    store_in_cache(state)

    return jsonify(stored=True)

@app.route('/clients/', methods=['GET'])
def client_retrieve():
    # retrieve messages from cache
    msg, timestamp = retrieve_from_cache()

    if msg:
        return jsonify(ready=True, msg=msg, timestamp=timestamp)
    else:
        return jsonify(ready=False)

rawDescription: How to send information from client to server (Flask - python)

description: Send information from client to server (Flask - python)


rawDescription: how to flatten a 2D list to 1D without using numpy?

description: Flatten a 2D list to 1D without using numpy


rawDescription: Filling a blank image with another with opencv


code: x[:x.index(min(x)) + 1]

rawDescription: Extracting certain range of values from an array


rawDescription: NumPy dtype issues in genfromtxt(), reads string in as bytestring


code:
subjects = [ 'Maths', 'Physics', 'Art', ]

class Student(Base):
  __tablename__ = 'Student'
  student_id = Column(Integer, primary_key=True, autoincrement=True)
  name = Column(String(50, convert_unicode=True), nullable=False)

class StudentEnrollment(Base):
  __tablename__ = 'StudentEnrollment'
  student_id = Column(Integer, ForeignKey('Student.student_id', ondelete='CASCADE'), primary_key=True)
  subject = Column(Enum(*subjects), primary_key=True)
  student = relationship("Student",   primaryjoin='StudentEnrollment.student_id==Student.student_id', uselist=True, backref="enrollments")

rawDescription: SQLAlchemy relationships populating foreign key fields


code: [item for item in lst if item != itemToExclude]

rawDescription: What is the fastest way to remove all instances of a particular entry from a list in Python?


code: sum(1 for x in L if x.vote=='yes')

rawDescription: Counting elements in a list with given property values


rawDescription: Numpy: Sum clumps of rows

description: Numpy: Sum clumps of rows


code:
color = ((-30, 'red'), (-40, (0, 0, 0, 1)))
ax.zaxis.set_gridline_color(*color)
ax.xaxis.set_gridline_color((24, 'blue'))

rawDescription: How to color a specific gridline/tickline in 3D Matplotlib Scatter Plot figure?

description: Color a specific gridline/tickline in 3D Matplotlib Scatter Plot figure


code:
df_b.columns = df_b.columns.map(lambda x: str(x) + '_b')
df_a.join(df_b)

rawDescription: pandas join DataFrame force suffix?

description: Pandas join DataFrame force suffix


code:
from numpy.core.umath_tests import inner1d
a = inner1d(h, c)
np.allclose(a, ans)

rawDescription: A better way to express a multitude of dot products?


code:
g1 = Game(...)
g1.players[True] = playerA
g1.players[False] = playerB

rawDescription: Secondary Join Condition Ignored in Insert SQL Alchemy


code:
import project
project

rawDescription: Override namespace in Python

description: Override namespace in Python


rawDescription: Renaming files according to a set of rules


rawDescription: How to set offset with matplotlib

description: Set offset with matplotlib


code:
# This will save the data as ordered.
data = OrderedDict([('a', '1'), ('b', '2'), ('c', '3')])
cursor.update("""
    UPDATE mytable
    SET ordered = %(data)s;
""", {
    'data': data
})

# This will save the data as unordered. Whatever the internal order
# happens to be for the dict will be sent. When I run it in the python
# interpreter, it results in:
#   [('a', '1'), ('c', '3'), ('b', '2')]
cursor.update("""
    UPDATE mytable
    SET ordered = %(data)s;
""", {
    'data': data
})

rawDescription: Return PostgreSQL hstore as OrderedDict using psycopg2 in Python


code: pd.pivot_table(df, index= df.index.date, columns=df.index.time, values = 'Close')

rawDescription: How to transform a time series pandas dataframe using the index attributes?

description: Transform a time series pandas dataframe using the index attributes


code:
win.setWindowFlags(win.windowFlags() | QtCore.Qt.CustomizeWindowHint)
win.setWindowFlags(win.windowFlags() & ~QtCore.Qt.WindowMaximizeButtonHint)

rawDescription: how to disable the window maximize icon using PyQt4?

description: Disable the window maximize icon using PyQt4


code:
min_length = min([len(lst1 ), len(lst2 )])
for ii in xrange(min_length ):
    l1 = lst1[ii]
    l2 = lst2[ii]
    # go on to do stuff with l1, l2

rawDescription: Best way to create a dictionary for a later comparison of the elements

description: Create a dictionary for a later comparison of the elements


code:
STATICFILES_DIRS = (

    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    '/path/to/my_project/my_app/static/',
)

rawDescription: How can I use Bootstrap with Django?

description: Use Bootstrap with Django


code: (mod, countdict) = mode(magList, countdict)

rawDescription: Why I cannot pass my parameter python

description: Why I cannot pass my parameter python


code:
import numpy as np
from functools import total_ordering

@total_ordering
class A(object):
    def __init__(self, a):
        self.a = a
    def __lt__(self, other):
        return self.a < other.a
    def __eq__(self, other):
        return self.a == other.a
    def __ne__(self, other):
        return self.a != other.a
    def __hash__(self):
        return hash(self.a)
    def __repr__(self):
        return "A({})".format(self.a)
    def __str__(self):
       return repr(self)

rawDescription: numpy.unique generates a list unique in what regard?

description: Numpy.unique generates a list unique in what regard


rawDescription: Splitting a CSV file by range of datetimes


code: np.genfromtxt(StringIO(test), delimiter=",", dtype=("|S10", int, float))

rawDescription: How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

description: Use numpy.genfromtxt when first column is string and the remaining columns are numbers


rawDescription: "Less/greater than" comparison of N-dimensional and (N-k)-dimensional numpy arrays


rawDescription: Python Overwriting List Element

description: Python Overwriting List Element


rawDescription: Extracting rows from a table

description: Extracting rows from a table


code:
def usersummary(request, id):
    return render(request,{'user_id':id}, 'app/usersummary.html')

rawDescription: Url arguments with Django ajax datatable?


code: salt, *passw = map(int, passw.split())

rawDescription: Decode from ord()

description: Decode from ord()


code:
class File(file):
    """ An helper class for file reading  """

    def __init__(self, *args, **kwargs):
        super(File, self).__init__(*args, **kwargs)
        self.BLOCKSIZE = 4096

    def head(self, lines_2find=1):
        self.seek(0)                            #Rewind file
        return [super(File, self).next() for x in xrange(lines_2find)]

    def tail(self, lines_2find=1):
        self.seek(0, 2)                         #Go to end of file
        bytes_in_file = self.tell()
        lines_found, total_bytes_scanned = 0, 0
        while (lines_2find + 1 > lines_found and
               bytes_in_file > total_bytes_scanned):
            byte_block = min(
                self.BLOCKSIZE,
                bytes_in_file - total_bytes_scanned)
            self.seek( -(byte_block + total_bytes_scanned), 2)
            total_bytes_scanned += byte_block
            lines_found += self.read(self.BLOCKSIZE).count('\n')
        self.seek(-total_bytes_scanned, 2)
        line_list = list(self.readlines())
        return line_list[-lines_2find:]

    def backward(self):
        self.seek(0, 2)                         #Go to end of file
        blocksize = self.BLOCKSIZE
        last_row = ''
        while self.tell() != 0:
            try:
                self.seek(-blocksize, 1)
            except IOError:
                blocksize = self.tell()
                self.seek(-blocksize, 1)
            block = self.read(blocksize)
            self.seek(-blocksize, 1)
            rows = block.split('\n')
            rows[-1] = rows[-1] + last_row
            while rows:
                last_row = rows.pop(-1)
                if rows and last_row:
                    yield last_row
        yield last_row

rawDescription: python head, tail and backward read by lines of a text file

description: Python head, tail and backward read by lines of a text file


code:
from functools import partial

with open('somefile', 'rb') as openfileobject:
    for chunk in iter(partial(openfileobject.read, 1024), ''):
        do_something()

rawDescription: What's perfect counterpart in Python for "while not eof"


code:
format, enc = mimetypes.guess_type(filename)
mb = MIMEBase(*format.split('/'))

rawDescription: Using mimetypes.guess_type with email.mime.base.MIMEBase


code: [second for first, second in list_input if first == 'a']

rawDescription: List comprehension python and specific item


code: matched = namesearch('John*Smith', mylist)

rawDescription: How to retrieve dicts from a list of dicts using wildcard key value

description: Retrieve dicts from a list of dicts using wildcard key value


code:
import matplotlib.pyplot as plt

# Note that the size is in inches at 80dpi.
# To set a size in pixels, divide by 80.
fig = plt.figure(figsize=(4, 5))

# Now we'll add an Axes that takes up the full figure
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off') # Hide all ticks, labels, outlines, etc.

# Display the image so that it will stretch to fit the size
# of the figure (pixels won't be square)
ax.imshow(plt.imread('test.png'), aspect='auto')

plt.show()

rawDescription: How can I display a matplotlib interactive window without any of the controls visible?

description: Display a matplotlib interactive window without any of the controls visible


rawDescription: Numpy fancy indexing in multiple dimensions


rawDescription: Better way to create block matrices out of individual blocks in numpy?


code:
#!/usr/bin/env python3

import xml.etree.ElementTree as ET

root=ET.fromstring(b'<?xml version="1.0" ?><BrowseNodeLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01"><OperationRequest><HTTPHeaders><Header Name="UserAgent" Value="Python-urllib/3.5"/></HTTPHeaders><RequestId>54e05f2a-e792-11e5-8694-85b3fa7a9fcf</RequestId><Arguments><Argument Name="AWSAccessKeyId" Value="xxxxx"/><Argument Name="AssociateTag" Value="xxx-21"/><Argument Name="BrowseNodeId" Value="2844434031"/><Argument Name="Operation" Value="BrowseNodeLookup"/><Argument Name="Service" Value="AWSECommerceService"/><Argument Name="Signature" Value="cf1A3M8S30Y32EdxVVoBljYUNrt4ZiqgvM+/B1uPrDg="/><Argument Name="Timestamp" Value="2016-03-11T14:05:38Z"/><Argument Name="Version" Value="2011-08-01"/></Arguments><RequestProcessingTime>0.005945883</RequestProcessingTime></OperationRequest><BrowseNodes><Request><IsValid>True</IsValid><BrowseNodeLookupRequest><BrowseNodeId>2844434031</BrowseNodeId></BrowseNodeLookupRequest></Request><BrowseNode><BrowseNodeId>2844434031</BrowseNodeId><Name>Categorie</Name><IsCategoryRoot>1</IsCategoryRoot><Children><BrowseNode><BrowseNodeId>2892859031</BrowseNodeId><Name>Donna</Name></BrowseNode><BrowseNode><BrowseNodeId>2892862031</BrowseNodeId><Name>Uomo</Name></BrowseNode><BrowseNode><BrowseNodeId>2892857031</BrowseNodeId><Name>Bambine e ragazze</Name></BrowseNode><BrowseNode><BrowseNodeId>2892858031</BrowseNodeId><Name>Bambini e ragazzi</Name></BrowseNode><BrowseNode><BrowseNodeId>1739205031</BrowseNodeId><Name>Prima infanzia</Name></BrowseNode><BrowseNode><BrowseNodeId>2892860031</BrowseNodeId><Name>Abbigliamento specifico e altre marche</Name></BrowseNode></Children><Ancestors><BrowseNode><BrowseNodeId>2844433031</BrowseNodeId><Name>Abbigliamento</Name></BrowseNode></Ancestors></BrowseNode></BrowseNodes></BrowseNodeLookupResponse>')

# This AMAZON_STR is a kind of "header". It comes from xmls attribute of BrowseNodeLookupResponse (could be extracted from it, in case it changes in the future)
AMAZON_STR="{http://webservices.amazon.com/AWSECommerceService/2011-08-01}"

# Recursive function that deals with a node
def get_data_from(xml_node):
    # Loop over the children of current node
    for child in xml_node:
        # To avoid the "Category" Node, we only check the ones who have exactly 2 children
        if len(child) == 2:
            # We only look into the content of BrowseNode nodes
            if child.tag == AMAZON_STR + "BrowseNode":
                # Looping over the children of a BrowseNode node,
                # we simply print the contents (.text)
                for c in child:
                    if c.tag == AMAZON_STR + "BrowseNodeId":
                        print("children : " + c.text)
                    if c.tag == AMAZON_STR + "Name":
                        print("name : " + c.text)

        get_data_from(child)

# Finally call the function on the top node (root)
get_data_from(root)

rawDescription: python xml parser with ElementTree amazon api

description: Python xml parser with ElementTree amazon api


code:
teststep_subtest = Table('teststep_subtest',
    Base.metadata,
    Column('subtest_id', Integer, ForeignKey('SubTests.id'), primary_key=True),
    Column('teststep_id', Integer, ForeignKey('TestSteps.id'), primary_key=True),
    )

class TestStep(Base):
    __tablename__ = "TestSteps"
    id = Column(Integer, primary_key = True)
    tag = Column(String) # @note: just for tests
    #subTestID = Column(Integer, ForeignKey("SubTests.id")) # @note: removed
    testStepNumber = Column(Integer)

class SubTest(Base):
    __tablename__ = "SubTests"
    id = Column(Integer, primary_key=True)
    tag = Column(String) # @note: just for tests
    #testSteps = relationship("TestStep", backref = "subTest", order_by=TestStep.testStepNumber)
    testSteps = relationship('TestStep',
            secondary=teststep_subtest,
            backref='subTests',
            order_by=TestStep.testStepNumber,
            )

rawDescription: Multiple foreign keys in one column referencing the same table


code: plt.plot(range(10), linestyle='--', marker='o', color='b')

rawDescription: matplotlib: Set markers for individual points on a line

description: Matplotlib: Set markers for individual points on a line


code:
from lxml import etree as et

s1 = """foo bar <pb n="42"/> parrots like <pb n="43"/> eggs and spam"""
s2 = "<text>{0}</text>".format(s1)

text = et.fromstring(s2)
root = et.Element('root')
root.append(text)

et.dump(root)

rawDescription: lxml.etree insert elements into element.text

description: Lxml.etree insert elements into element.text


code: blacklist = ["olive leaf plucked", "during mating searson"]

rawDescription: finder.apply_ngram_filter in nltk.collocations to classify some ngrams

description: Finder.apply_ngram_filter in nltk.collocations to classify some ngrams


code:
def GetMaxFlow(flows):
    maks=max(flows, key=lambda k: len(flows[k]))
    return len(flows[maks]), maks

rawDescription: Get longest element in Dict

description: Get longest element in Dict


rawDescription: Using simple python script in qt (via QT-designer)


rawDescription: How to see logging output in embedded python interpreter?

description: See logging output in embedded python interpreter


code:
def get_range(dictionary, begin, end):
  return dict((k, v) for k, v in dictionary.iteritems() if begin <= k <= end)

rawDescription: python: how to get a subset of dict

description: Python: how to get a subset of dict


code:
if request.function in ['action1', 'action2', 'action3']:
    response.delimiters = ['{%', '%}']

rawDescription: Processing ember.js tagged html with python


rawDescription: Seperate words/numbers from symbols in Python


code: data = {x['name']: x for x in original_data}

rawDescription: python - access list element by key

description: Python - access list element by key


code:
def fileLineIter(inputFile,
                 inputNewline="\n",
                 outputNewline=None,
                 readSize=8192):
   """Like the normal file iter but you can set what string indicates newline.

   The newline string can be arbitrarily long; it need not be restricted to a
   single character. You can also set the read size and control whether or not
   the newline string is left on the end of the iterated lines.  Setting
   newline to '\0' is particularly good for use with an input file created with
   something like "os.popen('find -print0')".
   """
   if outputNewline is None: outputNewline = inputNewline
   partialLine = ''
   while True:
       charsJustRead = inputFile.read(readSize)
       if not charsJustRead: break
       partialLine += charsJustRead
       lines = partialLine.split(inputNewline)
       partialLine = lines.pop()
       for line in lines: yield line + outputNewline
   if partialLine: yield partialLine

rawDescription: Python - how to read file with NUL delimited lines?


code:
booking_times = {
   'Today': ['9:00', '12:00', '14:00', '15:00', '19:00', '20:00'],
   'Tue': ['9:00', '12:00', '14:00', '15:00', '19:00', '20:00'],
   'Wed': ['9:00', '12:00', '14:00', '15:00', '19:00', '20:00']
 }

# Create a new booking_times variable that is a list-of-list,
# leading with the 'days' and followed by one list for each time
sorted_keys = ['Today', 'Tue', 'Wed']
booking_times = [sorted_keys] + zip(*(booking_times[s] for s in sorted_keys))

rawDescription: Google App Engine passing template variables into view with arrays


code:
from mock import Mock

readlines = Mock(return_value=[])
stdout = Mock(readlines=readlines)
theMock = Mock(stdout=stdout)
print(theMock.stdout.readlines())

rawDescription: Mock stdout in Python

description: Mock stdout in Python


rawDescription: Dot product sparse matrices

description: Dot product sparse matrices


rawDescription: How do I remove a dictionary from a list depending on a value being present in a list in Python?

description: Remove a dictionary from a list depending on a value being present in a list in Python


code:
def numb(a, b, c, d, e):
    assert {a, b, c, d, e} <= {3, 5, 7}

rawDescription: Conditions of a function

description: Conditions of a function


rawDescription: Opening and using Safari

description: Opening and using Safari


code: res = df.groupby('date').flag.sum()

rawDescription: FX Data - analyse intraday data

description: FX Data - analyse intraday data


rawDescription: Python - Appending list to list during while loop - Result not as expected


code:
callback = self.get_argument('callback')
jsonp = "{jsfunc}({json});".format(jsfunc=callback,
    json=json_encode(obj))
self.set_header('Content-Type', 'application/javascript')
self.write(jsonp)

rawDescription: tornado write a Jsonp object

description: Tornado write a Jsonp object


code:
# will contain a map from names to IDs
name_to_id = dict((row["name"], row["id"]) for row in rows)

rawDescription: Python/MySQL get data from table based on values in a dictionary


code: pixel_rect = image.get_bounding_rect()

rawDescription: Remove border around image in Pygame

description: Remove border around image in Pygame


code:
stream = p.open(format = p.get_format_from_width(SoundGeneratorObject.WIDTH),
                channels = SoundGeneratorObject.CHANNELS,
                rate = SoundGeneratorObject.BITRATE,
                frames_per_buffer = SoundGeneratorObject.CHUNKSIZE,
                output = True,
                stream_callback = callback_maker(SoundGeneratorObject))

rawDescription: (python) Finding the argument of a parent function from a callback


code:
def custom_gen(xs):
    from collections import Counter
    assert all(1 <= i <= 2 for i in xs)
    # There are only 5 unique pieces that can be used:
    pieces = [(1,), (2,), (1, 1), (2, 2), (1, 2)]
    countpieces = {piece: Counter(piece) for piece in pieces}

    def extend(i, n1, n2, result):
        # try all ways of extending with pieces[i];
        # there are n1 1's and n2 2's remaining to be used
        assert n1 >= 0 and n2 >= 0
        if n1 == n2 == 0:
            yield result
            return
        if i == len(pieces):  # dead end
            return
        piece = pieces[i]
        c = countpieces[piece]
        p1 = c[1]
        p2 = c[2]
        # What's the most number of this piece we could
        # possibly take?
        assert p1 or p2
        if p1:
            if p2:
                most = min(n1 // p1, n2 // p2)
            else:
                most = n1 // p1
        else:
            most = n2 // p2
        for count in range(most + 1):
            for t in extend(i+1,
                            n1 - count * p1,
                            n2 - count * p2,
                            result + [piece] * count):
                yield t

    c = Counter(xs)
    for t in extend(0, c[1], c[2], []):
        yield t

rawDescription: Partioning non-unique entities into unique sets with Python


code: from firebase import requests

rawDescription: Distinguishing between Python modules of the same name / installing with different name?


rawDescription: Calculate matrix of pairwise differences for large number of sequences?


code:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.Popen(cmd, startupinfo=startupinfo)

rawDescription: WIndows: subprocess making new console window, losing stdin/out


rawDescription: Regular expression to find string prefix in Python grammar


code:
def check(x):
    if isinstance(x,list):
        if len(x) == 2:
            if all(np.isfinite(ele) for ele in x):
                return True
    return False

rawDescription: Check if dictionary key is filled with list of 2 numbers


code: os.path.join(mydir, myfile)

rawDescription: Windows path in python

description: Windows path in python


code:
shp = A.shape  # Get shape of A
out = (A.reshape(shp[0],shp[1],-1)*B[:,:,None]).reshape(shp)

rawDescription: Elementwise multiplication of tensors of unknown dimension


code:
def loop_function(num):
    num.extend(range(6))

rawDescription: Placing a While-loop Inside a Function

description: Placing a While-loop Inside a Function


code:
class Test:
    def __init__(self):
        self.matrix_names = ['F', 'B', 'H', 'Q', 'R', 'x', 'P']

    def __matrix_read(self, name):
        return (read(".matrix/%s.csv"%filename))

    def __getattr__(self, name):
        if name in self.matrix_names:
            return self.__matrix_read(name)

rawDescription: Using eval in defing Python class data attributs


code:
#pythran export f(float[][])
def f(in_img):
    return 1 / (1 + numpy.exp(-in_img[:,:]))

rawDescription: Opencv python: apply arbitrary function to each pixel without iterating


code:
import argparse

def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument("filename", help="Filename to interact with")
    p.add_argument("-v", "--verbose", action="store_true", help="Turn on verbose mode")

    subparsers = p.add_subparsers(title="Commands", dest="command")

    read_p = subparsers.add_parser("read", help="read from FILENAME")

    load_p = subparsers.add_parser("load", help="load from FILENAME")
    return p.parse_args()

if __name__ == "__main__":
    args = parse_args()

rawDescription: Are there rules to using argparse?

description: Are there rules to using argparse


code: np.add.reduceat(x, [0, 1, 4], axis=1)

rawDescription: sum uneven segments of an array in numpy

description: Sum uneven segments of an array in numpy


code: re.match(".*\d$", process_str)

rawDescription: python regular expression match comma

description: Python regular expression match comma


rawDescription: Overlapping regex

description: Overlapping regex


code: np.argwhere(image[:,:,0] > threshold)

rawDescription: Thresholded pixel indices of a NumPy array


code: myDict['value']

rawDescription: When to use __getattr__

description: When to use __getattr__


rawDescription: Latin Hypercube Sampling from a normal distribution (Python)


rawDescription: Do requests sessions end when the program is killed?


code:
if 0 <= random < 16:
    winning = 0

# The above is a shorthand syntax for this:
# if 0 <= random and random < 16

rawDescription: How do I search a range for a single integer?

description: Search a range for a single integer


code:
#never!
always_return_one = lambda ignored_argument: 1

#OK: functions with names are def'ed not lambda'd
def always_return_one(ignored_argument):
    return 1

#Also OK: pass the lambda to another function as soon as you spell it.
modified_list = some_highorder_function(lambda ignored: 1, [1, 2, 3, 4, 5])

rawDescription: constant lambda function in python

description: Constant lambda function in python


rawDescription: Numpy - Matrix Generation from list comprehension


code: stdscr.hline(y, 0, ord(' '), 80)   # where 80 is the width of the screen

rawDescription: How to move character string in ncurses screen?

description: Move character string in ncurses screen


code:
[settings]
port = 1234
host = abc.com

rawDescription: python script command line arguments from file

description: Python script command line arguments from file


code:
import easygui as eg
import csv

# # KeywordsCSV = dict(csv.reader(open('Keywords and Solutions.csv')))
# why are you nesting THREE function calls? That's awful. Don't do that.
# KeywordsCSV should be named something different, too. `problems` is probably fine.

with open("Keywords and Solutions.csv") as f:
    reader = csv.reader(f)
    problems = dict(reader)

problem = eg.enterbox('Please enter your problem: ', 'Troubleshooting').lower().split()
# this one's not bad, but I lowercased your `Problem` because capital-case
# words are idiomatically class names. Chaining this many functions together isn't
# ideal, but for this one-shot case it's not awful.

rawDescription: Python - Searching a dictionary for strings


code: xnew = np.exp(np.arange(log(x[0]), log(x[-1]), log(x[-1]/x[0])/x.size))

rawDescription: Interpolate on a logarithmic scale in python


code:
from operator import itemgetter

nl = [x.split('~') for x in l]

nl.sort(key=itemgetter(1))
nl.sort(key=itemgetter(2))
nl.sort(key=lambda x: datetime.datetime.strptime(x[3], '%m/%d/%Y %H:%M'),
        reverse=True) # Newest first
nl.sort(key=itemgetter(0))

rawDescription: Sorting a list of strings by their components


code:
with open(phone_numbers) as f:
    reader = csv.DictReader(f)
    names, phones = zip(*[(record['name'], record['value']) for record in reader if record.get('phone').strip()])

rawDescription: How to read several rows from a csv

description: Read several rows from a csv


code:
f_old = open("old.txt")
f_new = open("new.txt", "w")

for line in f_old:
    f_new.write(line)
    if 'identifier' in line:
        f_new.write("extra stuff\n")

f_old.close()
f_new.close()

rawDescription: Insert text into a text file following specific text using Python


code:
class Piece():
    R=4
    L=5
    W=7
    K=9

Ask=input("Which value do you want:")
Value = getattr(Piece, Ask)

rawDescription: Python - Enumerated types

description: Python - Enumerated types


code:
dict1 = {1 :["in",1], 2 :["out",1], 3 :["in",1]}

dict2 = {1 :["out",2], 2 :["out",1]}
vals = []
# get items from dict1 and common keys with largest values
for k, v in dict1.iteritems():
    if k in dict2:
        if dict2[k][1] > v[1]:
            vals.append((k, dict2[k]))
        else:
            vals.append((k,v))
    else:
        vals.append((k,v))
new_d = {}
# add all dict2 to a new dict
new_d.update(dict2)

# add dict1 items and overwrite common keys with larger value
for k,v in vals:
    new_d[k] = v
print(new_d)
{1: ['out', 2], 2: ['out', 1], 3: ['in', 1]}

rawDescription: Python Merge 2 or more Dicts using a value to handle duplicate keys


code: m_angle = math.degrees(math.atan(float(thing.position()[1]-stuff.position()[1]) / thing.position()[0]-stuff.position()[0]))

rawDescription: Odd behavior with division in Python

description: Odd behavior with division in Python


code:
n = 8
dates = pd.date_range('1/1/2013', freq='D', periods=n)
df = DataFrame({'key': np.arange(n),
                'date': dates,
                'value': np.arange(n) * 10})
df2 = DataFrame({'key': np.arange(n),
                 'valid_from': dates[[1,1,1,1,5,5,5,5]],
                 'valid_to': dates[[4,4,4,4,6,6,6,6]],
                 'value': np.arange(n) * 100})

rawDescription: SQL like joins in pandas

description: SQL like joins in pandas


rawDescription: Python some special products of a given list


rawDescription: question related to reverse function and kwargs

description: Question related to reverse function and kwargs


rawDescription: Python App Engine serving files with Google Cloud Storage


code: fn1(xs, lambda m: m[0]<2)

rawDescription: Split data into sub cubes in numpy

description: Split data into sub cubes in numpy


code:
output = [list(combinations(g,2)) for _,g in groupby(li,lambda x: x[0])]
for id_ in output:
    for combo in id_:
        print([x[1] for x in combo])

['Phone', 'MP3 Player']
['MP3 Player', 'headphone']
['MP3 Player', 'laptop']
['MP3 Player', 'tablet']
['headphone', 'laptop']
['headphone', 'tablet']
['laptop', 'tablet']
['tablet', 'laptop']

rawDescription: Fastest way to identify the combinations of items


code:
key = {'A': 1000, 'B': 2000}
df.fillna(value=key).cumsum()

rawDescription: Add specific amount to each column in pandas


code:
people = ['Charlie', 'Augustus', 'Veruca', 'Violet',
         'Mike', 'Joe', 'Willy', 'Miranda']
links = [('Augustus', 'Willy'),
        ('Mike', 'Joe'),
        ('Miranda', 'Mike'),
        ('Violet', 'Augustus'),
        ('Miranda', 'Willy'),
        ('Charlie', 'Mike'),
        ('Veruca', 'Joe'),
        ('Miranda', 'Augustus'),
        ('Willy', 'Augustus'),
        ('Joe', 'Charlie'),
        ('Veruca', 'Augustus'),
        ('Miranda', 'Joe')]

rawDescription: Issue with Python data-mining code from "Programming Collective Intelligence" to count crossed lines


code:
with open('my_file.txt') as my_file:
  y = lambda x: len(x.strip().split('\t'))
  a = [line if y(line) == 5 else '%s%s\n' % (line.strip(), '\t'*(5 - y(line)))
       for line in my_file.readlines()]

# ['11\t22\t33\t44\t\n', '53\t25\t36\t25\t\n', '74\t89\t24\t35\tand\n']

rawDescription: Filling tabs until the maximum length of column


rawDescription: Python expected a character buffer object


code:
policy[0]
policy.read

rawDescription: Python - Get Multiple Characters From String


code:
class Settings(model.Model):
    receive_newsletter = model.BooleanField()
    ...

rawDescription: How to insert a checkbox in a django form

description: Insert a checkbox in a django form


code: L.sort(key=lambda e: max(e))

rawDescription: Python: How to sort a list by the max of each element?


code: with open('data00.pk','rb') as f : u=pickle.load(f)

rawDescription: multiplying two huge matrices using numpy.dot

description: Multiplying two huge matrices using numpy.dot


code:
class Person(models.Model):
  name = models.CharField(max_length=64, blank=True, null=True)
  age = models.IntField(blank=True, null=True)

class Friendship(models.Model):
  members = models.ManyToManyField(Person)

rawDescription: Efficient Django querying across models denoting relationships


code: time, data = np.genfromtxt('./temp.csv', delimiter=',', unpack=True)

rawDescription: Use numpy to read a two-column csv file

description: Use numpy to read a two-column csv file


code:
def parse(args, subcommands):
    cmds = []
    cmd = None
    for arg in args[1:]:
        if arg in (subcommands):
            if cmd is not None:
                cmds.append(cmd)
            cmd = [arg]
        else:
            cmd.append(arg)
    cmds.append(cmd)
    return cmds

rawDescription: Multiple invocation of the same subcommand in a single command line


rawDescription: Porting a VBA Type / C struct to a Python ctypes.Structure: array of strings with fixed length


code:
files = list_of_files
fd = {}
for file in files:
    with open(file) as f:
        for sent in nltk.sent_tokenize(f.lower()):
            for word in nltk.word_tokenize(sent):
                try:
                    fd[word] = fd[word]+1
                except KeyError:
                    fd[word] = 1

rawDescription: How do I count words in an nltk plaintextcorpus faster?

description: Count words in an nltk plaintextcorpus faster


code:
from itertools import izip_longest # needed for grouper helper
list(grouper([1,2,3,4,5,6,7], 2))

rawDescription: How can I rearange a list items into paired tuple/list in python?

description: Rearange a list items into paired tuple/list in python


code:
from collections import defaultdict

# Make an empty dict where, if a key is requested and not found, an empty list
# will be stored for that key as the default.
letter_dict = defaultdict(lambda: [])

rawDescription: Python: creating a variable using retrieved string name


code:
import time

wakeup = time.time()

while True:
    wakeup += 6 * 60

    for i in range(500):
        # something

        # Has it taken longer the 6 minutes?
        if time.time() > wakeup:
            break

    while time.time() < wakeup:
        time.sleep(1)

rawDescription: Restart a script after 6 minutes

description: Restart a script after 6 minutes


code:
def flatten_all(iterable):
    for elem in iterable:
        if not isinstance(elem, list):
            yield elem
        else:
            for x in flatten_all(elem):
                yield x
            # in Python 3.3 just: yield from flatten_all(elem)

rawDescription: Python: multilevel nested lists

description: Python: multilevel nested lists


code:
index = table.model().index(line, 12)
table.model().dataChanged.emit(index,index)

rawDescription: setData is very slow

description: SetData is very slow


code:
@defer.inlineCallbacks
def some_func_better():
    d1 = call1()
    d2 = call2()
    res1 = yield d1
    res2 = yield d2

rawDescription: Twisted Deferred.addCallBack() vs. yield and @inlineDeferred


rawDescription: MongoDB query in pymongo with sort feature


rawDescription: Loop within 26 numbers

description: Loop within 26 numbers


code: myfunc(key1="value1", key2="value2")

rawDescription: Formal parameter of the form **keyword

description: Formal parameter of the form **keyword


code:
import pandas as pd
df1 = pd.read_csv('path\\to\\file1.csv')
df2 = pd.read_csv('path\\to\\file2.csv')

writer = pd.ExcelWriter('path\\to\\output\\file.xls')
df1.to_excel(writer,'sheet1')
df2.to_excel(writer,'sheet2')
writer.save()

rawDescription: joining two .xls file into a single .xls file with 2 sheets

description: Joining two .xls file into a single .xls file with 2 sheets


code:
for w in root.winfo_children():
    w.configure(state="disabled")

rawDescription: disable buttons in Python and Tk

description: Disable buttons in Python and Tk


code:
def func(x, y, z, a, b, c):
    f = (a**2
         + x * b**2
         + y * a * b * np.cos(c)
         + z * a * b * np.sin(c))
    return f

rawDescription: Solving non-linear equations in python

description: Solving non-linear equations in python


code:
import os
from ctypes import *
open('tmp.c', 'w').write(r'''
#include <stdio.h>
typedef char (*callback_t)(char **buf);
int test(callback_t foo)
{
    char res, *buf;
    res = foo(&buf);
    printf("res: %d\n", res);
    printf("buf: %s\n", buf);
    return 0;
}
''')
_ = os.system('gcc -shared -fPIC -o tmp.so tmp.c')
lib = CDLL('./tmp.so')
class Test(object):
  def __init__(self):
    self.response = create_string_buffer("The Response String")
    self.callback = CFUNCTYPE(c_byte, POINTER(POINTER(c_char)))(self.pyfoo)
  def pyfoo(self, char_ptr_ptr):
    char_ptr_ptr[0] = self.response
    return 0

t = Test()
_ = lib.test(t.callback)

rawDescription: Using ctypes to write callbacks that pass-in pointer to pointer parameters to be used as output-parameter


code:
class A(b.generalObjectLikeA):
    def __init__(self):
        pass

    def some_method_in_a(self):
        pass

rawDescription: How can I define a class in multi file(or module) in python

description: Define a class in multi file(or module) in python


code:
[[u'Gallup US Consumer Spending Measure8:30 AM\xa0ET',
  u'4-Week Bill Announcement11:00 AM\xa0ET',
  u'3-Month Bill Auction11:30 AM\xa0ET',
  ...
 ],
 ...
]

rawDescription: Python 2.7 : Can't figure out how to parse a tree with BeautifulSoup4


code:
urlpatterns = patterns('',
    url(r'^wiki/Sacramentum_(oath)/', my_view),
)

rawDescription: Parenthesis URL dispatcher Django?

description: Parenthesis URL dispatcher Django


code:
def post(self):
    write_retry_params = gcs.RetryParams(backoff_factor=1.1)
    filename = '/{MY-BUCKET-NAME}/static.txt'

    gcs_file = gcs.open(
        filename,
        'w',
        content_type='text/plain',
        options={'x-goog-meta-foo': 'foo',
                 'x-goog-meta-bar': 'bar'},
        retry_params=write_retry_params)

    inFile = self.request.POST.multi['file'].file
    while 1:
        line = inFile.readline()
        if not line:
            break
        gcs_file.write(line)
        logging.info('Wrote line: {}'.format(line))

    gcs_file.close()

rawDescription: Google App Engine: store uploaded file in Google Cloud Storage


code:
surShader = cmds.ls(type = 'surfaceShader')
for con in surShader:
    surShaderOut = cmds.listConnections('%s.outColor' % con)
    surShaderTex = cmds.getAttr("%s.fileTextureName" % surShaderOut[0])

rawDescription: Unable to display all the information except for first selection


code: fill(*i)

rawDescription: Declare python variable that stores a function, but not run it


code:
@functools.lru_cache(maxsize=500)
def nck(n, k):
    ...

rawDescription: Find the index of a given combination (of natural numbers) among those returned by `itertools` Python module


code:
@app.route('/test')
def test():
    title = "Page for tree test"
    roots = Category.query.filter_by(parent_id=None)
    full_tree = []
    for root in roots:
        full_tree.append(root.drilldown_tree()[0])
    return render_template('test.html', title=title, category=full_tree)

rawDescription: SQLAlchemy-mptt get full tree

description: SQLAlchemy-mptt get full tree


code:
from collections import Counter
pred = lambda t: not t[-1] != t[-1] # predicate to drop the partial ones
iter = (ts.shift(-j) for j in range(3))
Counter(filter(pred, zip(*iter)))
pd.Series(_)

rawDescription: Summary of recurring subseries w/in a pandas Series


rawDescription: python: convert to HTML special characters

description: Python: convert to HTML special characters


code:
Tokenizing
tokA = strA.split('-')
tokB = strB.split('-')

print('NS4' in tokA and tokA.index('NS1') > tokA.index('NS4'))
print('NS4' in tokB and tokB.index('NS1') > tokB.index('NS4'))

# False
# True

rawDescription: How to specify the regex string in python

description: Specify the regex string in python


code: new_filename = "_".join([file_names.get(k, k) for k in filename_noext.split('_')])

rawDescription: How to rename a specific word in a file name using python

description: Rename a specific word in a file name using python


rawDescription: Manually replace elements in a list

description: Manually replace elements in a list


rawDescription: Ignore strings which do not completely match regex?


rawDescription: Using argparse with function that takes **kwargs argument


code: sumval, prodval = f(5,7)

rawDescription: how to return multiple values from a function and use that in somewhere else in python programme

description: Return multiple values from a function and use that in somewhere else in python programme


rawDescription: create a list from a functions output?

description: Create a list from a functions output


code:
import re
re.split('(?<=[0-9])-', text)

rawDescription: (Python) Splitting string only on single instance of delimiter


code: [''.join(c) for c in itertools.product(*['abc'] * 3)]

rawDescription: Help understanding how this recursive python function works?


code:
for key, value in my_dict.items():
   do_the_stuff(key, value)

rawDescription: Get key from dictionary

description: Get key from dictionary


code: df = df.astype(object)

rawDescription: Pandas - make a column dtype object or Factor


code:
import sys
sys.path.insert('/path/to/correct/robot/')
import robot

rawDescription: Create Python object from different .py file


code:
x
y

rawDescription: NumPy map calculation depending on the indices


code: thread = [threading.Thread(target=filestat, args=(filename,)) for filename in files]

rawDescription: Python Threading with varying arguments (Python 2.4.3)


code: from django.contrib.auth.decorators import login_required

rawDescription: Converting separate functions into class-based


code: G[slices] = np.gradient(N[slices])

rawDescription: Efficiently recalculating the gradient of a numpy array with unknown dimensionality


code:
def fileswithcymintree(treeroot_dirname, whatym):
    results = []
    for dp, dirs, files in os.walk(treeroot_dirname):
        for f in files:
            fullname = os.path.join(dp, f)
            if whatym == cym(fullname):
                results.append(fullname)
    return results

rawDescription: Python dealing with dates and times

description: Python dealing with dates and times


code:
print(', '.join(y))    # using join()
print(*y, sep=', ')    # Python 3 style print function

rawDescription: Sort an Input List of Floating Numbers.

description: Sort an Input List of Floating Numbers.


code:
with hide('running', 'stdout', 'stderr'):
    run('echo -e "%s\n%s\n" | sudo passwd %s' % (passwd, passwd, user))

rawDescription: use fabric to change default postgres user password

description: Use fabric to change default postgres user password


code: soup.find_all(lambda e: e.name == 'td' and 'Black' in e.text)

rawDescription: Why does bs4 return tags and then an empty list to this find_all() method?


code:
log_data = {
    'esp': generic_dict(),
    'por': generic_dict(),
    'sui': generic_dict(),
    'ben': generic_dict(),
    'mex': generic_dict(),
    'arg': generic_dict(),
}

rawDescription: How can I properly copy nested dictionary objects?

description: Properly copy nested dictionary objects


code:
def filter_unique(records, columns):
    unique = set(tuple(rec[col] for col in columns) for rec in records)
    return [dict(zip(columns, items)) for items in unique]

rawDescription: Extract specific column and group them from dictionary in Python


rawDescription: how does Cpython implement its type Objects, i.e. type's type is always type?

description: How does Cpython implement its type Objects, i.e. type's type is always type


rawDescription: Expanding a list of tuples

description: Expanding a list of tuples


code:
keys = np.array(mapping.keys())
vals = np.array(mapping.values())
result = vals[(data.reshape(-1, 1) == keys).nonzero()[1]]
result

rawDescription: Numpy: Convert values in a 1-D array based upon dictionary


code:
#!/usr/bin/env python
import json
from datetime import date
import icalendar # $ pip install icalendar

today = date.today()
calendar = icalendar.Calendar.from_ical(ics_file)
entries = [dict(summary=event['SUMMARY'])
           for event in calendar.walk('VEVENT')
           if event['DTSTART'].dt <= today <= event['DTEND'].dt]
print(json.dumps(entries, indent=2, sort_keys=True))

rawDescription: parse dates with icalendar and compare to python datetime

description: Parse dates with icalendar and compare to python datetime


code:
def input(a, b, c) :
    return min(max(a,b),max(b,c),max(a,c))

rawDescription: Middle value using python 3

description: Middle value using python 3


code:
import string

miriam = True

def get_letter_dict():
    return {val: idx for idx, val in enumerate(string.ascii_lowercase, 1)}

while miriam == True:
    letter_dict = letters()
    code_decode = input("would you like to code or decode? ")
    if code_decode.lower() == "code":
        code = input("enter the text you would like to code:\n")  # makes it easier to read
        listed_code= [letters[c] for c in code.lower()]
        print(listed_code)

rawDescription: how to change letters in a list to their corresponding alpabetical numbers in python

description: Change letters in a list to their corresponding alpabetical numbers in python


code: beta = alpha[1:].sum()

rawDescription: How to "simulate" numpy.delete during processing


code:
import re
strs = "3 Bedroom, Residential Apartment in Velachery"
re.sub(r'\s*Bedroom\s*', '', strs)

rawDescription: Cut of middle word from a string python

description: Cut of middle word from a string python


code:
for i, val in enumerate(lst):
    if text in val:
        desired = list( islice( cycle( lst), i+1, i+1+x))

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


code:
s.get("https://httpbin.org/cookies/set?foo=bar")
assert not s.cookies

rawDescription: How to disable cookie handling with the Python requests library?

description: Disable cookie handling with the Python requests library


code:
import os, imp
dirs = os.listdir('.')
dirs
modules = {d: imp.load_source(d, d + '/submission.py') for d in dirs}
modules

rawDescription: Calling A function from multiple scripts in python


code:
sample_names = list(set(pd.read_csv(infile, sep="\t", engine="c", usecols=[4], squeeze=True)))
sample_names.sort()

rawDescription: Read large csv file with many duplicate values, drop duplicates while reading


code:
numbers = (k for k in range(1, 42) if k%2 != 0)
[x * [-1, 1][n % 2] for n, x in enumerate(numbers)]

rawDescription: List Comprehension and traversing through a list


code:
Foo.lock = threading.Lock()

def interlocked_inc(n):
    for i in xrange(n):
        with Foo.lock:
            Foo.instance_count += 1

threads = [threading.Thread(target=interlocked_inc, args=(100000,)) for thread_nr in xrange(100)]
for thread in threads: thread.start()
for thread in threads: thread.join()

print(Foo.instance_count)

rawDescription: Is modifying a class variable in python threadsafe?


code:
while element<length:
    if lis[element][13:16] == lis[element+1][13:16]:
        array.append(element)

rawDescription: Removing repeated lines from text file

description: Removing repeated lines from text file


code:
sql_string = ",".join("'%s'"%i for i in sys.argv[1:])
sql_string

rawDescription: Python, How to take a comma separated sys argv, and make it like '1','2' (for MySQL "IN" Query)


code:
import pandas as pd

df = pd.read_json('data.json')
df.set_index('timestamp',inplace=True)
print(df)

rawDescription: Timestamp index for pandas dataframe from read_json()


code:
newtitle = '\n'.join(['$%s$'%item for item in wrap(title, width=50)]).replace(' ', '\ ')
newtitle = "%s\n%s"%('text\ below\ the\ main\ title', newtitle)

rawDescription: title in italic font in matplotlib isn't working

description: Title in italic font in matplotlib isn't working


code:
from resources import foo

foo()

rawDescription: How to call method from another kodi/xbmc addon

description: Call method from another kodi/xbmc addon


code:
short_genome = get_random_string(length=32, allowed_chars='ACTG')
short_genome

rawDescription: Django package to generate random alphanumeric string


rawDescription: Python inserting a short integer into a list of bytes


code:
import json

newConditions = {"con1":40, "con2":20, "con3":99, "con4":40, "password":"1234"}
params = json.dumps(newConditions).encode('utf8')
req = urllib.request.Request(conditionsSetURL, data=params,
                             headers={'content-type': 'application/json'})
response = urllib.request.urlopen(req)

rawDescription: Python3: JSON POST Request WITHOUT requests library


rawDescription: Clear invalid escape in python?

description: Clear invalid escape in python


rawDescription: wxPython textctrl temporarily gets black rectangle

description: WxPython textctrl temporarily gets black rectangle


rawDescription: Match a sequence of numbers preceded by certain text


code:
def addTextToRaw(self, text, changeColour=False):
    self.rawText.config(state=NORMAL)
    if changeColour is True:
        self.rawText.insert(END,text ,'oddObject')
    else:
        self.rawText.insert(END,text)
    self.rawText.config(state=DISABLED)

rawDescription: Tkinter Text Tag Config not persisting

description: Tkinter Text Tag Config not persisting


code:
from abc import ABCMeta, abstractmethod

class Divisible(metaclass=ABCMeta):
    """Anything with __truediv__ method."""
    __slots__ = ()
    __hash__ = None # disable default hashing

    @abstractmethod
    def __truediv__(self, other):
        """Return self / other."""

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Divisible:
            if any("__truediv__" in B.__dict__ for B in C.__mro__):
                return True
        return NotImplemented

class Addable(metaclass=ABCMeta):
    """Anything with __add__ method."""
    __slots__ = ()
    __hash__ = None # disable default hashing

    @abstractmethod
    def __add__(self, other):
        """Return self + other."""

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Addable:
            if any("__add__" in B.__dict__ for B in C.__mro__):
                return True
        return NotImplemented

rawDescription: Make my_average(a, b) work with any a and b for which f_add and d_div are defined. As well as builtins


code:
packed_input = coded_file.read()
last_byte_length, packed_input, last_byte = (packed_input[0],
                                             packed_input[1:-1],
                                             packed_input[-1])
if not last_byte_length: last_byte_length = 8
ascii_input = ''.join(chain((bin(ord(byte))[2:].zfill(8) for byte in packed_input),
                      tuple(bin(ord(last_byte))[2:].zfill(last_byte_length),)))
# OR
# ascii_input = ''.join(chain(('{0:0=8b}'.format(byte) for byte in packed_input),
#                       tuple(('{0:0=' + str(last_byte_length) + '8b}').format(last_byte),)))

rawDescription: Huffman encoding: how to write binary data in Python


code:
from timeit import timeit
import re

def substring():
    for x in do_not_scan:
        if x in string:
            return True
    return False

def any_substring():
    return any(x in string for x in do_not_scan)

def find_def():
    for x in do_not_scan:
        if string.find(x) != -1:
            return True
    return False

def index_of():
    for x in do_not_scan:
        try:
            string.index(x)
            return True
        except:
            return False

def re_match():
    for x in do_not_scan:
        if re.search(string, x):
            return True
    return False

string = 'a'
do_not_scan = ['node_modules','bower_components']

print(timeit('substring()', setup='from __main__ import substring'))
print(timeit('any_substring()', setup='from __main__ import any_substring'))
print(timeit('find_def()', setup='from __main__ import find_def'))
print(timeit('index_of()', setup='from __main__ import index_of'))
print(timeit('re_match()', setup='from __main__ import re_match'))

rawDescription: Python3 Fast Way To Find If Any Elements In Collections Are Substring Of String


code:
v1 = np.zeros(20)
v2 = np.zeros(20)
is_foo = np.asarray([ele.type == "foo" for ele in data])
v1[~is_foo] = 1
v2[~is_foo] = 20

rawDescription: Vector filling array using numpy

description: Vector filling array using numpy


code:
class SetQueue(Queue.Queue):
    def _init(self, maxsize):
        self.queue = set()
    def _put(self, item):
        self.queue.add(item)
    def _get(self):
        return self.queue.pop()

rawDescription: Check if element is already in a Queue

description: Check if element is already in a Queue


code:
import subprocess

def tail(filename):
    process = subprocess.Popen(['tail', '-F', filename], stdout=subprocess.PIPE)

    while True:
        line = process.stdout.readline()

        if not line:
            process.terminate()
            return

        yield line

rawDescription: Get return value from shell command in python


code:
import win32ui
# X from the left margin, Y from top margin
# both in pixels
X=50; Y=50
multi_line_string = input_string.split()
hDC = win32ui.CreateDC ()
hDC.CreatePrinterDC (your_printer_name)
hDC.StartDoc (the_name_will_appear_on_printer_spool)
hDC.StartPage ()
for line in multi_line_string:
     hDC.TextOut(X,Y,line)
     Y += 100
hDC.EndPage ()
hDC.EndDoc ()

rawDescription: python win32print not printing

description: Python win32print not printing


code:
from itertools import groupby
from operator import itemgetter

sla_list = self.object_list.filter(types__name="Unplanned").filter(service__sla=True).order_by('service__name').values_list('service__name', 'end_out', 'start_out')
sla_deltas = {}
for name, entries in groupby(sla_list, itemgetter(0)):
    sla_deltas[name] = sum(end - start for name, end, start in entries)

rawDescription: Django View Nested Tuple Calculation

description: Django View Nested Tuple Calculation


code:
for i in paragList:
    para_string = para_string + str(i)
    newlist = range(len(findPatTitle))
    for i in newlist:
        ofile = open(str(listIterator[i])+'.txt', 'w')
        ofile.write(para_string)
        ofile.close()

rawDescription: Python Blog RSS Feed Scraping BeautifulSoup Output to .txt Files


code:
import numpy as np
import pandas as pd
df = pd.read_csv("dummy.csv")
str_ = lambda x:x[2:-1]
df["Timestamp"] = df["Timestamp"].map(str_)
df["Timestamp"] = pd.to_datetime(df["Timestamp"])
delta_ = df["Timestamp"].iat[-1] - df["Timestamp"].iat[0]
delta_
delta_ / np.timedelta64(1, "s")

rawDescription: Subtract last and first elements in a column using Python Pandas


code:
import calendar
list(calendar.day_name)

rawDescription: Get Day name from Weekday int

description: Get Day name from Weekday int


code:
for (sublist, shortcut) in shortcuts:
    replace_list(mvts, sublist.split(), shortcut) #@latty's function

rawDescription: Search replace patterns in a Python list


rawDescription: Pandas DataFrame column values in to list


code:
from innerlink import parse
with open("fragment.html") as f:
    parse(f.read())

rawDescription: How to read inner tags with HTMLParser?

description: Read inner tags with HTMLParser


code:
try:
    cmd= ['C:\Program Files\ImageMagick-6.8.3-Q16\convert','-size','30x40','xc:white','-fill','white','-fill','black','-font','fonts\Helvetica Regular.ttf','-pointsize','40','-gravity','South','-draw',"text 0,0 'P'",'draw_text.gif']
    print(str.join(' ', cmd))
    print('stdout: {}'.format(subprocess.check_output(cmd,shell=True,stderr=subprocess.STDOUT)))
except CalledProcessError as e:
    print(e)
    print(e.output)

rawDescription: running imagemagick convert (console application) from python

description: Running imagemagick convert (console application) from python


code:
class SurveyList(ListAPIView):
     queryset = Survey.objects.all()
     serializer_class = SurveySerializer

rawDescription: Django Rest Framework how to customize ListAPIView


code: v.set = "Internet is online"

rawDescription: Tkinter set new value for labels

description: Tkinter set new value for labels


code:
def replaceNum(myList, n):
    return [x if x != n else 1 for x in myList]

print(replaceNum([5, 10, 20], 10))

rawDescription: A function that takes in both a list (myList) and a value (n) and checks whether or not the value is in that list


rawDescription: Create new pandas timeseries dataframe from other dataframe


code:
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

rawDescription: python backports for some methods

description: Python backports for some methods


rawDescription: How to write a regex that pulls unordered list and paragraph preceding it

description: Write a regex that pulls unordered list and paragraph preceding it


code:
tf = 'textfile.txt'
f2 = open(tf, 'a+')
f2.writelines([str(data) + '\n' for data in [title,des,img,tag,tag2,tag3]])
f2.close()

rawDescription: Python, Writing Multiple Lines

description: Python, Writing Multiple Lines


rawDescription: Python: Complete asymmetric grid

description: Python: Complete asymmetric grid


code:
{
    "_id": ObjectId("553799187174b8c402151d06"),
    "category": "food",
    "venues": [
        {
            "name": "Thai Restaurant",
            "value": 251
        },
        {
            "name": "KFC",
            "value": 124
        },
        {
            "name": "Chinese Restaurant",
            "value": 21
        }
    ]
}

rawDescription: python: query mongodb database to find a specific value under a unknown field

description: Python: query mongodb database to find a specific value under a unknown field


code:
with open("in.txt") as f:
    prev = ""
    for line in f:
        if not line.startswith("!NAME:"):
            print(prev.rstrip())
            print(line.rstrip())
            for line in f:
                if line.startswith("!NAME:"):
                    prev = line
                    break
                print(line.rstrip())
                prev = line
        prev = line

rawDescription: Get text between two identical lines in Python


code: import pickle, sys

rawDescription: Is it possible to tell the IDLE python shell to automatically import modules every time you start it?


code:
list = ["{0:04b}".format(x) for x in range(16)]
print(list)

rawDescription: Python List - basic binary

description: Python List - basic binary


rawDescription: Python sort list of lists over multiple levels and with a custom order


code:
Player.objects.filter(score__score__lte=1000
                     ).annotate(max_score=Max('score__score'))

rawDescription: How to reduce multiple queries to only one query?

description: Reduce multiple queries to only one query


rawDescription: Mathematical function in Python

description: Mathematical function in Python


code:
def fix_orientation(file_like_object):
    img = Image.open(filename)

    # ... snip ...

    data = BytesIO()
    img.save(data)
    return data

rawDescription: Is there a cleaner way to rotate smartphone images uploaded via flask before pushing to S3?


rawDescription: How to match all links in python regex?

description: Match all links in python regex


code:
import contextlib

class context_mixin:
    def __enter__(self):
         self.__context = self.context()
         return self.__context.__enter__()
    def __exit__(self, *args):
         return self.__context.__exit__(*args)

class class_a(context_mixin):
    @contextlib.contextmanager
    def context(self):
         print('class_a enter')
         try:
             yield self
         finally:
             print('class_a exit')

class class_b(class_a):
    @contextlib.contextmanager
    def context(self):
        with super().context():
            print('class_b enter')
            try:
                yield self
            finally:
                print('class_b exit')

rawDescription: Pythons 'with'-statement: correctly nest/derive classes with __enter__/__exit__


code:
'({0[0]}, {0[1]})'.format(a)
'({}, {})'.format(*a)
'{0[0]}, {0[1]}'.format(a)   # without parentheses
'{}, {}'.format(*a)          # without parentheses

rawDescription: How to Modify a String in wx.StaticText?

description: Modify a String in wx.StaticText


code:
stringA, stringB = 'abcdefg', 'hijklmn'
any(char in stringB for char in stringA)
stringA, stringB = 'dog', 'abcdefg'
any(char in stringB for char in stringA)

rawDescription: Doing "if string a contains any letter in string b" with Python


code:
from collections import Counter
counts = Counter(['2', '5', '2', '5', '5', '3'])
counts
' * '.join(['{}^{}'.format(k, v) for k, v in counts.most_common()])

rawDescription: Python: Count and rearrange numbers with same value in a list


code:
not (len(x) - len(y)) and not any(map(lambda i, j: i - j, x, y))
not (len(x) - len(z)) and not any(map(lambda i, j: i - j, x, z))

rawDescription: Equality without using operator

description: Equality without using operator


rawDescription: accessing ArgumentParser variable with environment variable

description: Accessing ArgumentParser variable with environment variable


code:
class SignupFormExtra(SignupForm):
    address = forms.CharField(label=_(u'Address'),max_length=30,required=False)
    contact = forms.CharField(label=_(u'Contact'),max_length=30,required=False)
    business = forms.CharField(label=_(u'Business Name'),max_length=30,required=False)

    def save(self):
        """
        Override the save method to save the first and last name to the user
        field.

        """
        # Original save method returns the user
        user = super(SignupFormExtra, self).save()

        # Get the profile, the `save` method above creates a profile for each
        # user because it calls the manager method `create_user`.
        # See: https://github.com/bread-and-pepper/django-userena/blob/master/userena/managers.py#L65
        user_profile = user.get_profile()

        # Be sure that you have validated these fields with `clean_` methods.
        # Garbage in, garbage out.
        user_profile.address = self.cleaned_data['address']
        user_profile.contact = self.cleaned_data['contact']
        user_profile.save()

        # Business
        business = self.cleaned_data['business']
        business = Business.objects.get_or_create(name=business)
        business.save()

        # Return the user, not the profile!
        return user

rawDescription: adding extra fields to django-userena forms

description: Adding extra fields to django-userena forms


code:
key = 'your own key'
from safebrowsinglookup import SafebrowsinglookupClient
client = SafebrowsinglookupClient(key)
client.lookup('http://addonrock.ru/Debugger.js')
client.lookup('http://google.com')

rawDescription: Selenium: page displayed differently

description: Selenium: page displayed differently


rawDescription: Retrieve lyrics from an mp3 file in Python using eyeD3


rawDescription: Parsing XML with ElementTree in Python

description: Parsing XML with ElementTree in Python


code:
[{u'Class': u'Regression_TestCase.RegressionProject_TestCase2.RegressionProject_TestCase2',
  u'Error': u'9',
  u'Fail': u'1',
  u'Skip': u'0',
  u'Success': u'219',
  u'Total': u'229'}]

rawDescription: BeautifulSoup my for loop is printing all the data from the td tag. I would like to exclude the last section of the td tag


code:
import json
template = 'full iCal template with {insert_point} spec goes here'
data = json.JSONDecoder().decode(your_json_data)
ical = template.format(**data)

rawDescription: Convert JSON to .ics (Python)

description: Convert JSON to .ics (Python)


code:
deep_copy_of_outer = copy.deepcopy(outer)
deep_copy_of_outer[0] is a
outer[0] is deep_copy_of_outer[0]

rawDescription: Shallow/Deep copy in python

description: Shallow/Deep copy in python


code:
def addbook(request):
    if request.method == 'POST':
        name = request.POST['name']
        author = request.POST['author']
        bookInfo.objects.create(Name = name, Author=author)
        return render(request, 'index.html', {'Name': name, 'Author': author})

rawDescription: How to configure HTML form to work with django models?

description: Configure HTML form to work with django models


code:
import wmi

c = wmi.WMI()

for service in c.Win32_Service(Name="W3SVC"):
    result, = service.StopService()

rawDescription: Restarting IIS6 - Python

description: Restarting IIS6 - Python


code:
set(B).issubset(A)
set(A).issubset(B)

rawDescription: Compare List with different number of items


code:
from itertools import izip

def multi_enumerate(*iterables):
    return ((n,) + t for n, t in enumerate(izip(*iterables)))

rawDescription: Variable length 'yield'?

description: Variable length 'yield'


code:
# Create an empty list at the beginning
list_of_dicts = []

# Then, for each dict you create...
d = { 'id' : counter,
      'file': [ {'name': filename,
                 'uri' : 'http://localhost:8000/uploads/' + filename,
                 'path' : os.path.join(dirname, filename) } ] }
# ... add it to your list
list_of_dicts.append(d)

rawDescription: Python Dictionary Appending

description: Python Dictionary Appending


code:
if not pickle.load(open("%s.p"%username, "rb"))[1]:
    break

rawDescription: Why is it continuing to repeat the while True even though I have broken it?


code:
import sys                 # we import the module
sys.__repr__()               # works as usual
sys.__dict__['__repr__']     # but it's not in the modules __dict__ ?
sys.__class__.__dict__['__repr__'] # __repr__ is provided on the module type as a slot wrapper
sys.__class__.__dict__['__repr__'](sys) # which we should feed an instance of the module type

rawDescription: Can a python module have a __repr__?

description: Can a python module have a __repr__


code:
import csv
CSV_FIELDS = ("field1", "field2", "field3")

class MyDictReader(csv.DictReader):
    def next(self):
        if self.line_num == 0:
            # Used only for its side effect.
            self.fieldnames
        row = self.reader.next()
        self.line_num = self.reader.line_num

        d = dict(zip(self.fieldnames, row))
        lf = len(self.fieldnames)
        lr = len(row)
        if lf < lr:
            d[self.restkey] = row[lf:]
        elif lf > lr:
            for key in self.fieldnames[lr:]:
                d[key] = self.restval
        return d

for row in MyDictReader(open("f", 'rb'), fieldnames=CSV_FIELDS, restval=""):
    print(row)

rawDescription: Why does csv.DictReader skip empty lines?


code:
n = 3
channel = ['this', 'use', 'globals()']

print(' '.join(channels[i] for i in range(n)))

rawDescription: How to add certain number of variable names to a string

description: Add certain number of variable names to a string


code:
mylist = [1,2,3]
','.join("'{0}'".format(x) for x in mylist)

rawDescription: How to convert list into string with quotes in python

description: Convert list into string with quotes in python


code: [x for x,y in enumerate(lst) if "aaa" in y]

rawDescription: Python - search for string in array

description: Python - search for string in array


code:
def counter():
    r = re.compile('[^0-9]')
    for x in self.get_xs():
        yield sum(int(number) for number in r.sub('', x))

rawDescription: How to write in more pythonic way?

description: Write in more pythonic way


code:
import struct

def read_complex_array(filename, M, N):
    row_fmt = '={}h'.format(N)  # "=" prefix means integers in native byte-order
    row_len = struct.calcsize(row_fmt)
    result = []
    with open(filename, "rb" ) as input:
        for col in xrange(M):
            reals = struct.unpack(row_fmt, input.read(row_len))
            imags = struct.unpack(row_fmt, input.read(row_len))
            cmplx = [complex(r,i) for r,i in zip(reals, imags)]
            result.append(cmplx)
    return result

rawDescription: Reading complex binary file in python

description: Reading complex binary file in python


code: [id(x) for x in lis]

rawDescription: Time complexity of casting lists to tuples in python and vice versa


code:
# Set a default value
df['Age_Group'] = '<40'
# Set Age_Group value for all row indexes which Age are greater than 40
df['Age_Group'][df['Age'] > 40] = '>40'
# Set Age_Group value for all row indexes which Age are greater than 18 and < 40
df['Age_Group'][(df['Age'] > 18) & (df['Age'] < 40)] = '>18'
# Set Age_Group value for all row indexes which Age are less than 18
df['Age_Group'][df['Age'] < 18] = '<18'

rawDescription: Pandas dataframe add a field based on multiple if statements


rawDescription: What data structure container can be sorted by date


code: from gaesessions import get_current_session

rawDescription: Session handling in Django Python with Google App Engine


rawDescription: timedelta csv pandas

description: Timedelta csv pandas


code:
import os
import subprocess

line = "perl tilt.pl %s > final.txt"

framespdb = os.listdir("prac_frames")

for frames in framespdb:
    cmd = line % frames
    print(cmd)
    subprocess.Popen(cmd, shell=True)

rawDescription: Linux Command for Perl in Python

description: Linux Command for Perl in Python


code:
class B(A): pass

A.__subclasses__()
del B
A.__subclasses__()
gc.collect(0)
gc.collect(1)
gc.collect(1)
gc.collect(2)
A.__subclasses__()

rawDescription: Is __subclasses__() cached?

description: Is __subclasses__() cached


code:
z = np.zeros((nmax+1, mmax))
for i in range(nmax+1):
    z[i] = spe.jn_zeros(i, mmax)

rawDescription: Is there a more pythonic way to write

description: Is there a more pythonic way to write


rawDescription: numpy standard deviation stacked arrays

description: Numpy standard deviation stacked arrays


code:
start = (startrow, startcol)

for i, elements in enumerate(shortlist, start[0]):
    longlist[i][start[1]:start[1] + len(elements)] = elements

rawDescription: Copying a list of lists into part of another one in the most pythonic way


code:
for i in boxes:
    if i[1].get()==0:
        #do what ever you want
        i[2].destroy()

rawDescription: Creating a window with an unknown amount of checkboxes - Python/tkinter


code:
addresses = {'google.com': '216.239.32.20',
             'msdn.microsoft.com': '157.56.148.19',
}

for domain, ip in addresses.items():
    banner, body = http_banner_grabber(ip)
    print('*' * 24)
    print(domain, ip, 'HEAD HTTP/1.1')
    print(banner)

rawDescription: Banner grabbing HTTP

description: Banner grabbing HTTP


rawDescription: Access sequence element from fasta record using Biopython Entrez


code:
class UserAdmin(admin.ModelAdmin):
    list_display = ['username', 'fullname']

    def fullname(self, model):
        return  model.first_name + " " + model.second_name

rawDescription: Django add model methods at runtime

description: Django add model methods at runtime


code: scores[rows, cols]

rawDescription: How can I find the indices in a numpy array that meet multiple conditions?

description: Find the indices in a numpy array that meet multiple conditions


rawDescription: Applying an average across groups in pandas


code:
def foo(*args): print (args)
foo(*range(10))

rawDescription: How to transfer all the elements of a list into a function which asks for *args?

description: Transfer all the elements of a list into a function which asks for *args


rawDescription: Django OR query using Extra and Filter

description: Django OR query using Extra and Filter


code:
import os

dir = os.listdir(".")

files = []

for file in dir:
    if file[-5:] == '.html':
        files.insert(0, file)

for fileName in files:
    file = open(fileName)
    content = file.read()
    file.close()

    loc = content.find('<div class="channel">')

    newContent = content[loc:]

    file = open(fileName, 'w')
    file.write(newContent)
    file.close()

rawDescription: Programmatically delete everything before a HTML node?


code:
users_followers = Table(
    'users_follower', Base.metadata,
    Column('id', Integer, primary_key=True),
    Column('from_user', ForeignKey('user.id')),
    Column('to_user', ForeignKey('user.id')),
    UniqueConstraint('from_user', 'to_user', name='UC_users_follower'),
)

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String)

    followers = relationship(
        'User',
        secondary=users_followers,
        primaryjoin=id == users_followers.c.to_user,
        secondaryjoin=id == users_followers.c.from_user,
        backref="followees",
        # cascade='all',
    )

rawDescription: SQLAlchemy - How do I SELECT x.id IS NOT NULL AS with a join?


code:
master = [i for i in second if i not in first] + first
master

rawDescription: Python compare list to list of lists to check for duplicates


code:
def take_items(person,other):
    '''
    person takes other's items.
    Note however, that although person may be altered, other remains the same --
    other does not lose its items.
    '''
    person.items.update(other.items)
    return person

rawDescription: python list of dicts how to merge key:value where values are same?

description: Python list of dicts how to merge key:value where values are same


code:
resp = [{"country": "BR", "values": {"Server1": [100.0, 100.0]}},
    {"country": "IE", "values": {"Server2": [38.2132], "Server1": [61.7868]}},
    {"country": "US", "values": {"Server2": [100.0, 100.0],
    "Server1":[100.0, 92.8571, 100.0, 100.0, 18.1078]}}]

for d in resp:
    num_severs = len(d['values'])
    for s in d['values']:
        # Calculate average pct for each server
        avg_pct = sum(d['values'][s]) / len(d['values'][s])

        # Equalize the average
        d['values'][s] = avg_pct / num_severs

rawDescription: How to normalize percentages in python

description: Normalize percentages in python


rawDescription: How to get the User object from the user_key in Flask template

description: Get the User object from the user_key in Flask template


code:
", ".join(['SUM({n}) AS {n}'.format(n=x) for x in a])
# Returns SUM(foo) AS foo, SUM(bar) AS bar, SUM(doh) AS doh, SUM(rae) AS rae

rawDescription: python string formatting: way to not use two lists?

description: Python string formatting: way to not use two lists


code:
import copy

document2.body.append(copy.copy(document1.find('div', id_='someid')))

rawDescription: clone element with beautifulsoup

description: Clone element with beautifulsoup


code:
def findMiniRow(numlst):
    x = []
    for lst in numlst:
        x.append(sum(lst))
        m = min(x)
    return [i for i, j in enumerate(x) if j == m] if numlst else -1

rawDescription: Returning empty list -1

description: Returning empty list -1


code:
icons = win32gui.ExtractIconEx('C:/Program Files/Internet Explorer/iexplore.exe', 0, 10)
info = win32gui.GetIconInfo(icons[0][0])
pixmap = QtGui.QPixmap.fromWinHBITMAP(info[4])
info[3].close()
info[4].close()
# call win32gui.DestroyIcon on all the icons returned by ExtractIconEx

rawDescription: Best way to extract .ico from .exe and paint with PyQt?

description: Extract .ico from .exe and paint with PyQt


code:
def on_tree_selection_changed(self, selection):
    model, treeiter = selection.get_selected()

    name = str(model[treeiter][0])
    liststore_suggestions = Gtk.ListStore(str)
    suggestions = correct(name)
    for item in suggestions:
        liststore_suggestions.append([item])
    self.renderer_combo.set_property("model",liststore_suggestions)

rawDescription: python-gtk cellrenderer combobox for each row

description: Python-gtk cellrenderer combobox for each row


rawDescription: Extract a value out of n

description: Extract a value out of n


code:
from itertools import groupby

res = {}
for key, gen in groupby(sorted(linesort), key=lambda x: x[0]):
    val = list(gen)
    svals = [y[2] for y in val]
    res[key] = [sum([y[1] for y in val]), sum(svals) / float(len(svals))]

rawDescription: Applying arithmetic functions to elements of sublists where the first element of each sublist is the same


rawDescription: Equal strings auto updating (List object reference)


code:
import random
random_alien = random.choice(self.aliens)
# Now do what you like

rawDescription: Pygame - Space Invaders Aliens

description: Pygame - Space Invaders Aliens


code: csum - occupations

rawDescription: Fast Numpy calculation of a slight variation of the repeat and choose functions


code:
mylist = (1,3)
df[df.customer_id.isin(mylist)]

rawDescription: pandas query rows by list

description: Pandas query rows by list


code:
from operator import and_
map(and_, a, b)

rawDescription: Python list of booleans comparison gives strange results


rawDescription: python regular expression findall, need to remove inexact matches

description: Python regular expression findall, need to remove inexact matches


code:
def paint(self, painter, option, index):
    QStyledItemDelegate.paint(self, painter, option, index)

rawDescription: PyQt: QStyledItemDelegate in QTableView on Windows Vista/7?


code:
import itertools
def field1(line):
    data = line.split()
    try:
        return data[0]
    except IndexError:
        return None

def fields(line):
    data = line.split()
    return data[0],int(data[1]),int(data[2])

with open('test.dat') as fin, open('output.dat','w') as fout:
    for k,v in itertools.groupby(fin,key=field1):
        if k is None:
            fout.write('\n')
        else:
            fout.writelines(sorted(v,key=fields))

rawDescription: Sorting data by multiple columns

description: Sorting data by multiple columns


code:
def recAlphaCount(s, counter = 0):
    if len(s):
        counter = recAlphaCount(s[1:], counter + int(s[0].isalpha()))
    return counter

rawDescription: Resetting a counter after recursion

description: Resetting a counter after recursion


code:
entity = Object.get_by_id(name)
if not entity:
    entity = Object(id=name)
    entity.put()

rawDescription: How to check the existance of single Entity? Google App Engine, Python

description: Check the existance of single Entity? Google App Engine, Python


code:
dictstr = 'dict'
dictlist = []
for ii in range(16):
    dictstrtemp = dictstr
    b = str(ii)
    dictstrtemp += b #--> "dictii" created; where ii is 1, 2, ..., 15
    dictlist.append(dictstrtemp)
    print(dictstrtemp)

print(dictlist[4])
'dict4'

rawDescription: Create several dictionaries on the fly in a for-loop and reference them outside of the loop


code: def intersect(a, b): return [x for x in a if x in b]

rawDescription: Intersecting lists in python won't work

description: Intersecting lists in python won't work


code:
import unittest
from _test_wrapper import GetValueAndClearTestStream, TestFunc, TestWrappedFunctor, MyClass

class Test(unittest.TestCase):

    def setUp(self):
        GetValueAndClearTestStream()

    def testWrapper(self):
        self.assertEqual(TestFunc(69, 1.618), 'func(a=69, b=1.618)')
        self.assertEqual(GetValueAndClearTestStream(), '- In func(a=69, b=1.618)\n')

        self.assertEqual(TestWrappedFunctor(69, 1.618), 'func(a=69, b=1.618)')
        self.assertEqual(
            GetValueAndClearTestStream(),
            (
                '[Before action...]\n'
                '- In func(a=69, b=1.618)\n'
                '[After action...]\n'
            ),
        )

def testWrappedMemberFunction(self):
    from textwrap import dedent
    x = MyClass("xx")
    y = x.WrappedCloneAndChange("yy")
    z = y.WrappedCloneAndChange("zz")

    self.assertEqual(x.GetName(), "xx")
    self.assertEqual(y.GetName(), "yy")
    self.assertEqual(z.GetName(), "zz")

    self.assertEqual(
        GetValueAndClearTestStream(),
        dedent('''\
        - In MyClass::MyClass(p_name="xx")
        [Before action...]
        - In MyClass("xx").clone_and_change(p_new_name="yy")
        - In MyClass::MyClass(p_another=MyClass("xx"))
        [After action...]
        [Before action...]
        - In MyClass("yy").clone_and_change(p_new_name="zz")
        - In MyClass::MyClass(p_another=MyClass("yy"))
        [After action...]
        - In MyClass("xx").get_name()
        - In MyClass("yy").get_name()
        - In MyClass("zz").get_name()
        '''),
    )

rawDescription: How to write a wrapper over functions and member functions that executes some code before and after the wrapped function?

description: Write a wrapper over functions and member functions that executes some code before and after the wrapped function