code:
def future8(A):
    B = [-1] * len(A)
    for index in xrange(len(A)-2, -1, -1):
        target = index + 1
        value = A[index]
        while target != -1 and A[target] < value:
            target = B[target]
        B[index] = target
    return np.array(B)

rawDescription: Numpy vectorization algorithms to find first future element greater than current element


code:
target_files = []
# please modify to follow PEP-8 yourself, compressed for clarity
if user_wants_type1(type): target_files.append("option1")
if user_wants_type2(type): target_files.append("option2")
if user_wants_type3(type): target_files.append("option3")

try:
    handles = [open(filename) for filename in taget_files]
    for handle in handles:
        handle.write("something")
finally:
    for handle in handles:
        handle.close()

rawDescription: Conditionally writing to different output files


code:
parser = argparse.ArgumentParser()
parser.add_argument('--pretty-xml', nargs='?', type=int, dest='xml_space', action=PrettyXMLAction)
parser.parse_args('--pretty-xml'.split())
parser.parse_args('--pretty-xml=5'.split())
parser.parse_args(''.split())

rawDescription: Option accepted with and without value

description: Option accepted with and without value


rawDescription: Multiple recursions in a single statement


code:
is_dup = sum(1 for l in list1 if len(set(l)) < len(l))
if is_dup > 0:
  print ("repeat found")
else:
  print ("no repeat found")

rawDescription: Finding repeated values in multiple lists


code:
#! /usr/bin/env python
# -*- coding: utf-8 -*-

import random
import timeit
import numpy

def filtered_list_comprehension(grade_list):
    return [index for index, grade in enumerate(grade_list) if grade > 0.3]

def filtered_list_comprehension_np(grade_list):
    return numpy.array([index for index, grade in enumerate(grade_list)
                        if grade > 0.3])

def filtered_numpy(grade_list):
    grade_list_np = numpy.array(grade_list)
    return numpy.where(grade_list_np > 0.3)[0]

list_elements = 10000
grade_list = [random.random() for i in range(list_elements)]

res = timeit.timeit('filtered_numpy(grade_list)',
                    number=100000,
                    setup="from __main__ import grade_list, filtered_numpy")
print("numpy.where (|L| = %i): %s" % (list_elements, str(res)))
res = timeit.timeit('filtered_list_comprehension_np(grade_list)',
                    number=100000,
                    setup="from __main__ import grade_list, filtered_list_comprehension_np")
print("list_comprehension_np (|L| = %i): %s" % (list_elements, str(res)))
res = timeit.timeit('filtered_list_comprehension(grade_list)',
                    number=100000,
                    setup="from __main__ import grade_list, filtered_list_comprehension")
print("list_comprehension (|L| = %i): %s" % (list_elements, str(res)))

rawDescription: How can I convert a list to a numpy array for filtering elements?

description: Convert a list to a numpy array for filtering elements


code:
with open('/tmp/test', 'w') as test:
    test.write('hello!')
    test.flush()
    test.truncate(0)
    test.tell()

rawDescription: If I truncate a file to zero in Python 3 do I also need to seek to position zero?


code:
from collections import Counter
c = Counter(elem[1] for elem in given_list)

rawDescription: Count occurrence of tuples with Python

description: Count occurrence of tuples with Python


code: indexed = df.set_index(["current_IP", "URI"]).sort_index()

rawDescription: is it easy to modify this python code to use pandas and would it help if i did?

description: Is it easy to modify this python code to use pandas and would it help if i did


code:
@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'],
                       request.form['password']):
            return log_the_user_in(request.form['username'])
        else:
            error = 'Invalid username/password'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    return render_template('login.html', error=error)

rawDescription: Flask Login system

description: Flask Login system


code:
import matplotlib
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4'] = 'PySide'
from matplotlib.backends.backend_qt4agg import (
    FigureCanvasQTAgg as FigureCanvas,
    NavigationToolbar2QT as NavigationToolbar)
from matplotlib.figure import Figure
from PySide import QtGui, QtCore
import random

from weakref import proxy
from ui import Ui_Form

class Plotter(FigureCanvas):
    def __init__(self, parent):
        ''' plot some random stuff '''
        self.parent = proxy(parent)
        # random data
        data = [random.random() for i in range(10)]
        fig = Figure()
        super(Plotter,self).__init__(fig)
        # create an axis
        self.axes = fig.add_subplot(111)
        # discards the old graph
        self.axes.hold(False)
        # plot data
        self.axes.plot(data, '*-')

    def binding_plotter_with_ui(self):
        self.parent.vLayout.insertWidget(1, self)

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Form = QtGui.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    # plotter logic and binding needs to be added here
    plotter = Plotter(ui)
    plotter.binding_plotter_with_ui()
    plotter2 = Plotter(ui)
    plotter2.binding_plotter_with_ui()
    Form.show()
    sys.exit(app.exec_())

rawDescription: Matplotlib in Pyside with Qt designer (PySide)


code: log_lines = open(logLocation).readlines() # read log files as a list[] of lines

rawDescription: Python Logging: Evaluate Time before adding a new entry


code:
position=[]
n, m = 2, 3
for i in range(n):
    for j in range(m):
        position.append(some_object)

# do something with the object at (i, j)
position[m*i + j].do_something() # there are m elements between (i, j) and (i+1, j)

rawDescription: Store matrix-like data in dictionaries

description: Store matrix-like data in dictionaries


code: from operator import mul

rawDescription: How to Enter an unknown number of variables into a function?


code: mylist = [sublist for sublist in oldlist if sublist[1]]

rawDescription: dealing with an empty list inside a list

description: Dealing with an empty list inside a list


code:
class ThreadingHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
    allow_reuse_address = True

rawDescription: Shutting down python TCPServer by custom handler


rawDescription: Scrapy - Limiting middle directories (Python)


code:
[[td.text for td in row.find_elements_by_tag_name("td")]
 for row in browser.find_elements_by_xpath("//tbody[@id='mrc_main_table']/tr")]

rawDescription: How can I make a list of elements Selenium?

description: Make a list of elements Selenium


code:
from datetime import datetime

datetime.strptime(key.last_modified, '%Y-%m-%dT%H:%M:%S.%fZ')

rawDescription: python convert datetime formatted string to seconds

description: Python convert datetime formatted string to seconds


rawDescription: find values of pandas columns that only has numbers

description: Find values of pandas columns that only has numbers


code:
@ndb.tasklet
def get_updates_for_user_async(userKey, lastSyncDate):
  noteQuery = ndb.gql('...')
  note_list = yield noteQuery.map_async(lambda note: note.to_dict())
  raise ndb.Return(note_list)

rawDescription: Creating an asynchronous method with Google App Engine's NDB


rawDescription: Convert a float to a two-digit hex number in Python


code:
def triplets(iterable):
    a, b, c = itertools.tee(iterable, 3)
    next(b, None)
    next(c, None)
    next(c, None)
    return itertools.izip(a, b, c)

rawDescription: How can you manipulate the iterator in a for loop in python?

description: Manipulate the iterator in a for loop in python


code: scipy.optimize.brute(lambda x:x, (slice(1,100,1),), finish=None)

rawDescription: Using scipy.optimize.brute: How I get the minimizer outside the specified range?


code:
from pyspark.sql.functions import date_format

(df
   .select(date_format(col("vacationdate"), "dd-MM-YYYY")
   .alias("date_string"))
   .show())

rawDescription: Pyspark changing type of column from date to string


code:
class Sparring():
    def __init__(self, mywins = 0, hiswins = 0):
        self.mywins = mywins
        self.hiswins = hiswins

    def my_score(self):
        self.mywins += 1

    def his_score(self):
        self.hiswins += 1

    @property
    def best (self):
        return max ( [self.mywins, self.hiswins] )

rawDescription: Using a class to keep score in python

description: Using a class to keep score in python


code:
def D(x): return 2*x
def M(x): return -x
def S(*xs): return sum(xs)

a0 = S
b0, b1 = D, S
c0, d0, d1 = S, D, S
e0, e1, e2, f0, g0, g1 = D, M, D, M, D, M

rawDescription: Composition of a hierarchy of functions

description: Composition of a hierarchy of functions


code:
with open("filename") as f:
    nsize = {el.strip(): len(el.strip()) for el in f}

rawDescription: Use text from file

description: Use text from file


code: tf.pad(tensor, paddings, mode='CONSTANT', name=None)

rawDescription: Tensorflow Tensor reshape and pad with zeros


code:
book_message_adaptor = ObjectAdaptor(Book, kwargs={
    'isbn': Pick('isbn_number', TypeWrapper(ISBNNumber)),
    'authors': Pick('authorlist', ListAdaptor(TypeWrapper(Author)))
})

rawDescription: What is the pythonic way to add type information to an object's attributes?


code:
q1 = Q(field1=field1_val1, field2=field2_val1)
q2 = Q(filed1=field1_val2, field2=field2_val2)
#...etc

rawDescription: Performance impact of or-ing Q objects in django query


code:
t1.start()
t2.start()

rawDescription: my python3 threading prog didnt work with fifo-queue

description: My python3 threading prog didnt work with fifo-queue


rawDescription: Use of multiple regular parentheses to parse bbcode


code:
people = []

for line in self.data:
    people.append({
        "Number": line[0:9],
        "FullName": line[9:27].rstrip(),
        "LastName": line[27:63].rstrip(),
        "Area": line[63:65].rstrip(),
        "City": line[65:90].rstrip(),
        "Status": line[91],
        "Status2": line[92],
        "Status3": line[93]
    })

return people

rawDescription: parsing a line into a dictionary through a list comprehension

description: Parsing a line into a dictionary through a list comprehension


code:
while True:
    print("\n1. Surname\n2. D.O.B\n3. Quit")
    try:
        select = int(input("Please select an option: "))
    except ValueError:
        print("Not a valid input")
    else:
        if select == 1:
            surnameSearch()
        elif select == 2:
            DOB_search(BkRdr)
        elif select == 3:
            break
        else:
            print("That was an incorrect option, please try again:")

rawDescription: Breaking out of infinite loop

description: Breaking out of infinite loop


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

# plot f(x)=x for two different x ranges
x1 = np.linspace(0, 1, 50)
x2 = np.linspace(0, 2, 50)
fig = plt.figure()

ax1 = fig.add_subplot(111)
ax1.plot(x1, x1,'b--')

ax2 = ax1.twiny()
ax2.plot(x2, x2, 'go')

plt.show()

rawDescription: Matplotlib: one line, plotted against two related x axes in different units?


rawDescription: How to append a value to a not yet existing key?

description: Append a value to a not yet existing key


code:
class Cheese(object):
    def __init__(self, id):
        self.id = id

    def __eq__(self, other):
        if isinstance(other, Cheese):
            return self.id == other.id
        return NotImplemented

rawDescription: Searching for index of object in a list

description: Searching for index of object in a list


code:
import gzip
gz = gzip.open(filename + '.gz', 'wb')
gz.write(pickle.dumps(obj, pickle.HIGHEST_PROTOCOL))
gz.close()

rawDescription: Why does saving/loading data in python take a lot more space/time than matlab?


code: reduce(operator.getitem, c[:-1], b).insert(c[-1], "new")

rawDescription: Append to a list using indexes stored in another list


code:
Movie(title=u"Blade Runner", year=1982)
session.commit()

rawDescription: How to retrieve executed SQL code from SQLAlchemy

description: Retrieve executed SQL code from SQLAlchemy


code:
header = "location\ttemperature\tweather\date\n"
f.write(header)
for i in xrange(len(weather)):
    f.write('\t'.join([locations[i],temp_f[i],weather[i],str(now.day)]))
    f.write('\n')
