code:
def pytest_addoption(parser):
    parser.addoption("--libname", action="append", default=[],
                     help="name of the tested library")

def pytest_generate_tests(metafunc):
    if 'libname' in metafunc.fixturenames:
        metafunc.parametrize("libname", metafunc.config.option.libname)

rawDescription: how to test the same function from various modules using pytest

description: Test the same function from various modules using pytest


code: admin.site.register(Blog, BlogAdmin)

rawDescription: How to add  Search_fields in Django

description: Add  Search_fields in Django


code:
import itertools

class MyClass(object):
    get_next_id = itertools.count().next

    def __init__(self):
        self.id = self.get_next_id()

rawDescription: How can I determine the number of objects that exist of a specific class?

description: Determine the number of objects that exist of a specific class


code:
data = s.recv(2048)
my_bytes = bytearray(data)

rawDescription: Sending binary data over sockets with Python


code:
Turtle.__init__(self, shape = "circle")
solar_element.__init__(self, Name, Radius, Mass, Colour)

rawDescription: How to use a turtle superclass

description: Use a turtle superclass


code:
search_kw = ('kw: ', 'kw1: ', 'kw3 ', 'kw4: ', 'kw5: ', 'kw6: ', 'kw7: ', 'kw8: ')

keyword = raw_input('Enter your keyword here\n > ')

def add_keyword():
    for word in search_kw:
        # Leave the function, breaking the loop after the first iteration
        return word + keyword

text_file = open("/Users/home/Projects/keyword_file.txt", "w")
# Write search_kw before adding any keywords to it
text_file.write("%s" % search_kw)
text_file.close()

# Only calling add_keyword and the end, and not using the return value
add_keyword()

rawDescription: Trouble Getting a Function Result Written to External .txt Using Python


code:
def average(numbers):
    # We have to do the float(...) so it doesn't do an integer division.
    # In Python 3, it is not necessary.
    return sum(numbers) / float(len(numbers))

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

description: Add elements from a dictonary of lists in python


code: hour = int(line[10:-13])

rawDescription: Parse timestamps containing different lengths Python


code:
from .forms import MyForm
from django.shortcuts import render

def my_view(request):
    ...
    form = MyForm(request.POST or None)
    if request.method == "POST":
        # Have Django validate the form for you
        if form.is_valid():
            # The "display_type" key is now guaranteed to exist and
            # guaranteed to be "displaybox" or "locationbox"
            display_type = request.POST["display_type"]
            ...
    # This will display the blank form for a GET request
    # or show the errors on a POSTed form that was invalid
    return render(request, 'your_template.html', {'form': form})

rawDescription: Django check if checkbox is selected

description: Django check if checkbox is selected


rawDescription: built in method like pandas.sub() that does row wise subtraction

description: Built in method like pandas.sub() that does row wise subtraction


code: int()  # callable

rawDescription: Defaultdict with values defaulted to negative infinity


rawDescription: Text string into lists

description: Text string into lists


code:
df = df.stack().reset_index(1)
df.columns = ['Year', 'Value']

rawDescription: Pandas - Reshape / Transform Dataframe with Multiple Columns into a Single Column of values


code:
phone_number = "1-800-555-1234"
_result = result = float('inf')
for price_list in price_lists:

    _result = min(price_list[prefix_with_length(length, phone_number)] for length in prefix_lengths)
    # _result is the lowest price in that sublist
    result = min(_result, result)
    # result is the lowest so far

rawDescription: getting the prefix of a number in python

description: Getting the prefix of a number in python


code:
example_list = list()
total = 0
max_value = 0

for stored_number in example_list:
    # Ask for input and store in input_response variable
    example_list.append(input_response)

    # Here is where you could add the values to a counter variable,
    # as well as check whether they are the maximum
    total += stored_number
    if stored_number > max:
        max_value = stored_number

# Display results

rawDescription: Python number processing trouble

description: Python number processing trouble


code:
rev = reverse_list('cat')
rev
next(rev)

rawDescription: Creating a function which reverses iterator


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

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


rawDescription: How to speed up recursive call on Python linked list?

description: Speed up recursive call on Python linked list


code:
def tree():
    return collections.defaultdict(tree)

d = tree()
d['js']['title'] = 'Script1'

rawDescription: Update and create a multi-dimensional dictionary in Python


code:
import scipy.interpolate
x = [0, 1, 2, 3]
y = [0, 1, 4, 0]
tck = scipy.interpolate.splrep(x, y)
tck
pp = scipy.interpolate.interpolate.spltopp(tck[0][1:-1], tck[1], tck[2])
pp.coeffs.T

rawDescription: coefficients of spline interpolation in scipy

description: Coefficients of spline interpolation in scipy


code:
def index():
    pass
app.add_url_rule('/', 'index', login_required(index))

rawDescription: Flask-Login extension, enabling login on modules


code:
class Population(dict):
    def __getattr__(self, key):
        return self[key]
    def __setattr__(self, key, value):
        self[key] = value

rawDescription: Object vs. Dictionary: how to organise a data tree?


code:
getattr(a, 'b')
getattr(a, 'x', 'default')

rawDescription: Python Class dynamic attribute access

description: Python Class dynamic attribute access


rawDescription: Strip out html elements using beautiful soup


code: ipcontroller --dictb # or --mongodb or --sqlitedb

rawDescription: IPython.parallel client is hanging while waiting for result of map_async


code:
dictionary={"name":"abc","age":23,"male":True}
new_dictionary={"my_name":"abc","my_age":23,"male":1}
key_map = {"name": "my_name", "age": "my_age"}
all(new_dictionary[key_map.get(k, k)] == v for k, v in dictionary.items())

rawDescription: compare two dictionaries of different keys in python

description: Compare two dictionaries of different keys in python


code:
address = Address(**{
    "city": "CAMBRIDGE",
    "suffix": "",
    "street_name": "FRANKLIN ST",
    "prefix": "",
    "zipcode": "49503",
    "state": "MA",
    "street_num": "127"
})
Buildings(_id=ObjectId(), addresses=[address]).save()

rawDescription: Empty EmbeddedDocument field?

description: Empty EmbeddedDocument field


code:
plot_df = data_df['2008':'2009']

_, ax = plt.subplots()
ax2 = ax.twinx()

plot_df['Bonds'].plot(ax=ax)
plot_df['Bear market'].plot(ax=ax2, style='r--', ylim=[-.1, 1.1])
ax.set_title('Treasuries Performance during SP500 Corrections');

rawDescription: Identifying Extrema in Financial Data using Pandas


code:
def find_operator_right(text):
    position = -1

    for oper in '*/+-':
        index = text.rfind(oper)

        if index > position:
            position = index

    return position

rawDescription: Python: Using find function not in order


rawDescription: Obtaining a Time Zone Locale that is Different from Local Machine


code:
import re

ansi_escape = re.compile(r'\x1b[^m]*m')
ansi_escape.sub('', sometext)

rawDescription: How can I remove the ANSI escape sequences from a string in python

description: Remove the ANSI escape sequences from a string in python


code:
import argparse

parser = argparse.ArgumentParser(prog='mydaemon')
sp = parser.add_subparsers()
sp_start = sp.add_parser('start', help='Starts %(prog)s daemon')
sp_stop = sp.add_parser('stop', help='Stops %(prog)s daemon')
sp_restart = sp.add_parser('restart', help='Restarts %(prog)s daemon')

parser.parse_args()

rawDescription: How to make python argparse mutually exclusive group arguments without prefix?

description: Make python argparse mutually exclusive group arguments without prefix


code: any(x in M for x in L)

rawDescription: efficiently knowing if intersection of two list is empty or not, in python

description: Efficiently knowing if intersection of two list is empty or not, in python


rawDescription: converting string to tuple in python

description: Converting string to tuple in python


code:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.image as mimage
from matplotlib.backends.backend_pdf import PdfPages

_img = mimage.imread('test.jpg')

pdf = PdfPages( 'test.pdf' )
gs = gridspec.GridSpec(2, 4, top=1., bottom=0., right=1., left=0., hspace=0.,
        wspace=0.)

for g in gs:
    ax = plt.subplot(g)
    ax.imshow(_img)
    ax.set_xticks([])
    ax.set_yticks([])
#    ax.set_aspect('auto')

pdf.savefig()
pdf.close()

rawDescription: matplotlib show many images in single pdf page

description: Matplotlib show many images in single pdf page


code:
def get_work(request):
    if request.is_ajax():
        q = request.GET.get('workorder_id', '')
        wo_data = Dim_work_order.objects.filter(base_id__icontains = q )[:1]
        results = []
        if wo_data.exists():
            for x in wo_data:
                x_json = {}
                x_json['success'] = 'success'
                x_json['work_o'] = x.base_id
                x_json['customer_name'] = x.name
                x_json['part_number'] = x.part_id
                x_json['part_rev'] = x.part_rev
                x_json['purch_order'] = x.customer_po_ref
                results.append(x_json)
        else:
            results.append({'success': 'workorder_not_found'})

        data = json.dumps(results)
        mimetype = 'application/json'
        return HttpResponse(data, mimetype)

rawDescription: Cant get ajax response to place nice with python code


code:
data = '''{"ships":{"2":{"name":"Asp","alive":true,"id":2},"3":{"starsystem":{"systemaddress":"670417429889","id":"670417429889","name":"Diaguandri"},"station":{"id":3223343616,"name":"Ray Gateway"},"name":"SideWinder","alive":true,"id":3},"12":{"starsystem":{"systemaddress":"18263140541865","id":"73228","name":"Barnard's Star"},"station":{"id":128147960,"name":"Miller Depot"},"name":"Viper_MkIV","alive":true,"id":12},"13":{"starsystem":{"systemaddress":"673101653409","id":"673101653409","name":"Brestla"},"station":{"id":3224813312,"name":"Roed Odegaard Port"},"name":"Type7","alive":true,"id":13},"14":{"starsystem":{"systemaddress":"673101653409","id":"673101653409","name":"Brestla"},"station":{"id":3224813312,"name":"Roed Odegaard Port"},"name":"SideWinder","alive":true,"id":14}}}'''
import json
data = json.loads(data)
ships = [item['name'] for index, item in data['ships'].items()]
ships

rawDescription: TypeError: string indices must be integers - Parsing JSON


code:
import numpy as np
import pylab as pl

for i in xrange(1, 5):
    pl.subplot(220+i)
    pl.pie([i,2], labels=["a","b"], autopct='%1.1f%%')

fig = pl.gcf()
axe = fig.add_axes([0.4,0.4,0.2,0.2])

pie = pl.pie([1,1], labels=["a","b"])
l = pl.legend(title="sample", loc="center")
for group in pie:
    for x in group:
        x.set_visible(False)

pl.show()

rawDescription: matplotlib - Legend in separate subplot

description: Matplotlib - Legend in separate subplot


code:
import Tkinter
import ttk
root = Tk()
root = Tkinter.Tk()
master = Tkinter.Frame(root)
master.pack()
tree = ttk.Treeview(master, columns=['col A','col B','col C'])
tree.pack()
row1 = tree.insert("",index=0,text="row1",values=['A1','B1','C1'])
row1  # 'I001'
row2 = tree.insert("",index=0,text="row2",values=['A2','B2','C2'])
row2  # 'I002'
row3 = tree.insert("",index=0,text="row3",values=['A3','B3','C3'])
row3  # 'I003'

rawDescription: value tree item python tkinter

description: Value tree item python tkinter


code:
import time

class TimeTravelBase(object):
    def __init__(self):
        self.history = []
        self.blacklist = ['blacklist']

    def __setattr__(self, name, value):
        super(TimeTravelBase, self).__setattr__(name, value)
        if hasattr(self, 'blacklist') and name not in self.blacklist:
            self.history.append({'time': time.time(), 'name': name, 'value': value})

class Gun(TimeTravelBase):
    def __init__(self):
        super(Gun, self).__init__()
        self.blacklist.append('color')
        self.shots_fired = 0
        self.color = "black"

    def fire(self):
        self.shots_fired += 1

if __name__=='__main__':
    gun = Gun()
    gun.color = "red"
    gun.fire()
    from pprint import pprint
    pprint(gun.history)

rawDescription: Monitoring variable access and object creation in Python


code:
import lxml.html as LH
import urllib2
url = 'http://espn.go.com/nba/team/roster/_/name/bos/boston-celtics'
doc = LH.parse(urllib2.urlopen(url))
[LH.tostring(elt) for elt in doc.xpath('//div[@id="my-players-table"]/div//table/tr')]
[elt.text_content() for elt in doc.xpath('//div[@id="my-players-table"]/div//table/tr/td')]

rawDescription: XPath syntax with Python

description: XPath syntax with Python


code: re.findall("[A-Z][a-z]*(?:(?:\\S*&quot\\S*|\\s)+[A-Z][a-z]*){0,3}", "Bonds met Susann ("Sun") Margreth Branco, the mother of his first two children, in {{city-state|Montreal|Quebec}} in August 1987. They eloped in {{city-state|Las Vegas|Nevada}} Barry Bonds")

rawDescription: How to include special part in regex to find English names using python re.findall?

description: Include special part in regex to find English names using python re.findall


rawDescription: Python Special Chars Escape

description: Python Special Chars Escape


code:
if self.fig is None or not pyplot.fignum_exists(self.fig.number):
    self.fig = pyplot.figure()
# self.fig will now be active, either via an old still-open figure or a newly-created one

rawDescription: Control of the figure when using matplotlib


code:
def HandleCustomer(self):
    self.pipeline.send(self)

rawDescription: Implementing Chain of responsibility pattern in python using coroutines


code:
{u'Connection Status': u'LIVE - Active',
 u'Mobile Phone': u'9834900000',
 u'Network Operator / Service Provider': u'AIRTEL',
 u'Service Type / Signal': u'GSM',
 u'Telecom Circle / State': u'MADHYA PRADESH & CHHATISGARH'}

rawDescription: extract only a few lines from output

description: Extract only a few lines from output


rawDescription: plot entire row on pandas

description: Plot entire row on pandas


code:
def _greedy_part(r, sa, la, sb, lb):
    if not r:
        return sa == sb, la, lb;

    if sb < sa:
        # swap both lists in order to always have
        # the "lower sum list" as sa/la
        sb, sa = sa, sb
        lb, la = la, lb

    return _greedy_part(r[1:], sa+r[0], la+r[0:1], sb, lb)

def greedy_part(r):
    return _greedy_part(sorted(r,reverse=True), 0, [], 0, [])

rawDescription: How to recursively check all combinations of list python

description: Recursively check all combinations of list python


code:
pats = [re.compile(date_string+pat) for conf in Conf.values() for pat in conf]

with open('file.txt') as log:
    for line in log:
        if any(pat.match(line) for pat in pats):
            print(line.strip())

rawDescription: Output Print is Slow

description: Output Print is Slow


rawDescription: check if all elements in a list are identical

description: Check if all elements in a list are identical


code:
class Migration(DataMigration):
    def forwards(self, orm):
        #create a Feline for each Cat
        for c in orm['Cat'].objects.all():
            f = orm['Feline']()
            f.id = c.id
            f.save()

        if orm['Feline'].objects.count():
            #if there are any Feline objects, make sure that new ids are allocated after the largest current ID
            last_id = orm['Feline'].objects.latest('id').id
            db.execute('alter sequence animals_feline_id_seq restart with %s;' % (last_id + 1))

    def backwards(self, orm):
        #no need to do anything if migrating backwards
        pass

rawDescription: How to create a superclass (for an existing model) with Django and South

description: Create a superclass (for an existing model) with Django and South


code:
from itertools import product
list(product(range(3), repeat=2))

rawDescription: Python: shortest way to compute cartesian power of list


code:
import re
names = ['g18_84pp_2A_MVP1_GoodiesT0-HKJ-DFG_MIX-CMVP1_Y1000-MIX.txt',
'g18_84pp_2A_MVP2_GoodiesT0-HKJ-DFG_MIX-CMVP2_Y1000-MIX.txt',
'g18_84pp_2A_MVP3_GoodiesT0-HKJ-DFG_MIX-CMVP3_Y1000-MIX.txt',
'g18_84pp_2A_MVP4_GoodiesT0-HKJ-DFG_MIX-CMVP4_Y1000-MIX.txt',
'g18_84pp_2A_MVP5_GoodiesT0-HKJ-DFG_MIX-CMVP5_Y1000-MIX.txt',
'g18_84pp_2A_MVP6_GoodiesT0-HKJ-DFG_MIX-CMVP6_Y1000-MIX.txt',
'g18_84pp_2A_MVP7_GoodiesT0-HKJ-DFG_MIX-CMVP7_Y1000-MIX.txt']

f = lambda x: re.findall('g18_84pp_2A_MVP(.*?)_GoodiesT0(.*?)_MIX(.*?)\.txt', x)

for x in names:
    print(f(x))

rawDescription: How to extract a common name from multipal filenames and delete something I don't want

description: Extract a common name from multipal filenames and delete something I don't want


code:
a=np.arange(5)
b=a
b
b+=5
a
b
b=b+5
b
a

rawDescription: unexpected result in numpy array slicing (view vs copy)

description: Unexpected result in numpy array slicing (view vs copy)


code:
week3 = '------7'
''.join(map(max, zip(week1, week2, week3)))

rawDescription: Merging (logical OR) together the contents of two 'bitmaps' in strings


rawDescription: Most Pythonic way to read csv values into dict of lists


code: pool.map_async(lambda combi: runMyODE(INIT[combi,:], tval, para=PARA[combi,:]), range(numComb), callback=saveResult)

rawDescription: Python's multiprocessing: speed up a for-loop for several sets of parameters, "apply" vs. "apply_async"


code:
[nodes]
appserver-mgr2
appserver-wkr2
appserver-wkr3
appserver-wkr4

rawDescription: Python config parser array sort according to file content sequence


code:
def should_shutdown(battery_level, time_on):
    if battery_level < 4.8:
        if time_on < 60:
            return False
        else:
            return True
    else:
        if battery_level < 4.7:
            return True
        else:
            return False

rawDescription: Boolean operators and Conditions

description: Boolean operators and Conditions


code:
mean_qty = [np.mean([i['qty'] for i in d.values()\
 if i.get('start date') == day] or 0) for day in my_dates]

In [12]: mean_qty
Out[12]: [23.5, 34.0, 0.0]

rawDescription: Average values in nested dictionary

description: Average values in nested dictionary


code:
def mileage():
    filename = input("Please enter the file name: ")

    with open(filename, "r") as fin:
        for line_counter, line in enumerate(fin):
            current_item = line.split()
            print("Leg",line_counter + 1,"---", float(current_item[0])/float(current_item[1]),"miles/gallon")

rawDescription: Why aren't the lists populating in this code?


code:
def findall(word, elements):
    def sub(word, res):
        if word:
            for elt in elements:
                if word.startswith(elt):
                    yield from sub(word[len(elt):], res+[elt])
        else:
            yield res
    yield from sub(word, [])

rawDescription: is recursion the solution ?- Python

description: Is recursion the solution ?- Python


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

rawDescription: List comprehension missing some values versus writing loops


code:
self.matches = [s for s in self.options
                   if s and s.startswith(text)]

rawDescription: How to code autocompletion in python?

description: Code autocompletion in python


code:
def f(j, ls):
    return [ls[:i] + [j] + ls[i:] for i in xrange(len(ls) + 1)]

rawDescription: Insert an element into a list in python

description: Insert an element into a list in python


code:
graph = {}
graph[node_id] = [other_node_id for other_node_id in neighbors(node_id)]

rawDescription: how to represent graphs /trees in python and how to detect cycles?

description: Represent graphs /trees in python and how to detect cycles


code:
import operator
class Comparator:
     def __init__(self,fieldName,compareToValue,my_operator):
         self.op = my_operator
         self.field = fieldName
         self.comparedTo = compareToValue
     def __call__(self,row):
         my_row_val = getattr(row,self.field)
         return self.op(my_row_val,self.comparedTo)

class Row:
    class RowItem:
         def __init__(self,name):
              self.name = name
         def __eq__(self,other):
             return Comparator(self.name,other,operator.eq)
         def contains_(self,other):
             return Comparator(self.name,other,operator.contains)
    val1 = RowItem("val1")
    val2 = RowItem("val2")
    val3 = RowItem("val3")
    val4 = RowItem("val4")
    def __init__(self, val1, val2, val3, val4):
        self.val1 = val1
        self.val2 = val2
        self.val3 = val3
        self.val4 = val4
    def __str__(self):
        return str([self.val1,self.val2,self.val3,self.val4])
    def __repr__(self):
        return str(self)

rawDescription: Error implementing __contains__ (in) for a Python class


code:
# grab our word list as (original_word, word_signature) tuples
# you only have to do this once
words = []
with open('TextFIle.txt', 'r') as f:
    for word in f:
        word = word.strip()
        words.append((word, sorted(word)))

raw_letters = raw_input('Input the letters: ')
search_signature = sorted(raw_letters)

for word, word_signature in words:
    # these are the tiles we're searching over
    # pull it out like this so we can easily pop our way through
    remaining_search = list(reversed(search_signature))

    could_still_match = True
    found = []

    # this is going to look a bit horrible because you're sort of tracking
    # 2 cursors at the same time, incrementing them as you find matches, or not
    for letter in word_signature:

        while remaining_search:
            next_possible = remaining_search.pop()

            # either the possible letter is:
            # - the one we're looking for, that's great, move on to the next letter
            # - less than the one we're looking for, so we can skip it and look at
            #   another letter (by going through the next iteration of the while loop)
            # - greater than the one we're looking for, so this word is a non-match

            if next_possible == letter:
                found.append(next_possible)
                break

            if next_possible < letter:
                continue

            if next_possible > letter:
                could_still_match = False
                break

        # horrible little hack so we can break out of both loops
        if not could_still_match:
            break

    # if we found all the letters in the word then we have a match
    if len(found) == len(word_signature):
        print(word)

rawDescription: searching the strings in a text file in another string

description: Searching the strings in a text file in another string


code:
from pprint import pprint
from urllib.request import urlopen

from bs4 import BeautifulSoup

URL = urlopen("http://www.arrondissement.com/plateau_mont_royal/s1-alimentation/")
soup = BeautifulSoup(URL, "html.parser")

data = {}
divisions = soup.select("ul[name=divisions_form] ul > li")
for division in divisions:
    data[division.a.get_text(strip=True)] = [
        subitem.a.get_text(strip=True) for subitem in division.select(".divisionDDM > li")
    ]

pprint(data)

rawDescription: Beautiful soup select siblings not working


code:
import numpy as np
from pylab import *
x = np.array([1,2,3,4,5,9,6,97987978978977987987897987987])
y=fromstring(x,'uint16')
print('Your condition: ',y&0x8000==1)
time=compress(y&0x8000==1,y)
print('Your test: ',time)
time=compress(y&0x8000==0,y)
print('Test with True values in condition: ',time)

rawDescription: Python/Numpy compress methode issue

description: Python/Numpy compress methode issue


code:
for c in to_zero:
    arr[:, c] = 0

rawDescription: Fast way to update integer indexed slice in numpy


code:
from collections import Counter
aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005}]

[(country, _)] = Counter(x['country'] for x in aList).most_common(1)

print(country)
# Output: japan

rawDescription: Count Occurrences of a Value in a List of Dictionaries


code:
from urlparse import parse_qs, urlparse
parse_qs(urlparse(url).query)['radius'][0]

rawDescription: Parse value from string