f.close()

rawDescription: print with row for CSV in python respecting column(header) and row

description: Print with row for CSV in python respecting column(header) and row


code:
# initialize pygame and screen
import pygame
pygame.init()
screen = pygame.display.set_mode((720, 576))

# Draw the image to the screen
screen.blit(image, (0, 0))

# Draw a line on top of the image on the screen
pygame.draw.line(screen, (255, 255, 255), (0, 0), (50, 50))

rawDescription: how to draw lines on a picture background in pygame

description: Draw lines on a picture background in pygame


code:
import sys
sys.getsizeof(10 ** 10 ** 6)
sys.getsizeof(10 ** 10 ** 7)

rawDescription: n**n**n heuristics in Python

description: N**n**n heuristics in Python


code:
previews = {}

table = soup.select('table.fixture')[0]
for group_header in table.select('tbody tr th'):
    date = group_header.string
    for next_sibling in group_header.parent.find_next_siblings('tr'):
        if next_sibling.th:
            # found a next group, end scan
            break
        for preview in next_sibling.select('a.preview'):
            previews.setdefault(date, []).append(
                "http://www.afl.com.au" + preview.get('href'))

rawDescription: Extracting data from a web page using BS4 in Python


code:
raw = """\
%%
Type: language
Subtag: aa
Description: Afar
Added: 2005-10-16
%%
Type: language
Subtag: ab
Description: Abkhazian
Added: 2005-10-16
Suppress-Script: Cyrl
%%
Type: language
Subtag: ae
Description: Avestan
Added: 2005-10-16
%%"""

data = [
     dict(
         row.split(': ')
         for row in item_str.split("\n")
         if row  # required to avoid the empty lines which contained '%%'
     )
     for item_str in raw.split("%%")
     if item_str  # required to avoid the empty items at the start and end
]

rawDescription: Cascaded string split, pythonic way

description: Cascaded string split, pythonic way


code:
import numpy as np
dat = [['User1', 'Male', '2.2'], ['User2', 'Female', '3.777'], ['User3', 'Unknown', '0.0']]

# create data types: two strings of length 10 and float
dt = np.dtype('a10, a10, float')

# convert the inner lists to tuples so that a structured array can be used
for ind, l in enumerate(dat):
    dat[ind] = tuple(l)

# convert dat to an array
my_arr = np.array(dat, dt)

rawDescription: Make single column of numpy array another datatype


rawDescription: Converting string to normal text

description: Converting string to normal text


code: resized_image = cv2.resize(image, (100,100))

rawDescription: Is is possible to run knnMatch for different images on different threads?


code:
class Profile(models.Model):
    user = models.OneToOneField(User)
    contact = models.CharField(maX_length = 50)
    # User class contain other fields that you need.

rawDescription: Authentication is not working for custom authentication


rawDescription: append columns of a data frame to a different data frame in pandas

description: Append columns of a data frame to a different data frame in pandas


code:
def create(self, name , *parameters, page=5, opt1=False,
                                  opt2=False,opt3=False,
                                  opt4=False,opt5=False,
                                  opt6=False):
    print(parameters)
    print(page)
    print(opt4)

In [31]: create('C', 'some name', 1, 2, 3, opt4 = True)
(1, 2, 3)
5
True

rawDescription: How to call python function with optional parameters

description: Call python function with optional parameters


code:
class Predicate:
    def __init__(self, predicate, view):
        self.predicate = predicate
        self.view = view

# Creation of the predicates :
all_color = Predicate(lambda fruit: True, 'All colors')
red_color = Predicate(lambda fruit: fruit[2] == 'red')
# ...

# Then you have to generate your select form. I don't remember exactly the PyQt4 doc but it's not the harder part.

predicates = getAllSelected() # I guess you know how to get this kind of function

myfruits = {}
my_filtered_fruits = myfruits.items()
for pred in predicates:
    my_filtered_fruit = filter(lambda x: pred(x[1]), my_filtered_fruit)
my_filtered_fruit = list(my_filtered_fruit)

rawDescription: How to implement efficient filtering logic in Python?

description: Implement efficient filtering logic in Python


rawDescription: From list of dictionaries to np array of arrays and vice-versa


code:
if len(line) <= int(maxLength):
    for l, c in counter.items():
        if line.count(l) < c:
            break
    else:
        listOfWords.append(line)

rawDescription: Compare two strings, including duplicate letters?


code: os.sched_setaffinity(0, {0}) # current process on 0-th core

rawDescription: On what CPU cores are my Python processes running?


rawDescription: Reading Text File From Webpage by Python3


code:
for v in get_sums(pop, s, n):
    yield v

rawDescription: How do I iterate over a large number of tuples of integers in the order of their sum?

description: Iterate over a large number of tuples of integers in the order of their sum


code:
parameter = first | last | dob | hobbies | is_minor
my_data = person_start + delimitedList(parameter) + person_end

rawDescription: PyParsing a string representing a function


code:
ends
p = pd.PeriodIndex(freq='m', start='2000-1', periods=19)  # Note: needs to be one more than before
sparse_ends = ends.reindex(p)
sparse_ends.shift(1)

rawDescription: Pandas, simple add one month to a datetime column in a dataframe


code:
lessons = [
    [category1, category2, ...],
    [category10, category11, ...]
]

rawDescription: Python in HTML: Iterating over several lists by changing the name of a variable


code:
import numpy as np

arr = np.array([[3, 0, 3],
                [6, 7, 2],
                [2, 5, 0],
                [2, 1, 4]])

masked = np.ma.masked_array(arr, mask=False)
masked.mask[::2, None] = True

extracted = np.ma.compress_rows(masked)

analyzed = extracted*10

masked[~masked.mask] = analyzed.ravel()

print(masked)

rawDescription: Python, looking to extract values from a masked array, then rebuild an array


code: host = self.address_string()

rawDescription: Django 1.4.18 dev server slow to respond under VirtualBox


rawDescription: Pandas count(distinct) equivalent

description: Pandas count(distinct) equivalent


code:
tuples = [('a', '1'), ('b', '1'), ('c', '2'), ('d', '3')]
result = {}
for value, key in tuples:
    result.setdefault(key, []).append(value)

result

rawDescription: Python dictionary key assign

description: Python dictionary key assign


code:
term = u"réception".encode("utf-8")
M.literal = term
M.search("utf-8", "SUBJECT")

rawDescription: Python IMAP search using a subject encoded with iso-8859-1