description: Parse value from string


code:
def parallel(astart):
    for a in range (astart, astart+10):
        for b in range(500):
            for c in range(500):
                try:
                    if (1+1/a)*(1+1/b)*(1+1/c)==3:
                        print("a=",a ,", b=",b,", c=", c, sep='')
                except ZeroDivisionError:
                    pass

rawDescription: Paralleling without function is possible?


code: all_decisions = filter(lambda x: x[4] != 0, all_decisions)

rawDescription: Removing Line From Python List - All Lines Containing Certain Number


code:
@user_passes_test(type_one_only, login_url='/')
def my_view(request):
    ...

rawDescription: Django related User Model - Permissions and Decorators


code:
while number > 0:
    myList = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']

    myRemainder = number % 16
    #storage   #append remainder in list
    myResult = myList[myRemainder] + myResult
    number = number // 16

print(myResult)

rawDescription: List prints two values instead of one

description: List prints two values instead of one


rawDescription: Count of days of each month from a list of dates python


code:
tpl = '''
    "unaltered": "{{foo}}",
    "replaced": "{{test}}"
'''
a = CustomTemplate(tpl)
a.template
b = a.safe_substitute(replacement_dict)
b

rawDescription: Python template safe substitution with the custom double-braces format


rawDescription: Wikipedia link parsing with regex

description: Wikipedia link parsing with regex


code:
Result: failed
Year is 1
Month is 2
Day is 3
Hour is 1
Minute is 51
Second is 2

Result: passed
Month is 2
Day is 3
Hour is 1
Minute is 51
Second is 2

Result: passed
Year is 1
Month is 2
Day is 3
Hour is 1
Second is 2

Result: failed
Year is 1
Day is 4
Hour is 5
Minute is 3
Second is 2

rawDescription: Extracting multiple variables from a changing string in bash


code:
from collections import Counter
c = Counter()
A = [(2, 2, 0), (1, 5, 0), (6, 8, 0), (2, 2, 2) ]
for a in A:
    c[a[:2]] += a[2]
B = [list(k) + [v] for k,v in c.iteritems()]

rawDescription: Comparing rows elements in python

description: Comparing rows elements in python


code:
from itertools import *
def ntuples(lst, n):
    return izip(*[chain(islice(lst,i,None), islice(lst,None,i)) for i in range(n)])

rawDescription: Iterate over pairs in a list (circular fashion) in Python


code:
def _iter():
    yield 2
    n = 3
    while True:
        yield n
        n = n + 2

def primes():
    it = _iter()
    while True:
        n = next(it)
        yield n
        it = itertools.ifilter(lambda x, n=n: x%n, it)

rawDescription: Ifilter together with lambda expression

description: Ifilter together with lambda expression


code:
def process_df(df):
    # swap A and B
    df.columns = ['B', 'A']
    df[['B', 'A']] = df[['A', 'B']]

rawDescription: How to modify a pandas DataFrame in a function so that changes are seen by the caller?

description: Modify a pandas DataFrame in a function so that changes are seen by the caller


code:
import re
text = "hello world. It's nice."
re.sub(r'(?<=[.?!])( +|\Z)', r'\n', text)
text = "His thoughts trailed away... His heart wasn't in it!"
re.sub(r'(?<=[.?!])( +|$)', r'\n', text)

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


code:
result = urllib2.urlopen('http://127.0.0.1:8000/tasks/nlp/process/',
                         urllib.urlencode(post_data))

rawDescription: Django POST request to my view from Pyres worker - CSRF token


code:
class MyClass(object):
    pass

myObj = MyClass()
NewClass = myObj.__class__
newObj = NewClass()
myObj, newObj

rawDescription: class name as variable in python

description: Class name as variable in python


code:
{k:v for k,v in P.items() if k not in E}
{k:v for k,v in E.items() if k not in P}

rawDescription: How do I find the keys in one dictionary that do not have a counterpart in another dictionary?

description: Find the keys in one dictionary that do not have a counterpart in another dictionary


code:
def makeBaby(mommy, daddy):
   """Execute the miracle of life.

   Parameters
   ----------
   mommy : description of mommy
   daddy : description of daddy

   Returns
   -------
   baby : mommy + daddy

   """
   return mommy + daddy

rawDescription: Documenting a Python function with a docstring that is both readable in raw form and produces good sphinx output


rawDescription: Sort list B by the sort of list A?

description: Sort list B by the sort of list A


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


code:
import urllib
from bs4 import BeautifulSoup

url = 'http://biology.burke.washington.edu/conus/recordview/description.php?ID=1l9l0l421l55llll&tabs=21100111&frms=1&pglimit=A&offset=&res=&srt=&sql2='

html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
tables = soup.find_all('table')
#print(tables)

rawDescription: Extracting table info using BeautifulSoup (bs4)


rawDescription: python how to convert datetime dates to decimal years

description: Python how to convert datetime dates to decimal years


rawDescription: How can I make an rx.py Observable from a stream such as stdin?

description: Make an rx.py Observable from a stream such as stdin


code:
def generate_model_entries(models):
    return dict(zip(code_names(models), entries(models)))

d = generate_model_entries(appmodels)

rawDescription: How to add multiple dictionaries together from a dictionary generator to create single collated python dictionary

description: Add multiple dictionaries together from a dictionary generator to create single collated python dictionary


code:
import unittest
from algorithms import sorting

class Test( unittest.TestCase ):

  def testMergesort( self ):
      A = [8, 5, 3, 1, 9, 6, 0, 7, 4, 2, 5]
      sorting.mergesort( A )
      for i in range( 1, len( A ) ):
          if A[i - 1] > A[i]:
            self.fail( "mergesort method fails." )

rawDescription: Merge sort python infinite loop

description: Merge sort python infinite loop


rawDescription: How do I generate a list like the one in the example using a non-inclusive range? (Python)

description: Generate a list like the one in the example using a non-inclusive range? (Python)


code:
def onchange_fullname(self, cr, uid, ids, fname, lname, context=None):

    fullname = '%s %s' % (fname,lname)
    # It will add fname(First Name) and lname(Last Name) and assign to  fullname
    return {'value':{'fullname':fullname}}

rawDescription: How to make a user automatically from a class in OpenERP?

description: Make a user automatically from a class in OpenERP


code:
self.example_var = StringVar()
self.example_var.set(selectedetails[1])
self.example_txt = Entry(frame3,textvariable=self.example_var)
self.example_txt.grid(row=1,column=1)

rawDescription: Selecting data from a treeview

description: Selecting data from a treeview


code:
def myReduce(f, L):
    arg1 = L[0]
    for arg2 in L[1:]:
        arg1 = f(arg1, arg2)
    return arg1

rawDescription: Alternating sum of integers in Python using lambda


code:
# the txt file I'm trying to extract last words from and write strings into a file
#Hello:there:buddy
#How:areyou:doing
#I:amFine:thanks
#thats:good:I:guess

rawDescription: Write strings to another file

description: Write strings to another file


code: return Response('OK')

rawDescription: Use AJAX to upload a file, process, and return a result to Javascript using Flask


code:
text = input('Insert String: ')

from string import punctuation
from collections import Counter
def mwl(text):
    st = set(punctuation)
    # remove all punctuation and make every letter lowercase
    filtered = (ch.lower() for ch in text if ch not in st)
    # make counter dict from remaining letters and return the most common
    return Counter(filtered).most_common()[0][0]

rawDescription: Most Common letter in a string

description: Most Common letter in a string


code:
for name in listname[::-1]:
    print(name)

rawDescription: How to loop over a list incrementally

description: Loop over a list incrementally


rawDescription: Why does setattr fail on a bound method

description: Why does setattr fail on a bound method


code:
def your_function1(fp):
    # a bunch of code
    browser = webdriver.Firefox(firefox_profile = fp)

def your_function2(fp):
    # a bunch of code
    browser = webdriver.Firefox(firefox_profile = fp)

# etc

rawDescription: Is there a way to pass an instance of a Selenium Webdriver profile into several functions with Python


code:
@register.filter
def selected_labels(form, field):
    return [label for value, label in form.fields[field].choices if value in form[field].value()]

rawDescription: Django: Display values of the selected multiple choice field in a template


code:
def searchfun(d, queries):
    return [(key,d[key]) for key in queries if key in d]

rawDescription: Returning key of value found in dictionary using 'value in dict.values()'


code: ast.parse('''a and (b and c)''').body[0].value.values

rawDescription: When has ast.BoolOp more than two values?


rawDescription: Unexpected output for numpy.arange with step size of 0.005


code: my_series = pd.Series(my_dict)

rawDescription: Fastest way to sorting a corpus dictionary into an OrderedDict - python


code:
if GO_TO_MAX_SPEED_CONDITION:
    GO_TO_MAX_SPEED = True
if STOP_GOING_TO_MAX_SPEED_CONDITION:
    GO_TO_MAX_SPEED = False

rawDescription: Need help detecting a change in a variable outside of a while loop


code:
df = pd.DataFrame({'Value1': Value1, 'Value2': Value2, 'Value3':Value3}, index=Time)
df.head()

rawDescription: Python: Creating a multicolumn serie with Pandas


code:
values = [
    {'text': 'apple test', 'user': 'A'},
    {'text': 'test orange fruit', 'user': 'B'}
  ]

init = { 'apple': [], 'orange fruit': [], 'bunch of bananas': [] }

def aggregate(agg,x):
  for k in agg:
    if k in x['text']:
      agg[k].append(x)
  return agg

counts = reduce(aggregate, values, init)

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


code: dfts = df.set_index('date_time')

rawDescription: Group by multiple time units in pandas data frame


code:
import collections

class CountedOrderedDict(collections.OrderedDict):
    def __init__(self, *args, **kwargs):
        self.counter = collections.Counter()
        super(CountedOrderedDict, self).__init__(*args, **kwargs)

    def __delitem__(self, key):
        super(CountedOrderedDict, self).__delitem__(key)
        self.counter[key[1]] -= 1

    def __setitem__(self, key, value):
        if key not in self:
            self.counter[key[1]] += 1

        super(CountedOrderedDict, self).__setitem__(key, value)

rawDescription: Get key count from OrderedDict where key is a tuple


code:
result = []
for a in iterable_a:
    for b in iterable_b:
        result.append((a, b))

rawDescription: Understanding the map function

description: Understanding the map function


code:
months = set(month.lower() for month in ("January", "February", "March", "April",
                                         "May", "June", "July"))
while True:
    answer = raw_input("Month? ")
    if answer.lower() in months: break
    print("Sorry, didn't recognize your answer, try again")

rawDescription: How to check if a variable matches any item in list using the any function?

description: Check if a variable matches any item in list using the any function


code:
df1 = pd.DataFrame(np.random.rand(1000,10))
df2 = pd.DataFrame(np.random.rand(1000,10))
result = (df1*df2).sum(axis=1)

rawDescription: Applying np.dot to each row of two DataFrames


code:
mylist = [
(1, '/path/here', 'path/here/again'),
(2, 'a/different/path/here', 'another/path/here')
]

rawDescription: Pretty print Python Lists

description: Pretty print Python Lists


code: b = spread(a,1,j)

rawDescription: broadcast an array to different shape (adding "fake" dimensions)

description: Broadcast an array to different shape (adding "fake" dimensions)


code:
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')

u = np.linspace(-1, 2, 60)
v = np.linspace(0, 2*np.pi, 60)
U, V = np.meshgrid(u, v)

X = U
Y1 = (U**2 + 1)*np.cos(V)
Z1 = (U**2 + 1)*np.sin(V)

Y2 = (U + 3)*np.cos(V)
Z2 = (U + 3)*np.sin(V)

ax.plot_surface(X, Y1, Z1, alpha=0.3, color='red', rstride=6, cstride=12)
ax.plot_surface(X, Y2, Z2, alpha=0.3, color='blue', rstride=6, cstride=12)
plt.show()

rawDescription: Ploting solid of revolution in Python 3 (matplotlib maybe)


code:
from __future__ import print_function

import csv
import requests

CSV_URL = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'

with requests.Session() as s:
    download = s.get(CSV_URL)

    decoded_content = download.content.decode('utf-8')

    cr = csv.reader(decoded_content.splitlines(), delimiter=',')
    my_list = list(cr)
    for row in my_list:
        print(row)

rawDescription: Use python requests to download CSV

description: Use python requests to download CSV


code:
from pyspark.sql.functions import input_file_name, regexp_extract

df_with_year = (df.withColumn(
    "year",
    regexp_extract(input_file_name(), "[1-2][0-9]{3}", 0).cast("int")))

df_with_year.show()
## +--------+------+-----+----+
## |    name|gender|count|year|
## +--------+------+-----+----+
## |John Doe|     M|    1|1890|
## |Jane Doe|     F|    3|1870|
## +--------+------+-----+----+

df_with_year.write.jdbc(...)

rawDescription: Exporting text files to PostgreSQL using Spark - Automation


code: total_interval = sum(intervals, timedelta(0, 0, 0))

rawDescription: Sum elements of a list (datetime) in one value


code:
with open(sys.argv[1]) as inputfile, open("result.txt","w") as outputfile:
    name = None
    investment_id = max_investment = 0
    for line in inputfile:
        if not line.strip(): continue  # skip empty lines

        if not line[:1].isdigit():  # name
            if name and investment_id:
                # write previous name
                outputfile.write('{} {}\n'.format(name, investment_id))
            name = line.strip()
            investment_id = max_investment = 0

        else:
            id, investment = [int(i) for i in line.split()]
            if investment > max_investment:
                max_investment = investment
                investment_id = id

    if name and investment_id:
        # write last name
        outputfile.write('{} {}\n'.format(name, investment_id))

rawDescription: Selecting specific pieces of information from a text file and converting them to an array/list in python


code: idx = pd.IndexSlice

rawDescription: What is an efficient way to slice a Pandas Series with a MultiIndex along multiple dimensions?


code: gamescache = list(Game.objects.all())

rawDescription: Django: Saving old QuerySet for future comparison


rawDescription: Suggestions for passing large table between Python and C#


code:
name = {'$exists': True} if name == '*' else name
age = {'$exists': True} if age == '*' else age

info = list(db.test.find({'name': name, 'age': age}))

rawDescription: How to use '*' in Mongodb?

description: Use '*' in Mongodb


code:
modules = []

while True:
        moduleName = raw_input("Please enter module name: ")
        if moduleName == "-1":
            break
        grade = raw_input ("Please enter students grade for " + moduleName+": ")
        modules.append((moduleName, grade))

rawDescription: Saving Raw_input to a list when used in a While Loop


code:
tags = soup.findAll(['script', 'form'])
tags.extend(soup.findAll(id="footer"))

for tag in tags:
    tag.extract()

rawDescription: Can I combine two 'findAll' search blocks in beautifulsoup, into one?

description: Combine two 'findAll' search blocks in beautifulsoup, into one


rawDescription: Python collections of non-base type?

description: Python collections of non-base type


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

def generate_data_heat_map(data, x_axis_label, y_axis_label, plot_title, file_path, box_plot=False):
    plt.figure()
    gs = gridspec.GridSpec(2, 1,height_ratios=[1,4])
    if box_plot:
        plt.subplot(gs[0])
        plt.boxplot(data.data.flatten(), 0, 'rs', 0)
        plt.subplot(gs[1])

    plt.title(plot_title)
    fig = plt.imshow(data.data, extent=[0, data.cols, data.rows, 0])
    plt.xlabel(x_axis_label)
    plt.ylabel(y_axis_label)
    plt.colorbar(fig)
    plt.savefig(file_path + '.png')
    plt.close()

class Data(object):
    def __init__(self, rows=200, cols=300):
        # The data grid
        self.cols = cols
        self.rows = rows
        # The 2D data structure
        self.data = np.zeros((rows, cols), float)

    def randomise(self):
        self.data = np.random.rand(*self.data.shape)

data = Data()
data.randomise()
generate_data_heat_map(data, 'x', 'y', 'title', 'heat_map', box_plot=True)

rawDescription: Matplotlib boxplot + imageshow (subplots)


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

description: Make a variable created inside a function become global


code:
def g(tup):
    return f(*tup)

rawDescription: Python multiprocessing a function with several inputs


code:
TIME_FORMAT = "%b %d"
f_str = obj.date.strftime(TIME_FORMAT)

rawDescription: python django: convert the postgresql timestamp to datetime

description: Python django: convert the postgresql timestamp to datetime


code:
bld.new_task_gen (
  features = "subst",
  source= "versionfile.ver",
  target= "versionfile.out",
  VERSION = bld.env['VERSION'],
  DATADIR = bld.env['DATADIR'])

rawDescription: Waf: How to output a generated file?

description: Waf: How to output a generated file


code:
import sys
sys.stdin.encoding

rawDescription: Python Unicode strings and the Python interactive interpreter


code: random.triangular(0, length, 0)

rawDescription: Choose random element in list influenced by its position


code:
d = defaultdict(int)
d[10] = 3+4j
d
d[30]
d["fred"]

rawDescription: How to obtain the type of the values in a defaultdict

description: Obtain the type of the values in a defaultdict


rawDescription: Decompose list of lists into single list with non-iterable list elements


code:
import git
repo = git.Repo('.')

rawDescription: How do you merge the master branch into a feature branch with GitPython?

description: Merge the master branch into a feature branch with GitPython


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


code: Foo.aMethod = deco(Foo.aMethod.im_func)

rawDescription: Decorate subclass method

description: Decorate subclass method


code:
inp = ''
desired = 'hello'
while inp != desired:
    inp = raw_input('Enter a greeting: ')

rawDescription: I can't seem to understand loops

description: I can't seem to understand loops


code:
class LimitedJobForm(forms.ModelForm):

    jobnum = forms.CharField(label='Job Number')

    class Meta:
        model = Job
        fields = ['jobnum', 'client', 'status']  # no 'color' field

rawDescription: Set form value without user input

description: Set form value without user input


rawDescription: How can I disable "selection by clicking " on GTK+3 treeview

description: Disable "selection by clicking " on GTK+3 treeview


rawDescription: Unpickle sometimes makes blank objects

description: Unpickle sometimes makes blank objects


code:
def foo(): pass
foo = decorator(foo)

rawDescription: Python dynamic decorators - why so many wraps?


code: user_likes.exists() # user has liked an article

rawDescription: check for existence and active state in django filter

description: Check for existence and active state in django filter


code:
import itertools as it
filename='test.dat'

with open(filename,'r') as f:
    for key,group in it.groupby(f,lambda line: line.startswith(':Entry')):
        if not key:
            group = list(group)
            print(group)

rawDescription: Splitting large text file by a delimiter in Python


rawDescription: Split a string into a list in Python

description: Split a string into a list in Python


code:
from inspect import isfunction

def isalambda(v):
    return isfunction(v) and v.__name__ == '<lambda>'

rawDescription: What is islambda function in python

description: What is islambda function in python


code:
character.x += x_amount
character.y += y_amount

rawDescription: Pygame move object position from one point to another at constant speed


code:
cat_sorted = [
    [e for i, e in sorted(enumerate(cat[0]), key=lambda p: cat[2][p[0]])],
    [e for i, e in sorted(enumerate(cat[1]), key=lambda p: cat[2][p[0]])],
    sorted(cat[2])
]

rawDescription: Python - Sorting elements in a list of lists


code:
import json, atexit

def persist_to_file(file_name):

    try:
        cache = json.load(open(file_name, 'r'))
    except (IOError, ValueError):
        cache = {}

    atexit.register(lambda: json.dump(cache, open(file_name, 'w')))

    def decorator(func):
        def new_func(param):
            if param not in cache:
                cache[param] = func(param)
            return cache[param]
        return new_func

    return decorator

rawDescription: memoize to disk - python - persistent memoization

description: Memoize to disk - python - persistent memoization


rawDescription: python/pandas:need help adding double quotes to columns

description: Python/pandas:need help adding double quotes to columns


code:
['this is an average string' 'and another one'
 "let's push even more with a third string"]

rawDescription: How to pass a list of strings to an opencl kernel using pyopencl?

description: Pass a list of strings to an opencl kernel using pyopencl


code:
i1, i2 = itertools.tee(iterator)
next(i2, None)
for thing1, thing2 in itertools.izip(i1, i2):
    whatever()

rawDescription: Does Python copy references to objects when slicing a list?


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


code:
def faster(N):
    # pad on each side
    arr = np.zeros(N+2)
    arr[0] = arr[-1] = -1 # ignore edges
    while True:
        # zeros left
        zero_locations = np.where(arr == 0)[0]
        if not len(zero_locations):
            break # we're done
        np.random.shuffle(zero_locations)
        for zloc in zero_locations:
            if arr[zloc] == 0:
                arr[zloc-1:zloc+2] = [2, 1, 2]
    return arr[1:-1] # remove edges

rawDescription: Speeding up this Python code for large input


rawDescription: find common data python

description: Find common data python


code: dict.fromkeys(range(2), object())

rawDescription: Unwanted behaviour from dict.fromkeys

description: Unwanted behaviour from dict.fromkeys


code:
from Tkinter import *

class MyFrame(Frame):
    def __init__(self, root):
        Frame.__init__(self, root)
        self.parent = root
        self.configure(width=300,height=300)
        self.pack()
        self.bind("<Motion>", self.onmotion)

    def onmotion(self, event):
        self.parent.title("Mouse at %s,%s"%(event.x, event.y))

root = Tk()
frame = MyFrame(root)
root.title("Event test")
root.mainloop()

rawDescription: How to access external object within event handler?

description: Access external object within event handler


code:
list_of_nums = range(0, len(list))  # [0, 1, 2, 3, ...]
for i in list_of_nums:
    j = i[counter]
    ...

rawDescription: Updating range() function in for loop

description: Updating range() function in for loop


rawDescription: Search and sort through dictionary in Python


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

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


rawDescription: write csv row (from within for loop) out to csv file without using python csv module

description: Write csv row (from within for loop) out to csv file without using python csv module


code:
setup (
    name = 'MyProject',
    ext_modules = cythonize(["*.pyx"]),
)

rawDescription: How to compile and link multiple python modules (or packages) using cython?

description: Compile and link multiple python modules (or packages) using cython


code:
import pandas as pd
my_file = 'file_name'
df = pd.read_csv(my_file)

rawDescription: Python Import data dictionary and pattern


code:
df = pd.read_csv('myfile.csv', index_col=False, header=None)
df2 = pd.DataFrame(pd.DataFrame(df[1]).T)
header = df[0]
header.name = None
df2.columns = header
df2.index = [0]

rawDescription: Read a csv file with column name as one column cell values


code:
import ast
a = ast.literal_eval("{'a' : '1', 'b' : '2'}")
a
type(a)

rawDescription: Python Dictionary Stored as String in List


code:
def find_all(haystack, needle):
    pos = -1
    try:
        while True:
            yield haystack.index(needle, pos+1)
    except ValueError:
        pass

def agent_loc(a_maze):
    coor_list = str()
    for row, i in enumerate(a_maze):
         for column in find_all(i, "E"):
             coor_list = coor_list + str(row) + ";" + str(column) + "|"
    print(coor_list)

rawDescription: (Python) Index stops after finding one element in the row


rawDescription: pyparsing - defining keywords - compare Literal, Word, Keyword and Combine

description: Pyparsing - defining keywords - compare Literal, Word, Keyword and Combine


rawDescription: How to make List from Numpy Matrix in Python

description: Make List from Numpy Matrix in Python