code:
class waypointForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ChoiceField(
            choices=[(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
        )

rawDescription: Creating a dynamic choice field

description: Creating a dynamic choice field


code:
# You do some work...
offset = compute_overlap_offset()

rawDescription: deleting rows in linux

description: Deleting rows in linux


code:
idx = ['{0}_{1}'.format(conds[i], conds[j])
        for i in range(len(conds))
        for j in range(i + 1, len(conds))]

rawDescription: Improvement in pandas dataframe conversion in Python


rawDescription: How to filter the string patterns to match in textlines with regex?

description: Filter the string patterns to match in textlines with regex


code:
import my_package.my_very_long_module_name as foo
f1, f2, f3 = foo.f1, foo.f2, foo.f3
del foo

rawDescription: Importing names from an aliased module. Is it possible?


code: (total,success,failed) = reduce (lambda x,y:(x[0]+y[0],x[1]+y[1],x[2]+y[2]), [(project.projectTotal,project.projectSuccess,project.projectFailed) for project in dict.values()])

rawDescription: Organizing python code for handling statistic information


code:
somelist = ['a','b','b','c']
somefloat = -0.64524
sometuple = (235,633,4245,524)
output = str(somelist) + "|" + str(somefloat) + "|" + str(sometuple)

rawDescription: Output and Import list of lists to Pandas DataFrame


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

n = 100
dates = pd.date_range(start = "2015-01-01", periods = n, name = "yearDate")

dfs = []

for i in range(3):
    df = pd.DataFrame(data = np.random.random(n)*(i + 1), index = dates,
                      columns = ["DataFrame #" + str(i) ] )
    df.df_name = str(i)
    dfs.append(df)

df = pd.concat(dfs, axis = 1)
df.plot()

rawDescription: Date removed from x axis on overlaid plots matplotlib


rawDescription: Python: wrapping log file text in logging module


code:
y_key = None
for d, p in zip(temp_list, temp_search_list):
    temp2[d].add(p)
    if p == 'Y':
        y_key = d

rawDescription: python: how to compare more than two keys in the same dictionary?

description: Python: how to compare more than two keys in the same dictionary


rawDescription: How to apply functools.lru_cache to function with mutable parameters?

description: Apply functools.lru_cache to function with mutable parameters


code:
for j, l in zip(vara, varb):
    print(j[0], j[1], l)

rawDescription: Simultaneous Loops in Python

description: Simultaneous Loops in Python


code:
import pandas as pd
import numpy as np
df = pd.concat([df, df.Genres.str.get_dummies(sep='|')], axis=1)
df = df.groupby("Customers").aggregate(np.sum)

print(df)

rawDescription: finding dataframe group count

description: Finding dataframe group count


code:
group = {}
for i in range(array.shape[1]):
    tup = tuple(array[:,i])
    if tup in group.keys():
        group[tup].append(i)
    else:
        group[tup] = [i]

rawDescription: Finding the sets of columns/rows that overlap


code: lis = re.findall(r'[-+*/()]+|\d+', string)

rawDescription: Python re.findall with * and **

description: Python re.findall with * and **


code:
data = [(u'Tiger', (u'PRO-16', u'Passed')),
 (u'Tiger', (u'PRO-16', u'Failed')),
 (u'Tiger', (u'PRO-17', u'Failed')),
 (u'Tiger', (u'PRO-17', u'Passed')),
 (u'Monkey', (u'PRO-18', u'Passed')),
 (u'Monkey', (u'PRO-18', u'Failed')),
 (u'Monkey', (u'PRO-19', u'Passed')),
 (u'Monkey', (u'PRO-20', u'Failed')),
 (u'Elephant', (u'PRO-21', u'No Run')),
 (u'Elephant', (u'GR-01', u'Passed'))]

succeeded = set()
failed = set()
for item in data:
    if item[1][1] != 'Failed':
        succeeded.add((item[0], item[1][0]))
    else:
        failed.add((item[0], item[1][0]))

rawDescription: Python: iterate over a list of list

description: Python: iterate over a list of list


code: thelist[:] = [d for d in thelist if d.get('id') != 2]

rawDescription: Python: remove dictionary from list

description: Python: remove dictionary from list


rawDescription: Getting empty list while parsing

description: Getting empty list while parsing


code:
from pyspark.mllib.regression import LabeledPoint
from pyspark.sql.functions import col

(transformed.select(col("outcome_column").alias("label"), col("features"))
  .map(lambda row: LabeledPoint(row.label, row.features)))

rawDescription: Create labeledPoints from Spark DataFrame in Python


rawDescription: How to convert pandas single column data frame to series or numpy vector

description: Convert pandas single column data frame to series or numpy vector


code:
from collections import defaultdict
d = defaultdict(int)

for k in list:
    d[k] += 2

rawDescription: python dict add and modify operation

description: Python dict add and modify operation


code:
['cost', 'name']
['cost', 'name']

rawDescription: Get all keys from a list of dictionaries


rawDescription: referencing list object by data python

description: Referencing list object by data python


code:
def set_availability(self):

    start_delay = self.start_time + (self.start_date - self.run.start_date).total_seconds()/3600 # this returns the time in hours until the resource becomes available and is applied below.
    end_delay = self.end_time + (self.start_date - self.run.start_date).total_seconds()/3600
    repeat = (self.end_date - self.start_date).days + 1  # defines how man days to repeat it for

    for i in range(repeat):

        start_delayed(self.run.env, self.add_to_store(), start_delay)
        start_delayed(self.run.env, self.remove_from_store(), end_delay)
        start_delay += 24
        end_delay += 24

    yield self.run.env.timeout(0)

def add_to_store(self):

    self.run.ad_avail.remove(self)  # take adviser from a list
    self.run.adviser_store.put(self)  # and put it in the store
    yield self.run.env.timeout(0)

def remove_from_store(self):

    current_ad = yield self.run.adviser_store.get(lambda item: item.id_num == self.id_num)  # get itself from the store
    self.run.ad_avail.append(current_ad) # and put it back in the list
    yield self.run.env.timeout(0)

rawDescription: simpy resource availability schedule

description: Simpy resource availability schedule


code:
from itertools import groupby
for key, group in groupby([123, 127, 99, 75, 86, 83, 81], lambda x: int(x / 10)):
    print(key, list(group))

rawDescription: Given a list of numbers, find a fix range that can cover the most numbers


code:
from my_flask_project import db, create_app
create_app().app_context().push()
db.session.query(...)

rawDescription: Share sqlalchemy models between flask and other apps


rawDescription: Function called when using binary operators, python


code:
import requests
from bs4 import BeautifulSoup

js = "https://angel.co/company_filters/search_data"

headers = {"X-Requested-With": "XMLHttpRequest",
           "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36"}

u = "https://angel.co/companies/startups?ids%5B%5D={}&total={}&page={}&sort=signal&new=false&hexdigest={}"
with requests.Session() as s:
    params = s.post(js, data={"sort": "signal"}, headers=headers).json()
    companies = s.get(u.format("&ids%5B%5D=".join(map(str, params["ids"])),params["page"] ,params["total"], params["hexdigest"]), headers=headers)
    soup = BeautifulSoup(companies.json()["html"])

rawDescription: unable to scrape

description: Unable to scrape


code:
def add_foo(request):
    if request.method == "POST": # Check if the form is submitted
        foo = Foo() # instantiate a new object Foo, don't forget you need to import it first
        foo.name = request.POST['name']
        foo.gender = request.POST['gender']
        foo.save() # You need to save the object, for it to be stored in the database
        #Now you can redirect to another page
        return HttpResponseRedirect('/success/')
    else: #The form wasn't submitted, show the template above
        return render(request, 'path/to/template.html')

rawDescription: Passing objects from template to view using Django


code:
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    author = models.ForeignKey(Author)
    title = models.CharField(max_length=100)

rawDescription: How can I have the equivalent of django's admin inlines in a modelform?

description: Have the equivalent of django's admin inlines in a modelform


code:
from string import punctuation

s = ["Johnny and Annie.", "She and I."]

print([" ".join(filter(str.istitle,x.translate(None,punctuation).split(" "))) for x in s])
['Johnny Annie', 'She I']

rawDescription: Python how to delete lowercase words from a string that is in a list


rawDescription: How to set the screen resolution in pythoncard

description: Set the screen resolution in pythoncard


code: {'email': True, 'login': True, 'id': True, 'name': False}

rawDescription: SQLAlchemy Determine If Unique Constraint Exists


rawDescription: Clicking links by regexp in python selenium


rawDescription: How do I sort a text file in python?

description: Sort a text file in python


rawDescription: print edited list without actually editing the list

description: Print edited list without actually editing the list


code: df = pd.DataFrame(range(50), columns=list('B'))

rawDescription: Pandas replace issue

description: Pandas replace issue


code:
data = {
    'boxes': [[x1, y1], [x2, y2]],
    'height': [h1, h2],
    'general_parameter': [par1, par2]
}

rawDescription: Recommended way to represent my data with numpy


code:
def set_scroll_state(self, scroll_state):
    sceneWidthPercent, sceneHeightPercent = scroll_state
    x = (sceneWidthPercent * self.sceneRect().width() +
         self.sceneRect().left())
    y = (sceneHeightPercent * self.sceneRect().height() +
         self.sceneRect().top())
    self.centerOn(x, y)

rawDescription: Maintaining view/scroll position in QGraphicsView when swapping images


code:
if num in range(100, 200):
    print ("Your number is in range")

rawDescription: Range in Python 3x

description: Range in Python 3x


rawDescription: python regex: replacing <number>st, <number>nd, <number>th etc in a adress with a single sub

description: Python regex: replacing <number>st, <number>nd, <number>th etc in a adress with a single sub


code:
# this
tracks = Songplays.objects.using('prod').values().filter(user=id, when__gt=start, when__lt=end).order_by('-when')

#instead of this
tracks = Songplays.objects.using('prod').all().filter(user=id, when__gt=start, when__lt=end).order_by('-when')

rawDescription: Serializing attributes that are not model fields with Django JSON serializer


code:
class SettingManager(models.Manager):

    def get(self, *args, **kwargs):
        from modules.customer.proxies import *
        from modules.customer.models import *

        object = type('DomainSettings', (SettingProxy,), {'__module__' : 'modules.customer'})()
        for pair in self.filter(*args, **kwargs): setattr(object, pair.name, pair.value)

        setattr(object, 'domain', Domain.objects.get(id=int(kwargs['domain__exact'])))
        return object

rawDescription: Store form fields as key-values / individual rows


code:
class Test:

    def test_some_function(self, monkeypatch):
        monkeypatch.setattr(time, 'sleep', lambda s: None)
        data = some_sleepy_function()
        assert data == expected_data

rawDescription: mocking sleep in a test

description: Mocking sleep in a test


code:
# first, let's make a test dictionary
from string import ascii_lowercase
d = {k: i for i, k in enumerate(ascii_lowercase[:10])}
d
d['d']

rawDescription: How to minus one on multiple variable? python

description: Minus one on multiple variable? python


code: [urljoin(response.url, url) for url in url_list]

rawDescription: How to use map with urljoin?

description: Use map with urljoin


code:
def make_dict(seq):
    dic =  {}
    for i, lis in enumerate(seq):
        indices = {}
        for j, item in enumerate(lis):
            indices.setdefault(item, [i]).append(j)
        for k, v in indices.items():
            dic.setdefault(k, []).append(v)
    return dic

lis = [['d', 'e', 'f','d'], ['d', 'g','f']]

rawDescription: Build dictionary from list of lists and maintain position of elements


code:
import xml.etree.ElementTree as ET

def process_stream(self, stream, heading=None):
        if self.verbosity >= 2 and heading is not None:
            fprintf(self.logfile, "\n=== %s ===\n", heading)
        self.tree = ET.parse(stream)

rawDescription: How to prevent "billion laughs" DoS attack in Python's xlrd?

description: Prevent "billion laughs" DoS attack in Python's xlrd


code:
with open(filename) as f:
    next(f)  #drop the first line
    #now do something with rest of the lines

rawDescription: Understanding builtin next() function

description: Understanding builtin next() function


code:
import regex
if regex.search("(?<!right |left )shoulder", "left shoulder"):
    print("It matches!")
else:
    print("Nah... No match.")

rawDescription: Variable-Width Lookbehind Issue in Python


code:
import numpy as np
from pylab import *
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

def randrange(n, vmin, vmax):
    return (vmax-vmin)*np.random.rand(n) + vmin

fig = plt.figure(figsize=(8,6))

ax = fig.add_subplot(111,projection='3d')
n = 100

xs = randrange(n, 0, 100)
ys = randrange(n, 0, 100)
zs = randrange(n, 0, 100)
the_fourth_dimension = randrange(n,0,100)

colors = cm.hsv(the_fourth_dimension/max(the_fourth_dimension))

colmap = cm.ScalarMappable(cmap=cm.hsv)
colmap.set_array(the_fourth_dimension)

yg = ax.scatter(xs, ys, zs, c=colors, marker='o')
cb = fig.colorbar(colmap)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

rawDescription: How to plot heatmap colors in 3D in Matplotlib

description: Plot heatmap colors in 3D in Matplotlib


code:
class RemovableTask(Frame):
    def __init__(self, master, name, **options):
        Frame.__init__(self, master, **options)
        lbl = Label(self, text=name)
        btn = Button(self, text='Remove step', command=self.destroy)
        lbl.grid(row=0, column=0)
        btn.grid(row=0, column=1)

rawDescription: Tkinter: How can I dynamically create a widget that can then be destroyed or removed?


code:
a=slice(None, None, None)
a.indices(1)
a.indices(10)
a=slice(None, -5, None)
a.indices(100)

rawDescription: turn slice into range in python

description: Turn slice into range in python


code:
class SuperClass:
    __metaclass__ = Watcher

rawDescription: Python: Run code when a class is subclassed


code:
u_operators = []
non_u_operators = []

class Operator:
    def __init__(self, precedence, group):
        self.precedence = precedence
        group.append(self)

PLUS = Operator(0, non_u_operators)
UPLUS = Operator(10, u_operators)
MIN = Operator(0, non_u_operators)
UMIN = Operator(10, u_operators)
MULT = Operator(20, non_u_operators)

# Freeze the collections of Operators
non_u_operators = tuple(non_u_operators)
u_operators = tuple(u_operators)

rawDescription: Python: Grouping objects together

description: Python: Grouping objects together


code:
@expected_failure
def test_not_implemented():
    assert False

@expected_failure
def test_unexpected_success():
    assert True

rawDescription: nose plugin for expected-failures

description: Nose plugin for expected-failures


code:
myarray.min()
myarray.max()
np.nanmin(myarray)
np.nanmax(myarray)

rawDescription: zero values to nan values in an array of Python

description: Zero values to nan values in an array of Python


code:
counts = (df.groupby(['Protein'])['Peptide']
            .apply(lambda x: x.value_counts().nlargest(2)))
counts = counts[counts >= 2]
counts = counts.to_frame()
#                  counts
# Protein Peptide
# A1      AAB           2
#         ABB           2
# A2      ABB           2
#         ABC           2

rawDescription: Grouping and filtering data

description: Grouping and filtering data


code:
mydict={}
mydict.update({}.fromkeys(['1','2','3'],8.5))
mydict
mydict.update({}.fromkeys(['4', '5', '6'],13.5))
mydict

rawDescription: Assigning int values to each dictionary entry as well as having reference numbers?


code:
class Poll(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published', default=timezone.now)

rawDescription: Combining two forms in one Django view

description: Combining two forms in one Django view


code:
def zahlen(schein, function, *arguments):
    if len(schein) < 6:
        schein.append(function(*arguments))
        return zahlen(schein, function, *arguments)
    return schein

from random import randint
zahlen([], randint, 1, 49)
zahlen([], lambda: int(input('Please enter a number: ')))

rawDescription: recursive number generator not working

description: Recursive number generator not working


rawDescription: Import binary data using a different scanning direction


code:
localdt = local_tz.localize(datetime.datetime(year, month, day, hour, min))
localdt.astimezone(pytz.UTC)

rawDescription: Python pytz: convert local time to utc. Localize doesn't seem to convert


code:
link = linker.select('@href').extract()[0]
item ["link"] = re.search("\'(?P<url>https?://[^\s]+)\'", link).group("url")

rawDescription: scrapy scraped data contains javascript

description: Scrapy scraped data contains javascript


code:
inst2.__dict__
inst.__dict__

rawDescription: Questions about details of @property in Python


code:
def find_values(ticker, event_time):
    filename = ticker+'.csv'
    df = pd.read_csv(filename, parse_dates=[0])
    idx = df['Timestamp'].searchsorted(event_time, side='right')
    price_1, price_2 = df['Price'].iloc[idx-1:idx+1]
    df_later = df.iloc[idx:]
    return price_1, price_2, df_later

rawDescription: possible speed up of pandas apply

description: Possible speed up of pandas apply


code:
import mock

class AnyStringWith(str):
    def __eq__(self, other):
        return self in other

...
result = database.Query('complicated sql with an id: %s' % id)
database.Query.assert_called_once_with(AnyStringWith(id))
...

rawDescription: unittest.mock: asserting partial match for method argument

description: Unittest.mock: asserting partial match for method argument


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

class Slot(models.Model):
    #e.g. main_hand, off_hand, head, ... , feet
    name = models.CharField(max_length=255)

    def __unicode__(self):
        return self.name

class Item(models.Model):
    '''Details individual data for each item on a loot table'''
    name = models.CharField(max_length=255, null=True)
    item_id = models.IntegerField(null=True)
    """removed for the example"""
    #dropped_by = models.ForeignKey(Boss)
    warforgeable = models.BooleanField(default=True)
    bonus_string = models.CharField(max_length=255, blank=True, null=False, default='')

    def __unicode__(self):
        return self.name

class PlayerManager(models.Manager):
    def create_player_with_empty_slots(self, **kwargs):
        player = Player.objects.create(**kwargs)
        PlayerSlot.objects.bulk_create([
            PlayerSlot(player=player, slot=slot) for slot in Slot.objects.all()
        ])
        return player

class Player(models.Model):
    user = models.OneToOneField(User, null=True, blank=True)
    """removed for the example"""
    #accountID = models.CharField(max_length=255, null=True, blank=True)
    #battletag = models.CharField(max_length=255, null=True, blank=True)
    #main_character = models.ForeignKey('Character', null=True, blank=True, related_name='main_character')
    #signature = models.TextField(null=True, blank=True)

    slots = models.ManyToManyField(Slot, through='PlayerSlot')
    items = models.ManyToManyField(Item, through='PlayerSlot')

    objects = PlayerManager()

    def __unicode__(self):
        """changed for the example"""
        return self.user.username

    def get_slot(self, slot_or_slotname):
        if isinstance(slot_or_slotname, Slot):
            return self.playerslot_set.get(slot=slot_or_slotname)
        else:
            return self.playerslot_set.get(slot__name=slot_or_slotname)

    def set_item(self, item, at_slot):
        slot = self.get_slot(at_slot)
        slot.item = item
        slot.save()

class PlayerSlot(models.Model):
    player = models.ForeignKey(Player)
    slot = models.ForeignKey(Slot)
    #item is optional, to allow empty slots
    item = models.ForeignKey(Item, null=True, blank=True)
    locked = models.BooleanField(default=False)

    class Meta:
        unique_together = ('player', 'slot')

    def __unicode__(self):
        return "{player} carry {item} on {slot}".format(player=self.player, item=self.item or 'nothing', slot=self.slot)

rawDescription: Efficient reverse of queryset

description: Efficient reverse of queryset


code:
import pandas as pd
import datetime as DT

output_summary = [['X1', '01/01/2015', '01/01/2016', 100],
                  ['X2', '03/05/2015', '06/07/2015', 200],
                  ['X1', '01/08/2015', '25/09/2015', 50],
                  ['X300', '06/06/2015', '05/07/2016', 150]]

def alt(output_summary):
    data = {}
    for col, start_date, end_date, value in output_summary:
        dr = pd.date_range(start_date, end_date, freq='D')
        series = pd.Series(value, index=dr)
        data[col] = data.setdefault(col, pd.Series()).add(series, fill_value=0)
    result = pd.DataFrame(data)

    start_date = DT.date(2012,1,1)
    end_date = DT.date(2018,1,1)
    dr = pd.date_range(start_date, end_date, freq='D')
    result = result.reindex(dr)
    result = result.fillna(0)
    return result

def orig(output_summary):
    start_date = DT.date(2012,1,1)
    end_date = DT.date(2018,1,1)
    dr = pd.date_range(start_date, end_date, freq=pd.datetools.day)
    C = sorted(set([row[0] for row in output_summary]))
    empty_df = pd.DataFrame(index = dr, columns=C)
    empty_df.fillna(0, inplace=True)

    for row in output_summary:
        dr = pd.date_range(
            pd.Timestamp(row[1]).date(),
            pd.Timestamp(row[2]).date(),
            freq=pd.datetools.day)
        dr = pd.TimeSeries(row[3], index=dr)
        df = pd.DataFrame(data=dr)
        df.columns=[row[0]]
        empty_df = empty_df.add(df, fill_value=0, axis=0)
    return empty_df

rawDescription: Python Pandas, translating start-end events into single consolidated Dataframe


rawDescription: Renaming multiple files in python

description: Renaming multiple files in python


code:
new = df.groupby(pd.TimeGrouper('5Min'),as_index=False).apply(lambda x: x['val'])
df['period'] = new.index.get_level_values(0)
df

rawDescription: how to create a group ID based on 5 minutes interval in pandas timeseries?

description: Create a group ID based on 5 minutes interval in pandas timeseries


code:
def insertInHtml(string, insstr, position):
    ctr=0
    insidetag=False
    insideattr=False
    for ci in range(len(string)):
        suchar=''
        if not ci==len(string)-1: suchar=string[ci+1]
        if string[ci]=='<' and not insideattr:
            insidetag=True
        elif (string[ci]=='>' and not insideattr) or (string[ci]=='-' and string[ci-2:ci]=='!-'):
            insidetag=False
        elif insidetag and string[ci]+suchar=='="':
            insideattr=True
        elif insideattr and string[ci]=='"':
            insideattr=False
        else:
            if not insidetag: ctr+=1
        if ctr==position+1:
            HTMLIndex=ci
            break
    return string[0:HTMLIndex] + insstr + string[HTMLIndex:]

rawDescription: Calculate a text-position inside a div element into the according position in HTML with Python


code:
#...
with self.lock:
    existing = self.processes.setdefault(pid, new_proc)
#...
with self.lock:
    existing.update(user_avg=user_avg, sys_avg=sys_avg, **new_proc)
#...

def get_curr_processes(self):
    with self.lock:
        return [self.processes[pid] for pid in psutil.get_pid_list()
                if pid in self.processes]

rawDescription: Run a script with web server and maintain data to be used later


code:
g.get_group(1)
[x for _, x in g]

rawDescription: Splitting dataframe and saving to txt files


code:
import pandas as pd
pandas_df = pd.read_csv('data/accounts.0.csv')
len(pandas_df)
pandas_df.groupby('names').sum()

rawDescription: Do aggregations and statistics on a very large Pandas Data frame


code:
import collections as co
import abc

class ImmutableMeta(abc.ABCMeta):

    _classes = {}

    def __new__(meta, clsname, bases, clsdict):
        attributes = clsdict.pop('_attributes_')

        if bases[0] is object:
            # 'new' class
            methods = clsdict
        else:
            # we're 'inheriting' from an existing class
            base = bases[0]
            attributes = meta._classes[base]['attributes'] + ' ' + attributes
            base_methods = meta._classes[base]['methods'].copy()
            base_methods.update(clsdict)
            methods = base_methods

        # construct the actual base class and create the return class
        new_base = co.namedtuple(clsname + 'Base', attributes)
        cls = super(ImmutableMeta, meta).__new__(meta, clsname, (new_base,),
                                                 methods)

        # register the data necessary to 'inherit' from the class
        # and make sure that it passes typechecking
        meta._classes[cls] = {'attributes': attributes,
                              'methods': methods}
        if bases[0] is not object:
            base.register(cls)
        return cls

rawDescription: Immutable types allowing subclassing in Python


code: ['simple', 'basic']

rawDescription: Python regexes: return a list of words containing a given substring


rawDescription: Passing arguments to fsolve

description: Passing arguments to fsolve


code:
import threading
wlock=threading.Lock()
printqueue=[]
rinput=False
def winput(text):
    with wlock:
        global printqueue,rinput
        rinput=True
        text = raw_input(text)
        rinput=False
        for text in printqueue:
            print(text)
        printqueue=[]
        return text
def wprint(obj):
    global printqueue
    if not(rinput):
        print(str(obj))
    else:
        printqueue.append(str(obj))

rawDescription: Terminating raw_input() if other text displays


code:
background = pygame.image.load("leaves.png").convert_alpha()
mask = pygame.image.load("mask-fuzzy.png").convert_alpha()

rawDescription: Pygame - is there any way to only blit or update in a mask


code:
import numpy as np
with open('spam.txt', 'r') as file:
    ncols = len(file.readline().split(',')) - 1
    data = np.fromiter((int(v) for line in file for v in line.split(',')[:-1]), int, count=-1)
    cols = data.reshape(data.size / ncols, ncols).transpose()
cols

rawDescription: reading a text file columnwise and storing in a list in python

description: Reading a text file columnwise and storing in a list in python


code: hash -r  # will erase the currently used hash table

rawDescription: Python: cannot import urandom module (OS X)


rawDescription: Consequences of abusing nltk's word_tokenize(sent)


code:
def accum(initial_value,a):
    value = initial_value
    yield value
    for x in a:
        value += x
        yield value

def integral_hybrid(integrand,initial_value,dt):
    for x in accum(initial_value,scale_stream(integrand,dt)):
        yield x

rawDescription: SICP "streams as signals" in Python

description: SICP "streams as signals" in Python


rawDescription: RIGHT() function in sqlalchemy

description: RIGHT() function in sqlalchemy


code:
from django.conf import settings
from django.contrib.sessions.backends.db import SessionStore as DBStore
from django.core.cache import get_cache

class SessionStore(DBStore):
    """
    Implements cached, database backed sessions.  Now with control over the cache!
    """

    def __init__(self, session_key=None):
        super(SessionStore, self).__init__(session_key)
        self.cache = get_cache(getattr(settings, 'SESSION_CACHE_ALIAS', 'default'))

    def load(self):
        data = self.cache.get(self.session_key, None)
        if data is None:
            data = super(SessionStore, self).load()
            self.cache.set(self.session_key, data, settings.SESSION_COOKIE_AGE)
        return data

    def exists(self, session_key):
        return super(SessionStore, self).exists(session_key)

    def save(self, must_create=False):
        super(SessionStore, self).save(must_create)
        self.cache.set(self.session_key, self._session, settings.SESSION_COOKIE_AGE)

    def delete(self, session_key=None):
        super(SessionStore, self).delete(session_key)
        self.cache.delete(session_key or self.session_key)

    def flush(self):
        """
        Removes the current session data from the database and regenerates the
        key.
        """
        self.clear()
        self.delete(self.session_key)
        self.create()

rawDescription: Django Multiple Caches - How to choose which cache the session goes in?


rawDescription: the .set() method is not in the xml.etree library for Python?

description: The .set() method is not in the xml.etree library for Python


code:
x,y = bezier(np.arange(0,1,0.01))
plot(x,y)

rawDescription: python program bezier function

description: Python program bezier function


code:
from pandas import *
L1 = [1,2,3]
L2 = [2,2,3]
S1 = Series(L1)
S2 = Series(L2)
RES = S1==S2
RES

rawDescription: How do you compare integer values in two separate lists?

description: Compare integer values in two separate lists


code:
def myFunc(x, y):
    for i in range(*sorted((x, y))):
        ...

rawDescription: Best way to find max and min of two values

description: Find max and min of two values


code:
import random

val = int(input('How many numbers?: '))
#random number is stored as val

for i in range(val):
#this will run from 1-val
    print(random.randint(1,99))
    #these numbers are simply being printed, not stored

rawDescription: Store the numbers of a `for` loop's output, and sum them all?


code:
import fred
fred.main()

rawDescription: Breaking Python Circular Imports

description: Breaking Python Circular Imports


code:
import xml.etree.ElementTree as ET
the_tree = ET.fromstring('''<class id="1" name="good/bad">
    <verb>
        <token>like</token>
        <token>feel</token>
    </verb>
    <mess>This is <sugg>not</sugg> text</mess>
    <id type="incorrect">I'm glad to <marker>unsee you</marker>.</id>
    <id type="correct">I'm glad to see you.</id>
</class>''')
elems = the_tree.find('./verb').getchildren()
verbs = [verb.text for verb in elems]
# -> ['like', 'feel']

rawDescription: How to extract text from tags using ElementTree

description: Extract text from tags using ElementTree


code:
import wx
import numpy
import matplotlib

from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas

class TestFrame(wx.Frame):
    def __init__(self,parent,title):
        wx.Frame.__init__(self,parent,title=title,size=(500,500))
        self.sp = wx.SplitterWindow(self)
        self.p1 = wx.Panel(self.sp, style=wx.SUNKEN_BORDER)
        self.p2 = MatplotPanel(self.sp)
        self.sp.SplitVertically(self.p1,self.p2,100)
        self.statusbar = self.CreateStatusBar()
        self.statusbar.SetStatusText('Oi')

class MatplotPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent,-1,size=(50,50))

        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        t = numpy.arange(0.0,10,1.0)
        s = [0,1,0,1,0,2,1,2,1,0]
        self.y_max = 1.0
        self.axes.plot(t,s)
        self.canvas = FigureCanvas(self,-1,self.figure)

app = wx.App(redirect=False)
frame = TestFrame(None, 'Hello World!')
frame.Show()
app.MainLoop()

rawDescription: WXPython with MatPlotLib

description: WXPython with MatPlotLib


code: minimize(tmp,[0,0,3,60000], args=(n,cons),tol =1e-15)#where args is (2,False) for example

rawDescription: Minimizing a function while keeping some of the variables constant


code:
df['weighted_sum'] = df.dot(weight)
df

rawDescription: How to compute weighted sum of all elements in a row in pandas?

description: Compute weighted sum of all elements in a row in pandas


rawDescription: Two ways to join lists in dataframe: as rows and columns


code: ts.resample('5min', how=sum)

rawDescription: Downsize series containing boolean data with resample


code:
def Collection_is_cheap(C, price):
    result = []
    for rest in C:
        for dish in rest.menu:
            if dish.price <= price:
                result.append(rest)
                break  # stop the rest.menu loop, go to the next
    return result

print(Collection_is_cheap(collection, 28))

rawDescription: Iterating over list of namedtuples, selecting restaurants


code: u': Francja'.lstrip(': ')

rawDescription: Parsing web page in python using Beautiful Soup


code:
from itertools import groupby, chain, dropwhile

def get_sections(fle):
    with open(fle) as f:
        grps = groupby(dropwhile(lambda x: not x.startswith("#"), f))
        for k, v in grps:
            if k:
                yield chain([next(v)], (next(grps)[1]))  # all lines up to next #TYPE

rawDescription: How to split file into chunks by string delimiter in Python

description: Split file into chunks by string delimiter in Python


rawDescription: Converting columns in a file into separate lists using python


rawDescription: What is faster: Python3's 'len' or numpys shape?


rawDescription: python asign value of list variable from text file

description: Python asign value of list variable from text file


rawDescription: Numpy function to get shape of added arrays


code:
def foo(bar, lst):
    return lst + [bar]

some_list = []
now_list = foo('baz', some_list)

rawDescription: What are non-pure functions in python?

description: What are non-pure functions in python


code:
def add_optimal_edge(graph, rank, n=1):
    paths = [[graph]] # start off with just one graph path, which contains a single graph
    for generation in range(n):
        # path[-1] is the latest graph for each generation
        paths = (path + path[-1].add_edge(e) for path in paths for e in path[-1].possible_new_edges())
    # select best path by comparison of final generation against original graph
    best = max(paths, lambda path: rank(graph, path[-1]))
    return best[1] # returns the first generation graph

rawDescription: lookahead algorithm in Python

description: Lookahead algorithm in Python


code:
import json

json_result = json.loads(json_string)
id = json_result['data'][0]['id']

rawDescription: Collecting a value from Json

description: Collecting a value from Json


rawDescription: Python reversing slice of a list

description: Python reversing slice of a list


code: df.groupby(['c1', 'c2']).cumcount()

rawDescription: best way to add sequential counter column using pandas.groupby

description: Add sequential counter column using pandas.groupby


rawDescription: pandas object indexes can be either string or int, how can I tell them apart?

description: Pandas object indexes can be either string or int, how can I tell them apart


code: list_of_files = ...

rawDescription: Create numerous unique events

description: Create numerous unique events


code:
for line in infile:
    if line.startswith("Class"):
        temp,class_var = line.split(' ')
        class_var = class_var.replace(':','')
    elif line.startswith("Subject"):
        temp,subject = line.split(' ')
        subject = subject.replace(':','')

rawDescription: Efficient way to calculate averages, standard deviations from a txt file


code:
with Timeout(2, False):
    node_message = NodeMessage.recv(active_socket)

rawDescription: gevent 'with Timeout' stopped working

description: Gevent 'with Timeout' stopped working


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


code: mask = (min_value < a) & (a < max_value)

rawDescription: Filter an array in Python3 / Numpy and return indices


code:
def check(a, b):
    return bool(a) != bool(b)

rawDescription: Compare nth elements of multiple lists

description: Compare nth elements of multiple lists


code:
search = { "START": "Virginia", "END": "Boston" }
trip = next(d for d in dict_list if all(i in d.items() for i in search.items()))

rawDescription: Python: How to access the dictionary that has specific key-values in a list


code:
def on_release(self, event):
    ...
    self.signal.updatedSignal.emit(str(self.point.newYcoordinate))

rawDescription: Draggable point in matplotlib - How to retrieve point coordinates


rawDescription: Better way to shuffle two numpy arrays in unison


code: 'Hawthorn'

rawDescription: Python Pandas get one text value

description: Python Pandas get one text value


code: df

rawDescription: How to apply hierarchy or multi-index to panda columns

description: Apply hierarchy or multi-index to panda columns


rawDescription: "TypeError: can't multiply sequence by non-int of type 'float'" when multiplying two lists of floats


code: sorted([dict([('user', k)] + list(v.items())) for k, v in a['users'].items()], key=lambda x: x['rating'])

rawDescription: flask/jinja: creating a leaderboard out of an unordered dict object

description: Flask/jinja: creating a leaderboard out of an unordered dict object


code:
import inspect
import os
import sys

def get_my_path():
    try:
        filename = __file__ # where we were when the module was loaded
    except NameError: # fallback
        filename = inspect.getsourcefile(get_my_path)
    return os.path.realpath(filename)

# path to ConfigManager.py
cm_path = get_my_path()
# go 6 directory levels up
sp_path = reduce(lambda x, f: f(x), [os.path.dirname]*6, cm_path)
constants_path = os.path.join(sp_path, "conf", "constants.cfg")

rawDescription: Python : How to access file from different directory


code:
klass = getattr(module, classname)
instance = klass(*args, **kw)

rawDescription: Instantiating object of a class using the name of the class


code:
def HandleCheckbox(self, e):
    print(e.object.title, e.value)

rawDescription: Python create an event to an ObjectListView check box


code: pd.read_csv(filename, ...)

rawDescription: Combine date column and time column into index in pandas data frame


code:
class MyTuple(namedtuple('MyTuple', 'field1 field2')):
    __slots__ = ()

    def __new__(cls, field1, field2):
        """Create a new instance of MyTuple(field1, field2)"""
        return super(MyTuple, cls).__new__(cls, field1.lower(), field2)

    def __str__(self):
        return '{}:{}'.format(self.field1, self.field2)

rawDescription: Lowercase a field in namedtuple in python


rawDescription: How to create a list of fields in django forms

description: Create a list of fields in django forms


code: re.search('<!-- begin staff -->.*<!-- end staff -->', text, re.DOTALL)

rawDescription: Matching a pair of comments in HTML using regular expressions


code: room is Test

rawDescription: Using globals() to create class object

description: Using globals() to create class object


code:
def decorator_that_makes_func_into_generator(func):
    def wrapper(*a, **ka):
        yield from func(*a, **ka)
    return wrapper

rawDescription: Using decorator to turn function into generator in python


code: used_user, used_real, aligned = map(sum,(used_bytes, total_bytes, aligned_bytes))

rawDescription: Pythonic way to aggregate object properties in memory efficient way?


rawDescription: Permute a list using Python

description: Permute a list using Python


rawDescription: Python sort a JSON list by two key values


code: rolesFormSet = rolesInlineFormSet(request.POST, instance=app, prefix='roles')

rawDescription: Multiple linked Django forms, one submit


code:
data = {
    'ID': ['A2035559', 'A20340619', 'A2035559', 'A20340619'],
    'FIRST_NAME': ['Sometsdf', 'Nsdsjes', 'Sometsdf', 'Nsdsjes'],
    'FIRST_SUBJECT': ['SCIENCE', 'MATHS', 'ENGINEERING', 'SCIENCE'],
    'SECOND_SUBJECT': [None, None, None, None]
}

d = pandas.DataFrame(data=data, columns=['ID', 'FIRST_NAME', 'FIRST_SUBJECT', 'SECOND_SUBJECT'])

dup_first = d.drop_duplicates(subset=['ID'], take_last=True)
dup_last = d.drop_duplicates(subset=['ID'], take_last=False)

for row in dup_last['ID']:
    dup_first.loc[dup_first['ID'] == row, 'SECOND_SUBJECT'] = dup_last.loc[dup_last['ID'] == row, 'FIRST_SUBJECT'].values[0]

dup_first

rawDescription: How to work with duplicate entries in Pandas Data Frame?

description: Work with duplicate entries in Pandas Data Frame


code:
import facebook

API_KEY     =   'your_api_key'
SECRET_KEY  =   'your_secret_key'

fb = odb.facebook.Facebook(API_KEY, SECRET_KEY)

fb_uid = self.request[API_KEY+'_user']
fb_session_key = self.request[API_KEY+'_session_key']
fb_ss = self.request[API_KEY+'_ss']
fb_signature = self.request[API_KEY] #no suffix for signature

fb.session_key = fb_session_key
fb.uid = fb_uid

fb.friends.get() # Results in list of friends

rawDescription: Accessing Facebook Connect FBML cookie via PyFacebook?


code: chili = list(my_dict[2])

rawDescription: Behaviour of DEL with list taken from a dict


code:
class HomeView(MethodView):

    def get(self):
        thing = do_fun_stuff()
        return render_template('home', foo=thing)

app.add_url_rule('/', view_func=HomeView.as_view('home'))

rawDescription: Flask view methods and SRP

description: Flask view methods and SRP


code:
import datetime
import pandas as pd
DF = pd.read_csv('time_test.csv', dtypes = {'Date' : str, 'Time' : str})
datetime_index = []

for row in DF.index:
    time_val = DF.loc[row, 'Time']
    date_val = DF.loc[row, 'Date']
    while len(time_val) != 4: #pad with zeros as needed to avoid conditional testing
        time_val = '0' + time_val
    datetime_index.append(datetime.datetime(int(date_val[:4]), int(date_val[4:6]), int(date_val[6:]), int(time_val[:2]), int(time_val[2:]), 00))

DF['Datetime'] = pd.Series(datetime_index, index = DF.index)

rawDescription: Create Pandas Datetime index from 8 digit date and 2,3, and 4 digit time


code:
class AutoNameValueEnum(enum.Enum):
   def __init__(self):
       self._value_ = self._name_.lower()
class Color(AutoNameValueEnum):
   RED = ()
Color.RED

rawDescription: How to create an enum that uses the name of the member as the value?

description: Create an enum that uses the name of the member as the value


rawDescription: load csv into 2D matrix with numpy for plotting

description: Load csv into 2D matrix with numpy for plotting


code:
import subprocess
subprocess.call("command1")
subprocess.call(["command1", "arg1", "arg2"])

rawDescription: Run a command every one second using threads in python


rawDescription: How to add values accordingly of the first indices of a dictionary of tuples of a list of strings? Python 3x

description: Add values accordingly of the first indices of a dictionary of tuples of a list of strings? Python 3x


code:
tmp=min(x,y)
y=max(x,y)
x=tmp

rawDescription: Number sort using Min, Max and Variables


code:
groups = db.GqlQuery("SELECT * "
                     "FROM Group")

for g in groups:
   if user.key() not in g.users:
      group = g
      break

group.users.append(user.key())

rawDescription: GQL - Select all parents where specific child is not in children


code:
import re
with open('test.txt') as test_f, open('result.txt', 'w') as result_f:
    for line in test_f:
        new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)
        result_f.write(new_str)

rawDescription: write a text file in Python, line by line

description: Write a text file in Python, line by line


code: "ABCDEFG"

rawDescription: Can I create an RPG-esque save & quit, and then reload progress?

description: Create an RPG-esque save & quit, and then reload progress


code:
import cwrapper
api = Wrapper(cwrapper)

class MyClass(object):
    i = api.__some_Getter() #works

rawDescription: Clean way to circumvent name mangling for a module?


code:
import re
s="The Strings"
s=re.sub("\w","#",s)
s
s='Hello' + "her mom's shirt"
s
re.sub("\w","#",s)

rawDescription: how to replace the characters in strings with '#'s by using regex in Python

description: Replace the characters in strings with '#'s by using regex in Python


code: newdict = {k: v for k,v in d.iteritems() if v > 20}

rawDescription: Fastest way to remove a lot of keys from a dictionary


code:
from random import randint
randint(100, 999)  # randint is inclusive at both ends

rawDescription: How to generate random number with the specific length in python

description: Generate random number with the specific length in python


code:
globals()
x=2
globals()

rawDescription: Python - how to get a list of all global names I have ever defined?


code:
with open("file.nh", "r") as f:
    for line in f:
        z = re.findall(r"\):([0-9.]+)", line)
        print(z)

rawDescription: Splitting a file with multiple but not all delimiters in Python


code:
class MyApp(App):
    prefix = StringProperty('1')

rawDescription: Kivy: is it possible to trigger events with class level (not instance) Properties?


rawDescription: different encrypted versions on encrypting the same string using the same key

description: Different encrypted versions on encrypting the same string using the same key


Presence: Equipped

Equipped Product Name: EEE UCS B200 M3

rawDescription: Nesting dictionaries while looping through data


code:
from __future__ import print_function
import pandas as pd
try: import builtins
except ImportError: import __builtin__ as builtins

def print(*args, **kwargs):
    args = [item if not isinstance(item, (dict,)) else pd.Series(item)
            for item in args]
    builtins.print(*args, **kwargs)

print({'cheese':'stilton', 'swallow':'african', 'ride':'coconuts'})
print(2,3,4, sep=' -- ')

rawDescription: How to print dict as a pandas.Series

description: Print dict as a pandas.Series


code:
def hard_maths(name_matrix):
    name, matrix = name_matrix
    return name, np.dot(np.linalg.inv(matrix),
            matrix).round(0)

pool = mp.Pool()
results = pool.map(hard_maths, matrices.iteritems())
pool.close()
pool.join()

rawDescription: Return map results as keyed dictionary

description: Return map results as keyed dictionary


code:
c = 's'
results = [k for k,v in enumerate(s) if v == c]
results_sum = sum(results)
(results_sum / len(results)) / float(len(s))

rawDescription: Calculating the Letter Frequency in Python


rawDescription: finding the greatest Fibonacci number within limited time in python

description: Finding the greatest Fibonacci number within limited time in python


code:
annotator = Annotator()
text = """Robots in popular culture are there to remind us of the awesomeness of unbound human agency."""
dep_parse = annotator.getAnnotations(text, dep_parse=True)['dep_parse']

dp_list = dep_parse.split('\n')
pattern = re.compile(r'.+?\((.+?), (.+?)\)')
edges = []
for dep in dp_list:
    m = pattern.search(dep)
    edges.append((m.group(1), m.group(2)))

rawDescription: How to find the shortest dependency path between two words in Python?

description: Find the shortest dependency path between two words in Python


rawDescription: Python function for removing zeroes right of decimal, including decimal point?


code:
def mul(arg):
    return lambda x: x * arg

rawDescription: is it possible to add some new syntax in javascript?

description: Is it possible to add some new syntax in javascript


code:
import matplotlib.pyplot as plt
import pandas as pd
from pandas_datareader import data
import matplotlib.dates as mdates

df = data.get_data_yahoo('AAPL', start='2015-10-01')
fig, ax = plt.subplots(nrows=2, sharex=True)

ax[0].plot(df.index, df['Adj Close'])
ax[0].set_ylabel('price per share')

ax[1].bar(df.index, df['Volume']/10**6)
ax[1].xaxis.set_major_locator(mdates.MonthLocator(bymonthday=-1))
xfmt = mdates.DateFormatter('%B %d, %Y')
ax[1].xaxis.set_major_formatter(xfmt)
ax[1].set_ylabel('Volume (millions)')

# autorotate the xlabels
fig.autofmt_xdate()
plt.show()

rawDescription: Pandas matplotlib plotting, irregularities in time series labels between bar graph and line graph


code: frame[zipcol] = frame[zipcol].str[:5]

rawDescription: Faster processing of Dataframe in Pandas


rawDescription: Python calling method in class

description: Python calling method in class


code:
def divide(x):
    if x < 0:
        x = -x
    left, _, right = str(x).partition(".")
    first = [int(left[0])]
    second = [int(i) for i in left[1:]]
    third = [int(i) for i in right]
    if first == [0] and third:
        first = []
    return first, second, third

rawDescription: Using Float questions

description: Using Float questions


code: frame.loc[frame['DESIGN_VALUE'] > 20,['mycol3', 'mycol6']]

rawDescription: Subset of columns and filter Pandas

description: Subset of columns and filter Pandas


code:
mock_storage = mock.Mock()
obj._fetch_law(some_task, mock_storage)
mock_storage.extend.assert_called_with(expected_value)

rawDescription: How do you get to the value inside of a python function that returns nothing for unit testing?

description: Get to the value inside of a python function that returns nothing for unit testing


code:
import scipy.ndimage

mask = data > 20
labels, num_labels = scipy.ndimage.label(mask)
custers = scipy.ndimage.find_objects(labels)

rawDescription: detect high values from numpy array

description: Detect high values from numpy array


code: a.split(" ")

rawDescription: Printing long interger in python up to 10 digits


rawDescription: numpy element transformation with lambda?

description: Numpy element transformation with lambda


code:
def make_callback(params):
    def callback():
        print(params)
    return callback
params = 1,2,3
button = tk.Button(master, text='Boink', command=make_callback(params))

rawDescription: access to top level widget in Tkinter

description: Access to top level widget in Tkinter


code:
df = pd.DataFrame(np.random.rand(10))

df.loc[np.random.choice(df.index, 5, replace=False)]

rawDescription: Subsample pandas dataframe

description: Subsample pandas dataframe


code:
while True:
    ...

rawDescription: How do I go back to a variable in python?

description: Go back to a variable in python


code: objectsList = [w_lewo, w_prawo, w_gore, w_dol]

rawDescription: Sikuli Random - function that randomly click one of the location


code:
DEVELOP = True

# other codes and stuff

if DEVELOP == False:
    MEDIA_ROOT = os.path.join(PROJECT_ROOT,'media')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
if DEVELOP == False:
    STATIC_ROOT = os.path.join(PROJECT_ROOT,'static')

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT,'static'),
    # 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.
)