code:
class ProfileImageField(ImageField):

    def to_internal_value(self, data):
       converted = ImageHandler().convertImage(data)
       return super(ProfileImageField,self).to_internal_value(converted)

rawDescription: Overriding Django-Rest-Framework serializer is_valid method


code:
for i in range(0,int(files)):
    fig= plt.figure()
    plt.grid(True)
    ...

rawDescription: Matplotlib: Saved files in a loop aren't the same as in show()


rawDescription: How to find which key is from which dictionary in python

description: Find which key is from which dictionary in python


code:
def replace_FOO(m):
    if m.group().startswith("'"):
        return m.group().replace("FOO", "XXX")

    return m.group()

string = "' FOO ' abc 123 ' def FOO ghi 345 ' FOO '' FOO ' lmno 678 FOO '"

output = re.sub(r"'[^']*'|[^']+", replace_FOO, string)

rawDescription: Python regex to replace a string if not surrounded by single quotes


code:
def walk(gen, callbacks):
    for item in gen:
        for f in callbacks:
            f(item)

rawDescription: Multiple clients for a Python generator?

description: Multiple clients for a Python generator


code:
b = np.ma.masked_array([1, 2, 3, 4], mask=[True, True, True, True])
b

rawDescription: Most efficient way to determine if a numpy masked array contains any non-masked values?


code:
import pandas as pd
import datetime as DT

dfA = pd.DataFrame(
    {'case' : pd.Series(["A","B","B","B"]),
     'date' : pd.Series([DT.datetime(2014, 3, 2), DT.datetime(2014, 2,2),
                         DT.datetime(2014, 3, 1), DT.datetime(2014, 2, 8)]),
     'x' : pd.Series([1,2,3,4])})

dfB = pd.DataFrame({'case':list('ABB'), 'y':list('TTF')})

result = pd.merge(dfA, dfB, on=['case'], how='outer')
result.sort(['case','y','x'], ascending=[True,False,True], inplace=True)
print(result)

rawDescription: compare all x with in a group in dfA to all possible y's in the same group in dfB using pandas python

description: Compare all x with in a group in dfA to all possible y's in the same group in dfB using pandas python


code:
if command == "exit":
   a = 1
   break

rawDescription: Break out of double while loops?

description: Break out of double while loops


code:
merc
merc.m
merc.p

rawDescription: Manipulating a list to increase code efficiency, struggling


code:
from django import template

register = template.Library()

@register.filter(name='private')
def private(obj, attribute):
    return getattr(obj, attribute)

rawDescription: Django Templates and MongoDB _id

description: Django Templates and MongoDB _id


code: label.configure(text="This is different text")

rawDescription: Python - TKinter - Editing Widgets

description: Python - TKinter - Editing Widgets


code:
form = LaunchForm()
return render(request, 'my_template.html', {'form': form})

rawDescription: Django form as_table(), as_p() methods not working


rawDescription: Python : Match a dictionary value with another dictionary key


code:
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base

metadata = MetaData(create_engine(database_url), reflect=True)
Base = declarative_base(metadata)

class Order(Base):
    __table__ = metadata.tables['orders']

class OrderLine(Base):
    __table__ = metadata.tables['orderlines']
    order = relation(Order, backref='lines')

rawDescription: Entity Framwework-like ORM NOT for .NET

description: Entity Framwework-like ORM NOT for .NET


code:
edges = {}
with open('input2', 'r') as edge_data:
    for row in edge_data:
        col = row.strip().split()
        edges[col[0], col[1]] = col[2], col[3], col[4]

rawDescription: Append or create and new Dictionary

description: Append or create and new Dictionary


code:
class SimpleAppTk(Tkinter.Frame):
    def __init__(self,*args,**kwargs):
        Tkinter.Frame.__init__(self,*args,**kwargs)

        self.filelist=[]  #get your files here
        #it probably would look like:
        #for d in os.listdir(parentDir):
        #    self.filelist.extend(glob.glob(os.path.join(parentDir,d,'*.jpg'))
        self.index=-1
        self.setup()
        self.display_next()

    def setup(self):
        self.Label=Tkinter.Label(self)
        self.Label.grid(row=0,column=0)
        self.Button=Tkinter.Button(self,text="Next",command=self.display_next)
        self.Button.grid(row=0,column=1)

    def display_next(self):
        self.index+=1
        try:
            f=self.filelist[self.index]
        except IndexError:
            self.index=-1  #go back to the beginning of the list.
            self.display_next()
            return

        #create PhotoImage here
        photoimage=...
        self.Label.config(image=photoimage)
        self.Label.image=photoimage

if __name__ == "__main__":
   root=Tkinter.Tk()
   my_app=SimpleAppTk(root)
   my_app.grid(row=0,column=0)
   root.mainloop()

rawDescription: How to loop through subfolders showing jpg in Tkinter?

description: Loop through subfolders showing jpg in Tkinter


code: url(r'^quiz_score/$', quiz_score)

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


code:
new_container = []
for row in raw:
   if rowlen == 13:  # This is true only for csv files I want to shorten
       new_container.append(row[0:8])  # we just append your slice to the new_container each iteration
       rowlen = 8

rawDescription: Remove unwanted columns from CSV file

description: Remove unwanted columns from CSV file


rawDescription: Transform slow pandas iterrows into apply


code: H = sp.csr_matrix(H)

rawDescription: How to change elements in sparse matrix in Python's SciPy?

description: Change elements in sparse matrix in Python's SciPy


code:
def weighted_random_choice(choices):
    max = sum(choices.values())
    pick = random.uniform(0, max)
    current = 0
    for key, value in choices.items():
        current += value
        if current > pick:
            return key

rawDescription: Fitness proportionate selection (roulette wheel selection) in Python


code: ascending

rawDescription: Find a key's value from a list of dictionaries python


code:
print(hex(se[0]))
print(hex(se[1]))

rawDescription: How to see the bytes of a Python3 <class 'bytes'> object?

description: See the bytes of a Python3 <class 'bytes'> object


rawDescription: Convert Pandas DatetimeIndex to fractional day of year


code:
Lines = {}

for line in File1:
    Lines[int(line)] = True

rawDescription: write specific lines from a file python

description: Write specific lines from a file python


code:
def upload_one(filename):
    """ This function uploads one file.
        Perhaps is a a wrapper to your Popen call? """

rawDescription: Python FTP Upload Multiple Files at Once


code: categoria = serializers.SlugRelatedField(read_only=True, slug_field='titulo')

rawDescription: JSON from django rest Framework

description: JSON from django rest Framework


code: result = var1 if var1 not in [None,False] else var2  # FAIL! DOES NOT WORK!!!!!!

rawDescription: When zero is not None or not False but digit 0


code:
def analyzer(data):
    vocab = build_vocab(training_data)
    cl = train_classifier(vocab, trianing_data)
    results = cl.predict(data)
    results = format_results_to_dict()
    return results

rawDescription: Python-Flask: Pass data to machine learning python script and get results back


code:
class Expr:
    '''An Expr can be built with two different calls:
           -Expr(number) to build a literal expression
           -Expr(a, op, b) to build a complex expression.
            There a and b will be of type Expr,
            and op will be one of ('+','-', '*', '/').
    '''
    def __init__(self, *args):
        if len(args) == 1:
            self.left = self.right = self.op = None
            self.value = args[0]
        else:
            self.left = args[0]
            self.right = args[2]
            self.op = args[1]
            if self.op == '+':
                self.value = self.left.value + self.right.value
            elif self.op == '-':
                self.value = self.left.value - self.right.value
            elif self.op == '*':
                self.value = self.left.value * self.right.value
            elif self.op == '/':
                self.value = self.left.value // self.right.value

    def __str__(self):
        '''It can be done smarter not to print redundant parentheses,
           but that is out of the scope of this problem.
        '''
        if self.op:
            return "({0}{1}{2})".format(self.left, self.op, self.right)
        else:
            return "{0}".format(self.value)

rawDescription: Generate equation with the result value closest to the requested one, have speed problems


rawDescription: Create a list of Hex value in python

description: Create a list of Hex value in python


code: tup = tuple([(element.foo, element.bar) for element in alist])

rawDescription: Use list comprehension to build a tuple

description: Use list comprehension to build a tuple


rawDescription: Convert AWK regex to Python script

description: Convert AWK regex to Python script


code:
devnul = open(os.devnull,"w") #this is multiplatform, rather than hardocding "/dev/null"
ps = sb.Popen(cmd,stderr=devnul)
#....
#some other code here, eventually kill the process maybe
#....
devnul.close()

rawDescription: running ffmpeg from Popen inside (twisted) timer.LoopingCall() stalls

description: Running ffmpeg from Popen inside (twisted) timer.LoopingCall() stalls


code:
# you could make range as big as you like..
choices = [str(i) for i in range(1, 11)] #['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

while menu_choice not in choices:
    print("That input wasn't valid. Please try again.\n")
    menu_Choice = input("\n")

rawDescription: Is there a way to make a "Not a number" if statement in Python?


code:
class my_defaultdict(dict):
    def __missing__(self, key):
        return '<unknown %s>' % key

rawDescription: Python "switch statement" and string formatting


rawDescription: how to access elements by path?

description: Access elements by path


code:
import datetime
now = datetime.datetime.now()
now.strftime("%Y-%m-%d")
datetime.datetime.now().date().isoformat()

rawDescription: How do I Auto-Name Each Subsequent .CSV File of Scraped Date?


code:
def trans(s):
    x = ""
    a = False
    for j in range(len(s)):
        if s[j] == "*":
            a = not a  # change state; false to true and true to false
            continue  # no need to add the star to the output
        if a:
            x += s[j].upper()
        else:
            x += s[j]
    return x

rawDescription: Upper case between a char python

description: Upper case between a char python


code:
file = 'foo_bar_1_10.asc.gz'
pieces = file.split('.')
pieces

rawDescription: strip text to create list and compare 2 similar lists

description: Strip text to create list and compare 2 similar lists


rawDescription: Python list giving different order

description: Python list giving different order


code:
import json
with open("Tamaguchis.txt","r") as file:
    dictionary = json.loads(file.read())

rawDescription: Exporting a dictionary into a text-file

description: Exporting a dictionary into a text-file


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

# make some data
a = np.random.randn(10,10)

# mask some 'bad' data, in your case you would have: data == 0
a = np.ma.masked_where(a < 0.05, a)

cmap = plt.cm.OrRd
cmap.set_bad(color='black')

plt.imshow(a, interpolation='none', cmap=cmap)

rawDescription: Python color map but with all zero values mapped to black


code:
import os

for filename in glob(os.path.join(WorkingDirectory, '*.jpg')):
    ...

rawDescription: Python - Run a bash script for all files in a directory


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

rawDescription: Class Inheritence Naming in Python

description: Class Inheritence Naming in Python


code:
#include "wx/wxPython/wxPython.h"
#include "wx/wxPython/wxPython_int.h"

rawDescription: Python Callback from SWIG PyObject_Call Segfault


rawDescription: Solving system using linalg with constraints


code:
for i in itertools.product(range(0,100), repeat=3):
    #do stuff with i
    list.append(run(i[0],i[1],i[2]))

rawDescription: Nested for loops in Python compared to map function


code:
from itertools import chain

lis = list(chain.from_iterable(shakespeare))

# output:
# [
#   ['[', 'The', 'Tragedie', 'of', 'Hamlet', 'by', 'William', 'Shakespeare', '1599', ']'],
#   ['Actus', 'Primus', '.'],
#   ['[', 'The', 'Tragedie', 'of', 'Macbeth', 'by', 'William', 'Shakespeare', '1603', ']'],
#   ['Actus', 'Primus', '.'],
#   ['[', 'The', 'Tragedie', 'of', 'Julius', 'Caesar', 'by', 'William', 'Shakespeare', '1599', ']'],
#   ['Actus', 'Primus', '.']
# ]