rawDescription: How To add images in Django project

description: How To add images in Django project


code:
class CustomDict(dict):
    def __getitem__(self, key):
        try:
            return dict.__getitem__(self, key)
        except KeyError:
            closest_key = min(self.keys(), key=lambda x: abs(x - key))
            return dict.__getitem__(self, closest_key)

rawDescription: Find integer nearest-neighbour in a dict


code:
data='''\
<root>
<node1>
  <node2 a1="x1"> ... </node2>
  <node2 a1="x2"> ... </node2>
  <node2 a1="x1"> ... </node2>
</node1>
</root>
'''
doc = lxml.etree.XML(data)
e=doc.find('node1')
child = lxml.etree.Element("node3",attrib={'a1':'x3'})
child.text='...'
e.insert(1,child)
print(lxml.etree.tostring(doc))

rawDescription: add xml node to xml file with python

description: Add xml node to xml file with python


code:
import numpy as np
from scipy.signal import argrelextrema
data = np.array([ 5, 12.3, 12.3, 7, 2, 6, 9, 10, 5, 9, 17, 2 ])
radius = 2 # number of elements to the left and right to compare to
argrelextrema(data, np.less, order=radius)

rawDescription: numpy how find local minimum in neighborhood on 1darray

description: Numpy how find local minimum in neighborhood on 1darray


code:
import fileinput
import cProfile

pr = cProfile.Profile()
pr.enable()
for line in fileinput.input():
    for i in range(10):
        y = int(line.strip()) + int(line.strip())
pr.disable()
pr.print_stats(sort='time')

rawDescription: Python getting meaningful results from cProfile


code:
import xml.etree.ElementTree as ET
context = ET.iterparse('file.xml', events=('end', ))
index = 0
for event, elem in context:
    if elem.tag == 'row':
        index += 1
        filename = format(str(index) + ".xml")
        with open(filename, 'wb') as f:
            f.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
            f.write(ET.tostring(elem))

rawDescription: Splitting XML file into multiple at given tags


code:
# ...
for line in open('/home/ibrahim/Desktop/Test.list'):
    company, founding_year, number_of_employee = line.split(',')
    comp_info = CompanyInfo(company, founding_year, number_of_employee)

rawDescription: using a class instead of a list python

description: Using a class instead of a list python


code:
newfieldnames = csvreader.fieldnames
lastfield = newfieldnames.pop() # remove last field
if 'field_name' in newfieldnames:
    newfieldnames.remove('field_name') # remove by field name
writer = csv.DictWriter(f, newfieldnames)

rawDescription: Unable to write list back to CSV

description: Unable to write list back to CSV