rawDescription: Python :: NLTK concatenating list of sentences


rawDescription: Pandas: rare data form disrupts normal statistical analysis


rawDescription: python split and evaluate

description: Python split and evaluate


code: [instances_by_purpose.setdefault(i.tags.get('purpose'), []).append(i.ip_address) for i in instances]

rawDescription: Getting only unique tags from a set of tagged ec2 instances


code:
def getRoots(aNeigh):
    def findRoot(aNode,aRoot):
        while aNode != aRoot[aNode][0]:
            aNode = aRoot[aNode][0]
        return (aNode,aRoot[aNode][1])
    myRoot = {}
    for myNode in aNeigh.keys():
        myRoot[myNode] = (myNode,0)
    for myI in aNeigh:
        for myJ in aNeigh[myI]:
            (myRoot_myI,myDepthMyI) = findRoot(myI,myRoot)
            (myRoot_myJ,myDepthMyJ) = findRoot(myJ,myRoot)
            if myRoot_myI != myRoot_myJ:
                myMin = myRoot_myI
                myMax = myRoot_myJ
                if  myDepthMyI > myDepthMyJ:
                    myMin = myRoot_myJ
                    myMax = myRoot_myI
                myRoot[myMax] = (myMax,max(myRoot[myMin][1]+1,myRoot[myMax][1]))
                myRoot[myMin] = (myRoot[myMax][0],-1)
    myToRet = {}
    for myI in aNeigh:
        if myRoot[myI][0] == myI:
            myToRet[myI] = []
    for myI in aNeigh:
        myToRet[findRoot(myI,myRoot)[0]].append(myI)
    return myToRet

rawDescription: Python connected components

description: Python connected components


code:
for header in soup.select('div h3'):
    next_div = header.find_next_sibling('div')

rawDescription: how to grab alternating child tags in python beautifulsoup

description: Grab alternating child tags in python beautifulsoup


code:
import pandas as pd
import pandas.rpy.common as com

mtcars = com.load_data('mtcars')
mtcars['n'] = mtcars.groupby("cyl")['cyl'].transform('count')
print(mtcars.head())

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


code:
...
url(r'^(?P<pk>[-\w]+)/result/(?P<url>.*)$', DynProxyView.as_view(),name='result'),
...

rawDescription: Dynamically serving django docker containers


code:
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()

class Contact(db.Model):
    ...

rawDescription: Flask-SQLAlchemy not creating tables using create_all()


code:
ilocs_window = pd.rolling_apply(df, window=5, func=lambda x: x.argmin(), min_periods=1)
ilocs = ilocs_window['value'] + ([0, 0, 0, 0] + range(len(ilocs_window)-4))
ilocs
df.index.take(ilocs)
df['rolling_min_date'] = df.index.take(ilocs)
df

rawDescription: Most recent max/min value

description: Most recent max/min value


code:
def filter_enrollment(df):
    enrolled = df[df.Enrolled == 1].index.min()
    if pd.isnull(enrolled):
        return df
    else:
        return df[df.index <= enrolled]

rawDescription: Remove all data in a DF by group based on a condition (pandas,python3)


code:
for newpath in find_all_paths(graph, node, path):
    yield newpath

rawDescription: Find all paths without specifing end node?


code:
class Product(RandomPrimaryIdModel):
    class Meta:
        abstract=True

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

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


code:
fruits = {
    'apples': 25,
    'oranges': 35,
    'pears': 10,
    'bananas': 50,
    'pineapples': 40
}

rawDescription: python lists values

description: Python lists values


rawDescription: Wxpython drag and drop folder path, Popen not working with spaces on Windows


rawDescription: Infinite Loop i don't know why ( DichotomySearch )


rawDescription: Python 2.7, How can I get/check the size of a list?


rawDescription: How to recover lists that are saved in Series

description: Recover lists that are saved in Series


code: cleanline = line.strip()

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

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


rawDescription: Consecutive, conflicting regex substitutions


rawDescription: Convenient way to slice from multiindexed rows based on range of keys at different levels with pandas dataframe


code:
import collections
with open('path/to/input') as infile:
    answer = collections.defaultdict(list)
    for line in infile:
        x,y,v = line.split()
        answer[(x,y)].append(v)
answer = {k:tuple(v) for k,v in answer.items()}

rawDescription: Python dictionary having tuple keys and values


code:
import requests
from io import BytesIO
f = BytesIO()
r = requests.get("http://stackoverflow.com/questions/34372102/how-to-download-a-file-and-pass-it-to-a-function")

f.write(r.content.encode("base_64"))

f.seek(0)

print(f.read())

rawDescription: How to download a file and pass it to a function

description: Download a file and pass it to a function


code:
rdd1 = sc.parallelize([("foo", 1), ("foo", 1), ("bar", 1)])
rdd2 = sc.parallelize([("foo", "x"), ("bar", "y")])
rdd1.distinct().join(rdd2)

rawDescription: Does spark's distinct() function shuffle only the distinct tuples from each partition


code: Sparcy Libs Darwin Aaple Phoenix

rawDescription: Dynamically creating classes in python and __repr__


rawDescription: Python; BeautifulSoup and inbuilt Functions


code:
key = lambda d: (not d['logins'], d['logins'], d['date_used'] if d['logins'] else d['date_added'])
pprint(sorted(sample.itervalues(), key=key, reverse=True))

rawDescription: Sort a dictionary with custom sorting function


code:
def myfunction(arg1, arg2):
    pass
my_decorator(myfunction)

rawDescription: Dynamically update attributes of an object that depend on the state of other attributes of same object


code:
from fractions import Fraction
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9, 10]
map(Fraction, a, b)  # In Python 3.x: list(map(Fraction, a, b))

rawDescription: How to pair every item in a 2 lists as fractions until the end of said lists?

description: Pair every item in a 2 lists as fractions until the end of said lists


code:
import example
my_class = example.MyClass()
my_class.my_function(1)
assert(5 == my_class.my_function(2, 3))
assert(6 == my_class.my_function(2, 3, 1))
my_class.my_function(2, 3, 1, 3)
assert(6 == my_class.my_function(3, 1, c=2))
assert(7 == my_class.my_function(a=2, b=2, c=3))
my_class.my_function(b=2, c=1)

rawDescription: Extracting arguments from kwargs in boost::python


code:
def running_avg():
    count, sum = 0, 0
    value = yield None
    while True:
        if value:
            sum += value
            count += 1
        value = yield(sum/count)

# array for keeping running average
array = [[running_avg() for y in range(3)] for x in range(3)]

# advance to first yield before we begin
[[elem.next() for elem in row] for row in array]

with open('data.txt') as f:
    idx = None
    for line in f:
        if idx is not None and idx < 3:
            for i, elem in enumerate(line.strip().split()):
                array[idx][i].send(float(elem))
            idx += 1
        if line.startswith('timestep'):
            idx = 0

rawDescription: Using python to extract a few lines from a data file


code: "ANT101H5 Introduction to Biological Anthropology and Archaeology"

rawDescription: XPath: Select Current and Next Node's text by Current Node Attributes


code:
def f(self):
    return self.x
f.func_defaults = (f,)

rawDescription: how can python function access its own attributes?

description: How can python function access its own attributes


code:
def _word_count(msg):
    return len(msg.split())

@event.listens_for(Comment.message, "set")
def set(target, value, oldvalue, initiator):
    if target.thread is not None:
        target.thread.word_count += (_word_count(value) - _word_count(oldvalue))

@event.listens_for(Comment.thread, "set")
def set(target, value, oldvalue, initiator):
    # the new Thread, if any
    if value is not None:
        value.word_count += _word_count(target.message)

    # the old Thread, if any
    if oldvalue is not None:
        oldvalue.word_count -= _word_count(target.message)

rawDescription: Can SQLAlchemy events be used to update a denormalized data cache?


code:
from statistics import mean

avg = mean(x[2] for x in lst)

rawDescription: Calculate average of a column when two other columns values match


code:
conn.execute('insert into ages select 6 union all select 24 union all select 14 union all select 16 union all select 65')
df = pd.read_sql('select t1.age - t2.age from ages as t1 cross join ages as t2', conn)
df.column = ['diff']
a = pd.DataFrame.from_records(product(range(5), range(5)), columns=['a','b'])
res = pd.concat([df, a],axis=1)
res.pivot(index='a', columns='b', values='diff')

rawDescription: SQL query 1 col & 1000 rows to pandas dataframe 10 cols&100 rows


code: lst = [x[2].strip().split()[0:2] for x in [line.split(',') for line in open(fname)]]

rawDescription: How to read, in a line, all characters from column A to B

description: Read, in a line, all characters from column A to B


code:
def maingen(i):
    print("maingen started")
    gen = subgen(i)
    if gen:
        yield from gen
    print("maingen finished")

rawDescription: How to make Python recognize a function as a generator function?

description: Make Python recognize a function as a generator function


code: s = date.strftime("%Y%m%d")

rawDescription: How to convert integer into date object python?

description: Convert integer into date object python


code: np.take(arr,0) # Input array is arr, 0 is the index position

rawDescription: Find first element of numpy ndarray of unknown shape


code:
for i in d:
    setattr(testobj, i, d[i])

rawDescription: How to modify class object parameters in code

description: Modify class object parameters in code


code:
from itertools import groupby

groupby(sorted_list, key=lambda x: x.lives_in)
result = [(key, list(group)) \
        for key, group in groupby(sorted_list, key=lambda x: x.lives_in)]

rawDescription: How can I sort this list in Python?

description: Sort this list in Python


code:
def numPens(n):
    """
    n is a non-negative integer

    Returns True if some non-negative integer combination of 5, 8 and 24 equals n
    Otherwise returns False.
    """
    # Base case: Negative numbers are by definition false.
    if n < 0:
        return False

    # Base case: 0 is true. It is formed by a combination of zero addends,
    # and zero is a non-negative integer.
    if n == 0:
        return True

    # General case: Try subtracting *each* of the possible numbers, not just
    # the largest one. No matter what n-x will always be smaller than n so
    # eventually we'll reach one of the base cases (either a negative number or 0).
    for x in (24, 8, 5):
        if numPens(n - x):
            return True

    return False

rawDescription: Finding sum: Is recursion necessary, and what would a recursive algorithm look like?


rawDescription: Find Multiple Flagged String within String Python


rawDescription: .htaccess seemingly ignored on OpenShift


code:
'\b'
r'\b'
print('x\by')
print(r'x\by')

rawDescription: Pygame couldn't open image

description: Pygame couldn't open image


rawDescription: Python HTML Email : How to insert list items in HTML email


code:
mgr = multiproccessing.Manager()
d = mgr.dict()
L = mgr.list()

rawDescription: CPU (all cores) become idle during python multiprocessing on windows


code:
your_value = 3
result = reduce(lambda x, y: y(x), function_list, your_value)

rawDescription: How to apply an array of functions to a value using list comprehension?

description: Apply an array of functions to a value using list comprehension


rawDescription: Regular Expression to Remove Rows

description: Regular Expression to Remove Rows


code:
@login_registered
def myView(request):
    if not checkUserType(request.user):
        return redirect('setUserType')  # Page where the user will set his type

    # user has the type, continue

rawDescription: Execute a function in several views in Django


code:
import numpy as np
import numpngw

# The following import is just for creating an interesting array
# of data.  It is not necessary for writing a PNG file with PyPNG.
from scipy.ndimage import gaussian_filter

# Make an image in a numpy array for this demonstration.
nrows = 240
ncols = 320
np.random.seed(12345)
x = np.random.randn(nrows, ncols, 3)

# y is our floating point demonstration data.
y = gaussian_filter(x, (16, 16, 0))

# Convert y to 16 bit unsigned integers.
z = (65535*((y - y.max())/y.ptp())).astype(np.uint16)