code: LOGIN_REDIRECT_URL = '/enter/' # or any URL you want

rawDescription: How to have specific users see different webpages? Django

description: Have specific users see different webpages? Django


rawDescription: django queryset get object from filter

description: Django queryset get object from filter


code:
array3 = array1.astype(float) # this copies the array by default.
array3[array1 != 0] = array2[array1[array1 != 0]-1, 2]

rawDescription: Replacing entries of an array with those of different array


rawDescription: Simple way to get current memory usage from Guppy


code:
c = get_config()
c.Exporter.preprocessors = ['prelatex.MyLatexPreprocessor']

rawDescription: IPython nbconvert to latex - syntax colouring


code:
math = Class.objects.get(pk=1)
math.work_set.all()

rawDescription: Django foreign key starting with nothing


code:
combined = df1.merge(df2, how='outer')
combined
combined = df1.merge(df2, how='outer').fillna(0)
combined

rawDescription: efficient method for merging 2 sorted files with duplicate coordinates in python

description: Efficient method for merging 2 sorted files with duplicate coordinates in python


code:
import matplotlib.pyplot as plt

#First normal figure
fig1, axarr1 = plt.subplots(2,2, figsize=(6,6), dpi=100)
for i,ax in enumerate(axarr1.flatten()):
    ax.plot(range(10))
    ax.set_title('title'+str(i), fontsize=10)
    ax.set_xlabel('x'+str(i), fontsize=10)
    ax.set_ylabel('y'+str(i), fontsize=10)
plt.tight_layout()

fig2, axarr2 = plt.subplots(2,2, figsize=(12,12), dpi=50)
for i,ax in enumerate(axarr2.flatten()):
    ax.plot(range(10))
    ax.set_title('title'+str(i), fontsize=20)
    ax.set_xlabel('x'+str(i), fontsize=20)
    ax.set_ylabel('y'+str(i), fontsize=20)
plt.tight_layout()

plt.show()

rawDescription: Adjusting figure quality in matplotlib

description: Adjusting figure quality in matplotlib


code:
import pandas as pd
import numpy as np

cols = {}
for col in ('A', 'B', 'C', 'D', 'E'):
    cols[col] = np.random.randint(1, 5, 20)
df = pd.DataFrame(cols)

def filter_df(df, filter_cols, value):
    conditions = []
    for col in filter_cols:
        conditions.append('{c} == {v}'.format(c=col, v=value))
    query_expr = ' and '.join(conditions)
    print('querying with: {q}'.format(q=query_expr))
    return df.query(query_expr)

rawDescription: pandas: Is it possible to filter a dataframe with arbitrarily long boolean criteria?

description: Pandas: Is it possible to filter a dataframe with arbitrarily long boolean criteria


rawDescription: Python: write fitparameters into table

description: Python: write fitparameters into table


code:
fobj = open('data.csv')
data = [ x.split() for x in fobj ]
fobj.close()  #don't forget to close :)

rawDescription: python 2.4 sorting a text file by specific column

description: Python 2.4 sorting a text file by specific column


code:
# Column of row titles
rows = np.array(['row1', 'row2', 'row3'])[:, np.newaxis]
str_data = np.char.mod("%10.6f", data)
with open('test.csv', 'w') as f:
    np.savetxt(f, np.hstack((rows, str_data)), delimiter=', ', fmt='%s')

rawDescription: Python/Numpy - Save Array with Column AND Row Titles


code:
for i in date_list:
    data[i+"InDays"] = data[i].apply(lambda x: current_date - x if x is not pd.NaT else pd.Timedelta(0))

rawDescription: pandas error creating TimeDeltas from Datetime operation

description: Pandas error creating TimeDeltas from Datetime operation


code:
import pexpect

child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('Name .*: ')
child.sendline('anonymous')
child.expect('Password:')
child.sendline('noah@example.com')
child.expect('ftp> ')
child.sendline('cd pub')
child.expect('ftp> ')
child.sendline('get ls-lR.gz')
child.expect('ftp> ')
child.sendline('bye')

rawDescription: Provide called shell script with input in Python


rawDescription: Pandas: top N rows, top N rows per group, equivalent for ROW_NUMBER OVER(PARTITION BY ... ORDER BY ...)


code: root.bind('Key-{n}'.format(n=num[i]), lambda e, i=i: self.do(num[i]))

rawDescription: Creating buttons inside loop command failing


code:
operands1 = list(range(2, 12))
operators = ["+"]
operands2 = list(range(2, 12))

while question < 10:
    operand1 = random.choice(operands1)
    operand2 = random.choice(operands2)
    operator = random.choice(operators)
    user_answer = int(input('{} {} {} '.format(operand1, operator, operand2)))
    if operator == '+':
        expected_answer = operand1 + operand2
        if user_answer == expected_answer:
            print('This is correct!')
            score = score + 1
            question = question + 1
            time.sleep(2)
        else:
            print('This is incorrect!')
            question = question + 1
            time.sleep(2)

rawDescription: Python: how to make python calculate a sum to make sure an input is correct?


code:
sns.factorplot('ids', 'data', hue='var', kind='bar',
               data=df[df.isin({'ids':['Bob','Mary']}).any(1)])

rawDescription: How to iterate over a pandas dataframe and compare certain columns based on a third column?

description: Iterate over a pandas dataframe and compare certain columns based on a third column


code:
# inside the loop instead of iterating over the fields in the
# dict / row at hand, one could easily for instance do:
resp_json = json.loads(JSON_TEXT)
for d in resp_json['transacDet']:
    insert_row(**d)

rawDescription: Iterate python dictionary to assign value to table's fields


code:
pulses = random_integers(0, 1000, 4.2e6)
nZones = 200
zones = [[] for i in range(nZones)]

rawDescription: Speed up Python loop to categorize integers into a list of lists


rawDescription: Using the Image.point() method in PIL to manipulate pixel data


code:
{'stringOfAlphaNumeric2': ('stringOfAnyCharacter4', 'stringOfAnyCharacter5', 'stringOfAnyCharacter6'),
'stringOfAlphaNumeric1': ('stringOfAnyCharacter1', 'stringOfAnyCharacter2', 'stringOfAnyCharacter3')}

rawDescription: Again, regular expression matching in python


code:
def runmethods(self, variables, methods):
   for method in methods:
       method(variables)

rawDescription: Running bunch of python methods on a single piece of data


code:
for note in root.xpath('//note'):  # Locate all tags under the root named 'note'. There's one.
    my_values = dict(
        title = note.xpath('title'),
        created = note.xpath('created'),
        updated = note.xpath('updated'),
        latitude = note.xpath('latitude'),
        longitude = note.xpath('longitude'),
        mime = note.xpath('mime'),
        timestamp = note.xpath('timestamp'),
    )

rawDescription: Extracting each instance of a group of tags from an xml file and Parsing as a Column


code:
matching_result = YourModel.objects.filter(Q(name__contains='super') |
                                           Q(name__contains='very') |
                                           Q(name__contains='news'))

rawDescription: How to match string with database fields in Django?

description: Match string with database fields in Django


rawDescription: Using a map to return something specific


code:
import csv
from io import BytesIO
sample = BytesIO('''\
"4256996"\t"test@gmail.com"\t"Y  "\t"98230\r"\t"2012-07-10T12:00:00"\t"some  location"\t\\N\t\\N\t"false"\t"aaa"\t"another-field"\t"true"\t1\r\n''')
sample.readline()
sample.seek(0)
reader = csv.reader(sample, delimiter='\t',
        lineterminator='\n',
        quoting=csv.QUOTE_ALL
    )
next(reader)

rawDescription: python tab separated file parsing problems

description: Python tab separated file parsing problems


code: edge_labels[(node1, node2)] = float(weight1)

rawDescription: python 3 directed graph with labels from file

description: Python 3 directed graph with labels from file


code:
class MyModel1Admin(admin.ModelAdmin):

    class Media:
        js = ['/media/decimal_to_sci_not.js']

admin.site.register(MyModel1,MyModel1Admin)

rawDescription: Django - How to display Scientific Notation on Admin Page Field?


code: placeholders = ','.join("'%s'" % w for w in wortliste)

rawDescription: Give a list of strings to a sql-query [Python]


code:
class AdForm(Form):

    name = TextField(_('Name'), [validators.Length(min=4, max=50,
                     message=_('Name is required'))], widget=MyTextInput())
    title = TextField(_('title'))
    text = TextAreaField(_('Text'), widget=TextArea())
    phonenumber = TextField(_('Phone number'))
    phoneview = BooleanField(_('Display phone number on site'))
    price = TextField(_('Price'))
    password = PasswordField(_('Password'))
    email = TextField(_('Email'))

rawDescription: How to get red borders when a field is invalid using WTForms with GAE and Jinja2?

description: Get red borders when a field is invalid using WTForms with GAE and Jinja2


code:
def filterAcceptsRow(self, row, parent):
    if self.filterActive and '_B_' in self.sourceModel().data(self.sourceModel().index(row, 0), Qt.DisplayRole).toPyObject():
        self._view.selectRow(row)
    return True

rawDescription: How to select QTableView index or row from inside of Model

description: Select QTableView index or row from inside of Model


code:
def checkclas(x):
   if x not in ("A", "B", "C"):
      while x not in ("A", "B", "C"):
          x = input("You have to choose one of the three classes:     ").upper()
      return x
   else:
      return x

clas = input("which class are you in? ").upper()
clas = checkclas(clas)
print (clas)

rawDescription: How to use a shortcut for the (or) statement in python

description: Use a shortcut for the (or) statement in python


code:
circ1 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize=10, markerfacecolor="red")
circ2 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.3, markersize=10, markerfacecolor="blue")
circ3 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize=10, markerfacecolor="yellow")

plt.legend((circ1, circ2, circ3), ("Cat 1", "Cat 2", "Cat 3"), numpoints=1, loc="best")

rawDescription: Legend using PathCollections in matplotlib


code:
def myview(request):
    cats = Category.objects.all()
    render(request, "mytemplate.html", {"categories" : cats})

rawDescription: how to display the name field of Category model instead of [<Category: hockey>, <Category: run>]

description: Display the name field of Category model instead of [<Category: hockey>, <Category: run>]


code: return float(decimal.Decimal(base_str + '.' + dec_str))

rawDescription: float random.uniform to 4 decimal places in python

description: Float random.uniform to 4 decimal places in python


code:
import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.random((200,3)))
df['date'] = pd.date_range('2000-1-1', periods=200, freq='D')
mask = (df['date'] > '2000-6-1') & (df['date'] <= '2000-6-10')
print(df.loc[mask])

rawDescription: Select dataframe rows between two dates

description: Select dataframe rows between two dates


code:
with open('csvbooks_out.csv', 'wt') as f:
    wtr = csv.writer(f)
    for row in booklist:
        wtr.writerow(row)

rawDescription: Saving lists as a csv in python

description: Saving lists as a csv in python


rawDescription: All possible set of digits that sum==n in python list


code: sorted_generator = sorted(filtered, key=regexp.match(line).group(1))

rawDescription: Smart filter with python

description: Smart filter with python


code:
import random
data = [ [random.randint(1, 9) for _ in range(3)] for _ in range(1000000)]

rawDescription: make a dictionary out of first elements in a list of list

description: Make a dictionary out of first elements in a list of list


code:
for action, file in results:
  if (file != 'file1.txt' and file != 'file2.txt'): #here you cut the check of the files you don't want.
    full_filename = os.path.join (path_to_watch, file)
    if not os.path.exists (full_filename):
      file_type = "<deleted>"
    elif os.path.isdir (full_filename):
      file_type = 'folder'
    else:
      file_type = 'file'
    yield (file_type, full_filename, ACTIONS.get (action, "Unknown"))

rawDescription: Exlude a file from a directory listing

description: Exlude a file from a directory listing


code: query7 = QSqlQuery ("SELECT Exemplo FROM TabelaSubst WHERE Palavra='"+text+"' ORDER BY Exemple ASC;")

rawDescription: python SQL Variables in SELECT /WHERE

description: Python SQL Variables in SELECT /WHERE


code:
all_challenges = session.query(Challenge).distinct().\
                  join(Challenge.attempts).all()

rawDescription: SQLAlchemy Many-To-Many performance

description: SQLAlchemy Many-To-Many performance