# Use numpngw to write z as a color PNG.
numpngw.write_png('foo_color.png', z)

# Here's a grayscale example.
zgray = z[:, :, 0]

# Use numpngw to write zgray as a grayscale PNG.
numpngw.write_png('foo_gray.png', zgray)

rawDescription: Can I save a numpy array as a 16-bit image using "normal" (Enthought) python?

description: Save a numpy array as a 16-bit image using "normal" (Enthought) python


code:
from random import choice

COLORS = ("blue", "red", "yellow")
def b1():
    bl = Label(master, text="Hell yeah!", fg=choice(COLORS), bd = 3).pack()

rawDescription: Printing out different color text with each button press?


code:
class App(object):
    def __init__(self):
        self.nieuw_station = ''

    def add_buttons(self):
        a = Button(master, text="A", width=1, command=lambda: self.letter_toevoegen("a"))
        a.pack()
        # ...

    def letter_toevoegen(self, letter):
        time.sleep(2)
        self.nieuw_station += letter
        print(self.nieuw_station)
        return self.nieuw_station

rawDescription: Button excecutes command once (Tkinter)

description: Button excecutes command once (Tkinter)


code:
def do_nothing():
    pass

rawDescription: Python naming convention for variables that are functions


rawDescription: Multiply array of vectors with array of matrices; return array of vectors?


code: [f for i, f in enumerate(x) if i % 2]

rawDescription: How to delete all the odd ordinal items in a list?

description: Delete all the odd ordinal items in a list


code: 'John', 'Mark'

rawDescription: All items in list duplicated when saved to text file - Python


code:
# Let's do it again, but now use buffering.
fp1 = tempfile.NamedTemporaryFile(bufsize=0)
fp1.write('foo')
fp2 = open(fp1.name)
# Because we've set buffering to 0 (so no buffering) we've written to the
# file.
assert fp2.read() == 'foo'
fp1.close()
fp2.close()

rawDescription: Second file handler on a file behaves unexpectedly


code:
paths = [os.path.join(basedir, name) for name in names]
paths

rawDescription: How to check size of the files in a directory with python?

description: Check size of the files in a directory with python


code:
list1 = ["string1","string2","string3","string4"]
list2 = ["domain_string1","domain_string2"]
allparams = map(lambda x: ("list1", x), list1)
allparams += map(lambda x: ("list2", x), list2)
import urllib
urllib.urlencode(allparams)

rawDescription: How to send bulk data in url?

description: Send bulk data in url


code:
f = open("junk.txt", "a")
f
type(f)

rawDescription: What data type would the variable in "TEXTFILE = open('x.txt','a')" be?


code:
exts = (
    (".py", 1, "python"),
    (".php", 2, "php"),
    (".pl", 1, "perl"),
    (".sh", 1, "/bin/bash"), # Assumption, we accept only bash
    (".groovy", 1, "groovy"),
    (".rb", 1, "ruby"),
)
"""Matching extensions to positional arguments and interpreters"""

rawDescription: Password Management for non-interactive process


code:
try:
    with open('SSID.txt', 'r') as s:
        ssid_dict = {}
        for each_line in s:
            ssid_dict[each_line.strip()] = 0 #key: SSID value: count
except FileNotFoundError:
    pass

try:
    with open('kissmet.nettext', 'r') as f:
        try:
            for each_line in f:
                each_line = each_line.strip()
                if each_line.startswith("SSID") and ':' in each_line: #checks for a line that starts with 'SSID' and contains a ':'
                    val = each_line.split(':')[1].replace('"', '').strip() #splits the line to get the SSID, removes the quotes
                    if ssid_dict[val]:
                        ssid_dict[val] += 1 #adds one to the count in the dictionary
                    else:
                        pass#I don't know what you want to do here
        except KeyError as err:
            print("Key error" + str(err))
except FileNotFoundError:
    pass

for key in ssid_dict:
    print(str(key) + " " + str(ssid_dict[key]))

rawDescription: Using a list to search in textfile - Python


rawDescription: Import JSON data into Python

description: Import JSON data into Python


code: list = sorted(list, key=operator.itemgetter(1))

rawDescription: Getting duplicates in dict

description: Getting duplicates in dict


rawDescription: Select from numpy array by column with multiple logical conditions


code:
for c in phrase:
  ascii_codes = ord(c) # find ascii codes for each charcter in phrase
  ascii_codes = ascii_codes + shift_value # add an integer (shift value) to ascii codes
  phrase_rest = chr(ascii_codes) # convert ascii codes back to characters
  encoded_phrase = encoded_phrase + phrase_rest # stores the phrase character in a new variable

rawDescription: Encrypting a message using a cyclic cypher


code:
import tokenize
import token
import io

text = '''
x = 'hello there'
if x == 'example "quotes" inside quotes' and y == 'another example': pass
'''

tokens = tokenize.generate_tokens(io.BytesIO(text).readline)
for toknum, tokval, (srow, scol), (erow, ecol), line in tokens:
    tokname = token.tok_name[toknum]
    print(tokname, tokval)

rawDescription: Parsing python source into html - quotes


rawDescription: reading text into a dataframe

description: Reading text into a dataframe


code:
from collections import Counter
from pprint import pprint as pp