code:
assert isinstance(user_key, ndb.Key)
blog = Blog(title="title", body="body", author=user_key)

rawDescription: Assigning an author to an entity during its creation


rawDescription: Importing UDP Multicast signal into Python


code:
import xml.etree.ElementTree as ET
tree = ET.parse(r'C:\Users\Gord\Desktop\nasty.xml')
npexchange = tree.getroot()
for article in npexchange:
    for articleparts in article:
        for articlepart in articleparts:
            id = articlepart.attrib['id']
            print("ArticlePart - id: {0}".format(id))
            for data in articlepart:
                for npdoc in data:
                    for child in npdoc:
                        tag = child.tag[child.tag.find('}')+1:]
                        print("    {0}:".format(tag))  ## e.g., "body:"
                        contents = ET.tostring(child).decode('utf-8')
                        contents = contents.replace('<ns0:', '<')
                        contents = contents.replace('</ns0:', '</')
                        contents = contents.replace(' xmlns:ns0="http://www.example.com/npdoc/2.1">', '>')
                        contents = contents.replace('<' + tag + '>\n', '')
                        contents = contents.replace('</' + tag + '>', '')
                        contents = contents.strip()
                        print("        {0}".format(contents))

rawDescription: Parsing a complicated XML file with Python


rawDescription: Little confused with import python

description: Little confused with import python


code:
import io
import requests
from django.core.files import File
from django.core.files.storage import Storage
from django.conf import settings
from django.utils.deconstruct import deconstructible

@deconstructible
class PastebinStorage(Storage):
    def __init__(self, options=None):
        """ The options parameter should be a dict of pastebin parameters for
        the 'create new paste' operation: see http://pastebin.com/api#2
        The most important required option is api_dev_key. Optionally you can
        set api_user_key you want to create non-guest pastes. """
        self.__options = getattr(settings, 'PASTEBIN_STORAGE_OPTIONS', {})
        if options is not None:
            self.__options.update(options)

    @property
    def options(self):
        if 'api_dev_key' not in self.__options:
            raise ValueError('The "api_dev_key" option is missing')
        return self.__options

    def _save(self, name, content):
        # TODO: allow overriding the options on a per-file basis. Maybe we
        # should encode options into the name since we don't use it and
        # we return a completely new name/id at the end of this method.
        data = self.options.copy()
        data.update(
            api_option='paste',
            api_paste_code=content.read(),
        )
        response = requests.post('http://pastebin.com/api/api_post.php', data=data)
        response.raise_for_status()
        # A successful response contains something like: http://pastebin.com/<PASTE_KEY>
        return response.text[response.text.rfind('/')+1:]

    def _open(self, name, mode='rb'):
        if mode != 'rb':
            raise ValueError('Currently the only supported mode is "rb"')

        if 'api_user_key' in self.options:
            content = self._get_user_paste(name)
        else:
            content = self._get_public_paste(name)

        mem_stream = io.StringIO(content)
        mem_stream.name = name
        mem_stream.mode = mode
        return File(mem_stream)

    def _get_user_paste(self, name):
        response = requests.post('http://pastebin.com/api/api_raw.php', data=dict(
            api_dev_key=self.options['api_dev_key'],
            api_user_key=self.options['api_user_key'],
            api_option='show_paste',
            api_paste_key=name,
        ))
        # FIXME: Unfortunately the API seems to return status_code 200
        # also in case of errors with messages like "Bad API request,
        # invalid permission to view this paste or invalid api_paste_key"
        # in the body.
        response.raise_for_status()
        return response.text

    def _get_public_paste(self, name):
        response = requests.get('http://pastebin.com/raw/' + name)
        response.raise_for_status()
        return response.text

    def get_valid_name(self, name):
        return name

    def get_available_name(self, name, max_length=None):
        return name

rawDescription: Passing an input to a service and saving the result to DB in Django


code:
def repr_namedtuples(dumper, data):
    return dumper.represent_mapping(u"!namedtupleBase", {
        "__name__": data.__class__.__name__,
        "__dict__": collections.OrderedDict(
            [(k, v) for k, v in data._asdict().items()])
    })

def consruct_namedtuples(loader, node):
    value = loader.construct_mapping(node)
    cls_ = namedtuple(value['__name__'], value['__dict__'].keys())
    return cls_(*value['__dict__'].values())

yaml.add_multi_representer(namedtupleBase, repr_namedtuples)
yaml.add_constructor("!namedtupleBase", consruct_namedtuples)

rawDescription: Serializing namedtuples via PyYAML

description: Serializing namedtuples via PyYAML


code:
for i in range(10):
    print(i)
    i += 1

rawDescription: Python: list items are not changed in for loop


rawDescription: python - choose top k elements of column 2 for each value of column 1 in sorted numpy matrix

description: Python - choose top k elements of column 2 for each value of column 1 in sorted numpy matrix


code: filter("".join, result)

rawDescription: How do I split a list into a list of lists on a specific character in the elements?

description: Split a list into a list of lists on a specific character in the elements


code:
xml = et.fromstring(x)

print(et.tostring(xml))
e = et.SubElement(xml.find(".//attributes/transpose"), "octave-change")
e.text = "-1"
e.tail= "\n"

rawDescription: How to add a new Element to a musicXML tree in Python (elementtree)?

description: Add a new Element to a musicXML tree in Python (elementtree)


rawDescription: Speed up multi-loop data computation in Pandas


rawDescription: How to check if any tuple same as previsious or next

description: Check if any tuple same as previsious or next


code:
import numpy as np
x_str = np.array_repr(x).replace('\n', '')
print(x_str)

rawDescription: How to print numpy objects without line breaks

description: Print numpy objects without line breaks


code: multiple_index = [entry[0:3] for entry in L]

rawDescription: Python list index splitting and manipulation


rawDescription: how to sample a very big CSV file(6GB)

description: Sample a very big CSV file(6GB)


code:
import re
re.search(r"/(\d+)\?t:ac=(\d+)/(\d+)$", url).groups()

rawDescription: split url by python

description: Split url by python


code: " ".join(["{}/{}".format(word,pos) for word, pos in tagged_text])

rawDescription: chunk NP and VP using nltk

description: Chunk NP and VP using nltk


rawDescription: Writing tabs in a specific way (Not from lists) in python


code:
old = '''The quick
brown fox jumps
over the lazy
dog
'''
old.rstrip('\n').rsplit('\n', 1)[0] + '\nhorse and rider'

rawDescription: How do I efficiently replace the last line in a string?

description: Efficiently replace the last line in a string


code:
from django.views.generic import View
from django.http import HttpResponse

class CreateReport(View):

    def get_data(self):
        # Query your data here, probably using self.request to get query string
        ...
        return data

    def generate_report(self):
        # Here you will create xlsx doc and populate with data according to docs linked before
        ...
        return workbook

    def get(self, request, *args, **kwargs):
        document = self.generate_report()
        _file = open(document.filename, 'r')

        response(HttpResponse(_file, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'))
        response['Content-Disposition'] = 'attachment; filename=%s' % document.filename.split('/')[-1]  # Here will return a full path, that's why probably you will need a split to get only the filename
        add_never_cache_headers(response=response)  # To avoid download the same file with out of date data.
        return response

rawDescription: Download SQL data in xlsx format with Django


code:
def test(View):
    # Get the data from post
    if request.method == 'POST':
        name = request.POST['name']
        # And get all the variable you need for the tasks

        # Now call the task like this
        file_transfer.delay(name, 'test', 'test')

rawDescription: call a celery task within a Django view method?

description: Call a celery task within a Django view method


code:
def cities(request):
    data = requests.get('http://127.0.0.1:8000/app/cities/').json()
    context = RequestContext(request, {
        'cities': data.cities,
    })
    return render_to_response('taskmanager/cities.html', context)

def Peoplelist(request, pk):
    data = requests.get('http://127.0.0.1:8000/app/cities/' + pk + '/students/').json()
    context = RequestContext(request, {
        'students': data.students,
    })
    # Better rename this one to students.html
    return render_to_response('taskmanager/numbers.html', context)

def student_details(request, pk):
    data = requests.get('http://127.0.0.1:8000/app/students/' + pk).json()
    context = RequestContext(request, {
        'student': data.student,
    })
    return render_to_response('taskmanager/student_detail.html', context)

rawDescription: Consuming api from django rest framework


rawDescription: How to "pretty print" a python pandas DatetimeIndex


code:
float_array = array('d', [1, 1.2, 0.34, 9.8, 0.13, 1.1, 0.88, 72])
float_array.byteswap()
s = float_array.tostring()
new_float_array = array('f')
new_float_array.fromstring(s)
new_float_array

rawDescription: Convert a float array into little/big endian


code:
import pygame, itertools

RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)

colors = (RED, BLACK, BLUE) # to allow you to iterate over the colors

SIZE = (1000,1000)
screen = pygame.display.set_mode(SIZE)

# to cycle through the colors
cycle = itertools.cycle(colors) # create an infinite series..

clock = pygame.time.Clock() # regulate fps

while True:
    # handling events
    for event in pygame.event.get():
        if event.type == pygame.QUIT: # close window event
            pygame.quit()

    c = cycle.next()
    pygame.draw.circle(screen,c,(500,500),200)
    pygame.display.flip()

    clock.tick(6) # run at maximum 6 frames per second

rawDescription: Basic Pygame Graphics

description: Basic Pygame Graphics


code:
import h5py
import hdf5storage
import numpy as np

matfiledata = {} # make a dictionary to store the MAT data in
matfiledata[u'variable1'] = np.zeros(100) # *** u prefix for variable name = unicode format, no issues thru Python 3.5; advise keeping u prefix indicator format based on feedback despite docs ***
matfiledata[u'variable2'] = np.ones(300)
hdf5storage.write(matfiledata, '.', 'example.mat', matlab_compatible=True)

rawDescription: Creating a .mat file of v7.3 in python

description: Creating a .mat file of v7.3 in python


code:
with open("finalhostlist.txt", "wt") as f_out, open(infile, "rt") as f_in:
        for line in f_in:
            out.write(line.strip("\\"))

rawDescription: python split string from file

description: Python split string from file


code:
Apple_farm['Good_apples'] = Apple_farm['Good_apples'].astype(float)
Apple_farm['Total_apples'] = Apple_farm['Total_apples'].astype(float)

Apple_farm['Good_apples'] = Apple_farm['Good_apples'].astype(int)
Apple_farm['Total_apples'] = Apple_farm['Total_apples'].astype(int)

rawDescription: Calculating and creating percentage column from two columns


code:
db.define_table('mytable',
    Field('myfield', label=CAT('My', BR(), 'Label')))

rawDescription: multi line headers with web2py's SQLFORM.grid

description: Multi line headers with web2py's SQLFORM.grid


code:
def take(self, amount):
    ret = []
    while True:
        item = self.random()
        if item in ret:
            continue
        ret.append(item)
        if len(ret) == amount:
            return ret

rawDescription: Unique value in nested list - random

description: Unique value in nested list - random


code:
def proxy_kernel(X,Y,K):
    gram_matrix = np.zeros((X.shape[0], Y.shape[0]))
    for i, x in enumerate(X):
            for j, y in enumerate(Y):
                    gram_matrix[i, j] = K(x, y)
    return gram_matrix

rawDescription: Efficient element-wise function computation in Python


code:
from bs4 import BeautifulSoup           ## import bs4 as BeautifulSoup
content = BeautifulSoup(xml_content)    ## convert xml content to beautifulsoup object
span = content.find_all("span")         ## find all span tag and return as list

rawDescription: Accessing online xml with python

description: Accessing online xml with python