data = [
    {'price_ex_tax': '99.0000', 'event_date': '', 'wrapping_name': '', 'price_tax': '0.0000', 'id': 3, 'cost_price_tax': '0.0000', 'bin_picking_number': '', 'ebay_transaction_id': '', 'wrapping_cost_ex_tax': '0.0000', 'base_total': '99.0000', 'quantity': 1, 'ebay_item_id': '', 'type': 'physical', 'product_id': 83, 'price_inc_tax': '99.0000', 'base_wrapping_cost': '0.0000', 'parent_order_product_id': None, 'option_set_id': 15, 'wrapping_message': '', 'weight': '3.0000', 'refund_amount': '0.0000', 'applied_discounts': [{'amount': 99, 'id': 'total-coupon'}], 'event_name': None, 'cost_price_ex_tax': '0.0000', 'base_price': '99.0000', 'wrapping_cost_tax': '0.0000', 'total_inc_tax': '99.0000', 'total_ex_tax': '99.0000', 'quantity_shipped': 0, 'fixed_shipping_cost': '0.0000', 'total_tax': '0.0000', 'sku': 'S-TIM-BAC-STD', 'return_id': 0, 'wrapping_cost_inc_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'name': 'University of Timbuktu Bachelor Set', 'is_bundled_product ': False, 'order_id': 614534, 'configurable_fields': [], 'order_address_id': 2, 'is_refunded': False, 'product_options': [{'display_style': 'Pick list', 'type': 'Product list', 'product_option_id': 95, 'display_value': 'Cambridge-Style Bachelor Gown, Size L', 'id': 2, 'option_id': 19, 'value': '77', 'display_name': 'Gown size', 'name': 'Bachelor gown size', 'order_product_id': 3}, {'display_style': 'Pick list', 'type': 'Product list', 'product_option_id': 97, 'display_value': 'Bachelor and Masters Trencher, Size L', 'id': 3, 'option_id': 20, 'value': '80', 'display_name': 'Trencher size', 'name': 'Trencher size', 'order_product_id': 3}], 'base_cost_price': '0.0000'},
    {'price_ex_tax': '0.0000', 'event_date': '', 'wrapping_name': '', 'price_tax': '0.0000', 'id': 4, 'cost_price_tax': '0.0000', 'bin_picking_number': '', 'ebay_transaction_id': '', 'wrapping_cost_ex_tax': '0.0000', 'base_total': '0.0000', 'quantity': 1, 'ebay_item_id': '', 'type': 'physical', 'product_id': 80, 'price_inc_tax': '0.0000', 'base_wrapping_cost': '0.0000', 'parent_order_product_id': 3, 'option_set_id': None, 'wrapping_message': '', 'weight': '0.0000', 'refund_amount': '0.0000', 'applied_discounts': [], 'event_name': None, 'cost_price_ex_tax': '0.0000', 'base_price': '0.0000', 'wrapping_cost_tax': '0.0000', 'total_inc_tax': '0.0000', 'total_ex_tax': '0.0000', 'quantity_shipped': 0, 'fixed_shipping_cost': '0.0000', 'total_tax': '0.0000', 'sku': 'G-CAM-BAC-L', 'return_id': 0, 'wrapping_cost_inc_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'name': 'Cambridge-Style Bachelor Gown, Size L', 'is_bundled_product ': True, 'order_id': 614534, 'configurable_fields': [], 'order_address_id': 2, 'is_refunded': False, 'product_options': [], 'base_cost_price': '0.0000'},
    {'price_ex_tax': '0.0000', 'event_date': '', 'wrapping_name': '', 'price_tax': '0.0000', 'id': 5, 'cost_price_tax': '0.0000', 'bin_picking_number': '', 'ebay_transaction_id': '', 'wrapping_cost_ex_tax': '0.0000', 'base_total': '0.0000', 'quantity': 1, 'ebay_item_id': '', 'type': 'physical', 'product_id': 87, 'price_inc_tax': '0.0000', 'base_wrapping_cost': '0.0000', 'parent_order_product_id': 3, 'option_set_id': None, 'wrapping_message': '', 'weight': '0.0000', 'refund_amount': '0.0000', 'applied_discounts': [], 'event_name': None, 'cost_price_ex_tax': '0.0000', 'base_price': '0.0000', 'wrapping_cost_tax': '0.0000', 'total_inc_tax': '0.0000', 'total_ex_tax': '0.0000', 'quantity_shipped': 0, 'fixed_shipping_cost': '0.0000', 'total_tax': '0.0000', 'sku': 'C-STD-B&M-L', 'return_id': 0, 'wrapping_cost_inc_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'name': 'Bachelor and Masters Trencher, Size L', 'is_bundled_product ': True, 'order_id': 614534, 'configurable_fields': [], 'order_address_id': 2, 'is_refunded': False, 'product_options': [], 'base_cost_price': '0.0000'}
]

def get_defaults(lst_of_dct):
    defaults = {}
    majority = (len(data) + 1) // 2
    for key in lst_of_dct[0]:
        try:
            ctr = Counter(d[key] for d in lst_of_dct)
            value,count = ctr.most_common(1)[0]
            defaults[key] = value if count >= majority else ""
        except TypeError:
            # Counter doesn't like unhashable type ie lists
            defaults[key] = []
    return defaults

defaults = get_defaults(data)
pp(defaults)

rawDescription: Converting an unknown data structure to a known data structure in Python


code:
r, c = np.triu_indices_from(B.T)
B.T[r, c] = B.T[c - r, c]

rawDescription: Flip non-zero values along each row of a lower triangular numpy array


code:
def get_all_possible_items(max_no_users):
    return {i:i+49 if i+49 < max_no_users else max_no_users for i in range(0, max_no_users, 50)}

rawDescription: Python- Most efficient way to return batches of numbers


code:
a = np.array([[1,0,3,4],[0,5,4,6],[7,4,4,5],[3,4,5,6]])

np.fill_diagonal(a, 0) # changes original array, must be careful

overlap = (a == a.T) * a
indices = np.argwhere(overlap != 0)

rawDescription: numpy: find symmetric values in 2d arrays

description: Numpy: find symmetric values in 2d arrays


code:
import re
zip(*[(i.strip() for i in re.split('(\d{4})|\||>', text) if i and i.strip())]*3)

rawDescription: Converting one string with multiple lists/arrays into separate lists


code:
img = cv2.imread('origin.png')
im_color = cv2.applyColorMap(img, cv2.COLORMAP_HSV)
cv2.imshow('mapped_image', im_color)
# cv2.imwrite('result.png', im_color)
cv2.waitKey(0)

rawDescription: How to get the red channel color space of an image?

description: Get the red channel color space of an image


code:
def shifted_range(rangeob, shift):
    size, shift = rangeob.stop, shift * rangeobj.step
    return ((i + shift) % size for i in rangeob)

range_10 = range(10)
list(shifted_range(range_10, 3))
list(shifted_range(range_10, 7))
range_10_2 = range(0, 10, 2)
list(shifted_range(range_10_2, 4))

rawDescription: Python 3.x Shifting Ranges

description: Python 3.x Shifting Ranges


code:
def rotate(strg,n):
    n = n % len(strg)
    return strg[n:] + strg[:n]

rawDescription: swap letters in a string in python

description: Swap letters in a string in python


code:
def make_C(a=False, b=False):
    if a:
        return type('C', (A, B), {})()
    elif b:
        return type('C', (B, A), {})()

rawDescription: conditional class inheritance in python

description: Conditional class inheritance in python


rawDescription: Python 2.6 optimize nested loops

description: Python 2.6 optimize nested loops


code: s = 'Hi my name is {name} and I am {age} years old'

rawDescription: Python pattern replacement

description: Python pattern replacement


rawDescription: pandas build matrix of row by row comparisons

description: Pandas build matrix of row by row comparisons


code:
test_form.html
{{ form.choice_switcher() }}

rawDescription: How to make radio field show default value with flask and wtforms

description: Make radio field show default value with flask and wtforms


code: def f(y, z): return math.sqrt(y**2 + z**2)

rawDescription: Distance Calculation Not Working

description: Distance Calculation Not Working


code:
d = {}
d.setdefault(key, set()).add(value)

rawDescription: Creating a dictionary and adding a set as its value


code:
x = subprocess.Popen('sh abc.sh',
                 shell=True,
                 stdout=subprocess.PIPE,
                 stdin=subprocess.PIPE)

...

x.stdin.write('\n')

rawDescription: Press enter as command input

description: Press enter as command input


rawDescription: Convert binary to ASCII and vice versa

description: Convert binary to ASCII and vice versa


rawDescription: How do I view a model produced using scikit-learn?

description: View a model produced using scikit-learn


code:
class MySimpleTestCase(DjangoTestCase):
    def setUp(self):
        self.file = StringIO.StringIO('MiniMockTest')
        self.file.close = self.Mock('file_close_function')
    def test_urldump_dumpsContentProperly(self):
        self.mock('urllib2.urlopen', returns=self.file)
        self.assertEquals(urldump('http://pykler.github.com'), 'MiniMockTest')
        self.assertSameTrace('\n'.join([
            "Called urllib2.urlopen('http://pykler.github.com')",
            "Called file_close_function()",
        ]))
        urllib2.urlopen('anything')
        self.mock('urllib2.urlopen', returns=self.file, tracker=None)
        urllib2.urlopen('this is not tracked')
        self.assertTrace("Called urllib2.urlopen('anything')")
        self.assertTrace("Called urllib2.urlopen('this is mocked but not tracked')", includes=False)
        self.assertSameTrace('\n'.join([
            "Called urllib2.urlopen('http://pykler.github.com')",
            "Called file_close_function()",
            "Called urllib2.urlopen('anything')",
        ]))

rawDescription: Cleanly Mocking Remote Servers and APIs for Django Unittests


code:
# apps.py
from django.apps import AppConfig
from sexmachine.detector import Detector

class APIConfig(AppConfig):
    name = 'api'

    def ready(self):
        # Singleton utility
        # We load them here to avoid multiple instantiation across other
        # modules, that would take too much time.
        print("Loading gender detector..."),
        global gender_detector
        gender_detector = Detector()
        print("ok!")

rawDescription: Django application having in memory a big Panda object shared accros all requests?


rawDescription: importing an array from a .dat file in python

description: Importing an array from a .dat file in python


code:
df['period'] = df.END_DATE.dt.to_period('M')
df1['period'] = df1.Date.dt.to_period('M')

df2 = pd.merge(df1, df, on=['ID','period'], how='left')

df2['END_DATE'] = df2.END_DATE.combine_first(df2.Date)
df2['START_DATE'] = df2.START_DATE.bfill()
df2 = df2.drop(['Date','period'], axis=1)

rawDescription: Vectorized implementation to create multiple rows from a single row in pandas dataframe


code:
from pyspark.sql.functions import explode

keys = (df
    .select(explode("Parameters"))
    .select("key")
    .distinct()
    .rdd.flatMap(lambda x: x)
    .collect())

rawDescription: PySpark converting a column of type 'map' to multiple columns in a dataframe


code: type(x) == my.object.kind #3.x

rawDescription: How to check if variable is a specific class in python?

description: Check if variable is a specific class in python


rawDescription: How to look only at entire words with regex?

description: Look only at entire words with regex


code:
x = 6
x.real
x.imag
x.bit_length()

rawDescription: If everything is an object, why can't I add attributes to some?


code:
print('generating list...')
from random import randrange, seed
seed(0) # always same contents
l = []
for i in range(1000000):
    l.append(randrange(0,5000))

print('ok, measuring...')

from time import time

start = time();
print(get_pairs(l, 0))
print('took', time()-start, 'seconds')

rawDescription: The fastest way to find all pairs of numbers in a list that differ not more than x


code:
for sublist in data:
    file2.write(':'.join(sublist) + '\n')

rawDescription: Python Iterate an integer as long as elements exist in a list


rawDescription: Sum by year and id in Pandas

description: Sum by year and id in Pandas


code: [tablelist[0] + '.' + var for tablelist in list for var in tablelist[1:]]

rawDescription: Extracting multiple values from multiple tables from Database using python


code: gallery_list = list(sorted(frozenset(gallery_list), key=attrgetter('display_order')))

rawDescription: Django Query Optimization - Using Itertools


code:
with open('mediumWordList.txt') as f:
   sum(1 for line in f for word in line.split() if word.startswith('co'))

rawDescription: How to count number of words that start with a string

description: Count number of words that start with a string


code:
def func_a():
    #Do stuff here...
    return

def func_b():
    #Do stuff here...
    return

type = input("A/B: ").lower()

if type == "a":
    func_a()
elif type == "b":
    func_b()
else:
    print("Invalid option.")

rawDescription: Run Code based on User Input (Python3,Pandas)


rawDescription: Enumeration of all possible two-member group constellations


rawDescription: Mean value by equality of rows

description: Mean value by equality of rows


code:
import random

def valid_duplicate_spacing(x):
    for i, elem in enumerate(x):
        if elem in x[i+1:i+3]:
            return False
    return True

def sample_permutations_with_duplicate_spacing(seq):
    sample_seq = seq + seq
    random.shuffle(sample_seq)
    while not valid_duplicate_spacing(sample_seq):
        random.shuffle(sample_seq)

    return sample_seq

rawDescription: shuffle list with repetition constraint 2-back python

description: Shuffle list with repetition constraint 2-back python


code:
import random
import math
import operator as op

def test():
    num1 = random.randint(1, 10)
    num2 = random.randint(1, num1)

    ops = {
        '+': op.add,  #Just like the add() functions defined above
        '-': op.sub,
        '*': op.mul,
    }

    keys = list(ops.keys()) #=> ['+', '*', '-']
    rand_key = random.choice(keys)  #e.g. '-'
    operation = ops[rand_key]  #e.g. op.sub

    correct_result = operation(num1, num2)

rawDescription: python: Primary school Arithmetic quiz- saving results to a .txt file

description: Python: Primary school Arithmetic quiz- saving results to a .txt file


code:
if event.key == MOUSEBUTTONDOWN:    #Remember to use from pygame.locals import *
    pass                            #Create code to make rectangle
                                    #Of course, top and bottom is mousex and mousey
elif event.key == MOUSEBUTTONUP:
    pass                            #Do nothing else

rawDescription: Click the mouse to continue python 2

description: Click the mouse to continue python 2


code:
import pandas as pd

df = pd.DataFrame({'ID': [1, 1, 2, 2, 1],
                   'value': [10, 20, 15, 100, 12]})

byid = df.groupby('ID')
mean = byid.mean()
std = byid.std()

df['normalized'] = df.apply(lambda x: (x.value - mean.ix[x.ID]) / std.ix[x.ID], axis=1)
print(df)

rawDescription: NumPy : normalize column B according to value of column A


rawDescription: How to remove a list value from a dictionary?

description: Remove a list value from a dictionary


code: '~5n7x~ Jahalducro) P 4 J 99 UMH 9 (MD) auntud C D T)'

rawDescription: Avoid regex on a substring enclosed by a character


code: dout

rawDescription: Create open bounds indicators from pandas get_dummies on discretized numerical


rawDescription: python for each match in a string copy to an array

description: Python for each match in a string copy to an array


rawDescription: Fix values that are typed into a doublespinbox in PyQt


code:
x = iter(range(3))
y = iter(range(3, 6))
z = x + y
a = list(x)
b = list(z) # what should the contents of z be?

rawDescription: Concatenate generators in python 3 with +-operator


rawDescription: Pandas Dataframes to_html: Highlighting table rows


code: fmain()

rawDescription: How to catch the stdio from a python subroutine?

description: Catch the stdio from a python subroutine


code:
(...)
session = create_session(...)
(...)
model = Model(col='Iuri Diniz')
session.add(model)
session.commit()

rawDescription: Python-Sqlalchemy Binary Column Type HEX() and UNHEX()


code: d.addCallbacks(callback, errback)

rawDescription: Implementation of an async method in Python DBus


code:
for field, val in form.cleaned_data.items():
    do_stuff

rawDescription: Django 1.1 FormWizard, Dynamically extend form


code: package_data={'': ['license.txt']}

rawDescription: Including non-Python files with setup.py


rawDescription: Converting identifier naming between camelCase and underscores during JSON serialization/deserialization


code:
from contextlib import closing # http://stackoverflow.com/a/25968716/968442
from multiprocessing.pool import Pool

with closing(Pool(len(url))) as pool:
    pool.map(btl_test, url)

rawDescription: How to run script in multithreading or multiprocessing

description: Run script in multithreading or multiprocessing


code:
Node.__new__.__defaults__ = (None, None)
Node()
Node(3)

rawDescription: Named tuple and optional keyword arguments


code:
def newlist(old_list):
    new_list = []
    for i in old_list:
        sep = ''
        new_list.append(sep.join(i))
    return new_list

rawDescription: Unable to perform join in the inner lists of a list of lists


code:
import re

s = """
"I'm certain in America's “West,” it could’ve been possible for gunfights
to erupt at any time anywhere," he said holding a gun in his hand.
"""

callback = lambda pat: ''+pat.group(1)+''
result = re.sub(r"(?<!')(?!i>)(\w+)", callback, s)

rawDescription: Add link to every word, accounting for punctuation, contractions, and Unicode


code: self.update = self.sha256.update

rawDescription: How do I derive from hashlib.sha256 in Python?

description: Derive from hashlib.sha256 in Python


code:
x = np.arange(200).reshape((4,5,10))
with file('test.txt', 'w') as outfile:
    for slice_2d in x:
        np.savetxt(outfile, slice_2d)

rawDescription: How to write a multidimensional array to a text file?

description: Write a multidimensional array to a text file


code:
to_check = [120, 49]
"Not in" if not any(to_check in cluster for cluster in clusterList) else "In"

rawDescription: Check to see if a list is in a list of lists


code:
import inspect
try:
    # For modules that define __all__, we want all exported classes
    # even if they weren't originally defined in the module
    todefine = filter(inspect.isclass, (getattr(somemodule, name) for name in somemodule.__all__))
except AttributeError:
    # If __all__ not defined, heuristic approach; exclude private names
    # defined with leading underscore, and objects that were imported from
    # other modules (so if the module does from itertools import chain,
    # we don't wrap chain)
    todefine = (obj for name, obj in vars(somemodule).items() if not name.startswith('_') and inspect.isclass(obj) and inspect.getmodule(obj) is somemodule)

rawDescription: Defining same method override on lots of classes: DRY?