code:
# Create a user account if we haven't found one yet.
'social.pipeline.user.create_user',

rawDescription: Use Python social auth to only get tokens


code:
import ssl
import os
# get the https certificate
cert = ssl.get_server_certificate(('example.com', 443))
# append it to my personal chain
pem_path = os.path.expanduser('~/.pki/CA/cacert.pem')
with open(pem_path, 'a+') as f:
    f.write(cert)

rawDescription: How can I verify my selfsigned certificate when using easywebdav?

description: Verify my selfsigned certificate when using easywebdav


rawDescription: How to break down a number with another from list?

description: Break down a number with another from list


code:
import sys
import os
import glob

def handle_file(filename):
    # whatever you want to do with the file named filename e.g.
    print(filename)

for name in sys.argv[1:]:
    if name.find('.txt') != -1:
        handle_file(name)
    else:
        for filename in glob.glob(os.path.join(name, '*.txt')):
            handle_file(filename)

rawDescription: How to do write a Python script that inputs all files from a certain subdirectory from command line?

description: Do write a Python script that inputs all files from a certain subdirectory from command line


code:
gb = g.agg({'id': pd.Series.nunique,
            'amount': [np.sum, np.max]})

rawDescription: Grouped Aggregation on multiple columns in Pandas


code:
from string import ascii_uppercase
nodeName.split("_")[-1].translate(None,ascii_uppercase+"-")

rawDescription: Ignore all characters and just read numbers portion from the string


code:
# your string
line = '1 VNET ... 19.03 ...'
# pick out the price
price = line[40:48]

rawDescription: Grabbing String Contents Python

description: Grabbing String Contents Python


code:
from twisted.internet.protocol import ClientCreator
from twisted.internet import reactor

# some where :
defer = ClientCreator(reactor, RedisListenerProtocol).connectTCP(__HOST__, __PORT__)
# the defer will have your client when the connection is done

rawDescription: txredisapi subscribe and listen async

description: Txredisapi subscribe and listen async


code:
def classmethod_example(func):
    def wrapper(self, *args, **kwargs):
        return func(self.__class__, *args, **kwargs) # Substitute *cls* for *self*
    return wrapper

rawDescription: Function inside of Object generating different print output than stand-alone function in Python 3.5


code:
with open('test.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile,  delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow([min(size),min(size)])

rawDescription: Python csv writer writing all contents to one cell


code:
[l[i:i+2] for i in range(0, len(l), 2)]
l = [l[i:i+2] for i in range(0, len(l), 2)]

rawDescription: how to make regex go line by line to match two strings at the same time?

description: Make regex go line by line to match two strings at the same time


rawDescription: Python string formatting - old `%` vs new `str.format`


code:
import numpy as np
A = np.zeros(10)
B = np.ones(20)

n = len(A)
C = np.concatenate([A.reshape(n, 1), B.reshape(n, -1)], axis=1)
C = C.ravel()

rawDescription: Numpy setting j, j+1, j+2 to a

description: Numpy setting j, j+1, j+2 to a


code:
w = WebPage("foo.html")

w.process()
w.printedheadbody()

rawDescription: Using variable inside a class function defintion, which created in other class function | python


rawDescription: How to reorder indexed rows based on a list in Pandas data frame

description: Reorder indexed rows based on a list in Pandas data frame


code:
def hash(tuple):
    mult = 1000003
    x = 0x345678
    for index, item in enumerate(tuple):
        x = ((x ^ hash(item)) * mult) & (1<<32)
        mult += (82520 + (len(tuple)-index)*2)
    return x + 97531

rawDescription: What hash algorithm does Python's dictionary mapping use?


code: arr = np.random.rand(160,160)

rawDescription: Python: count the matrix values according to the threshold


code:
GOOGLE_LOGIN_CLIENT_ID = "<your-id-ending-with>.apps.googleusercontent.com"
GOOGLE_LOGIN_CLIENT_SECRET = "<your-secret>"

OAUTH_CREDENTIALS={
        'google': {
            'id': GOOGLE_LOGIN_CLIENT_ID,
            'secret': GOOGLE_LOGIN_CLIENT_SECRET
        }
}

rawDescription: Using Google OAuth2 with Flask

description: Using Google OAuth2 with Flask


code: [dic for dic in my_list if 'joe' in dic]

rawDescription: python list comprehension get dictionary by key

description: Python list comprehension get dictionary by key


code:
y = [(k,v) for k,v in x if max(d[v])==k]
y

rawDescription: Python: conditionally delete elements from list


code:
totals = pd.DataFrame()
counts = pd.DataFrame()
df = pd.read_csv(file_path, chunksize=5e4)
for chunk in df:
    grouped = chunk.groupby(['transcript_id', 'gene_id', 'gene_name'])
    totals = totals.add(grouped.sum())
    counts = counts.add(grouped.count())
means = totals/counts

rawDescription: Retaining nuisence coliumns in pandas groupby


code:
import json
# ...
list = json.loads(request.GET['arr'])

rawDescription: Send Array through url in python django

description: Send Array through url in python django


rawDescription: How to slice and extend a 2D numpy array?

description: Slice and extend a 2D numpy array


rawDescription: Hiding console window of Python GUI app with py2exe


code:
import pandas

# set up data structures
columns = [
    "year",
    "actual",
    "upper",
    "upper_central",
    "lower_central",
    "lower"
]
value_getter = {
    "year"         : lambda item: item['year'],
    "actual"       : lambda item: item['values'][0]['Actual'],
    "upper"        : lambda item: item['values'][1]['Upper End of Range'],
    "upper_central": lambda item: item['values'][2]['Upper End of Central Tendency'],
    "lower_central": lambda item: item['values'][3]['Lower End of Central Tendency'],
    "lower"        : lambda item: item['values'][4]['Lower End of Range']
}
mydata = {
    "year"         : [],
    "actual"       : [],
    "upper"        : [],
    "upper_central": [],
    "lower_central": [],
    "lower"        : []
}

# repackage data
for item in data[0]:
    for column in columns:
        mydata[column].append(value_getter[column](item))

# and stuff it into pandas
df = pandas.DataFrame(mydata, columns=columns)

rawDescription: How to convert nested dictionary into a 2D table

description: Convert nested dictionary into a 2D table


code: apple = 5

rawDescription: Python module importing

description: Python module importing


rawDescription: Multiple values JSON string Python (Django)


code:
from django.conf import settings
def my_site_url(request):
    return {
        'SITE_URL': settings.SITE_URL,
    }

rawDescription: a way to have django SITEURL constant in settings.py

description: A way to have django SITEURL constant in settings.py


rawDescription: Computing average across a list of MxN arrays


code:
input_list = [[1, 2], [1, 3], [1, 4], [2, 8], [2, 10]]
elimination_set = {(1, 2), (2, 8)}
result_list = [t for t in input_list if tuple(t) not in elimination_set]

rawDescription: Simple way to delete nested (list of 2 elements) from a list?


rawDescription: How to iterate a 3D numpy array

description: Iterate a 3D numpy array


code:
l = [[node_degree[r] if r == c else arc_weight[r,c]
            for c in xrange(dim)] for r in xrange(dim)]

rawDescription: fast python matrix creation and iteration

description: Fast python matrix creation and iteration


code:
def shift_towards_zero(number, delta):
    return sign(number) * (abs(number) - delta)

rawDescription: naming advice "subtract absolute" type function

description: Naming advice "subtract absolute" type function


code:
import PyQt4.QtCore
d = PyQt4.QtCore.QDateTime(2014, 2, 20, 17, 10, 30)
d.toMSecsSinceEpoch() / 1000

rawDescription: Convert QDate to seconds

description: Convert QDate to seconds


code:
import numpy as np
a = np.ma.masked_equal([2, 0, 1, 1, 3, 0, 0, 2, 0], 0)
rep = np.zeros(a.shape, dtype=int)
rep[~a.mask] = np.random.geometric(1. / a[~a.mask])

rawDescription: Python: Generating from geometric distribution


rawDescription: Remove duplicate considering a couple of attributes in Pandas


rawDescription: Complex Sorting of a List

description: Complex Sorting of a List


code:
driver = webdriver.Chrome();
driver.get('http://www.google.com');
driver.save_screenshot('out.png');
driver.quit();

rawDescription: How do I generate a png file w/ selenium/phantomjs from a string?

description: Generate a png file w/ selenium/phantomjs from a string


code:
for worker in workerthreads:
    worker.readycleanup.wait()
do_cleanup_stuff()
for worker in workerthreads:
    worker.readycleanup.clear()
    worker.cleanupfinished.set()

rawDescription: Synchronize a cleanup process between threads


code:
df["new_column"] = ""
is_null = pd.isnull(df["criteria_column"])
df["new_column"][is_null] = df["return_column"][is_null] # method 1

rawDescription: Using np.where, or another broadcasting technique in pandas dataframe


code:
class Model(SomeBaseClass):
    pass

rawDescription: Django - create a new instance of a model


code:
c=int(input('Please enter an amount between 0-99:'))
print(c//25, "quarters")
c = c%25
print(c//10, "dimes")
c = c%10
print(c//5, "nickles")
c = c%5
print(c//1, "pennies")

rawDescription: Coin Change Maker Python Program

description: Coin Change Maker Python Program


code:
p = re.compile(r'(?=\t)((?:.|\n\t+)*)', re.MULTILINE)
test_str = "SELECT\n\tSELECT select1\n\tFROM\n\t\tSELECT A\n\t\tFROM B\n\t\tWHERE C\n\tWHERE X\nFROM\n\tSELECT from1\n\tFROM from2\n\tWHERE from3\nWHERE\n\tSELECT child1\n\tFROM child2"
print(re.findall(p, test_str))

rawDescription: Regular expression pattern (match newline and tab) in Python


code:
from collections import namedtuple
Base = namedtuple('Base', ['Locus', 'Total_Depth', 'Average_Depth_sample', 'Depth_for_17'])
r = ['chr1:6484996', '1030', '1030', '1030']
Base(r[0], *map(int, r[1:]))

rawDescription: Converting values of named tuples from strings to integers


code:
with open("foo.txt") as fin:
    any(x.isspace() for x in fin) # skip to 1st blank line
    any(x.isspace() for x in fin) # skip to 2nd blank line
    next(fin)

rawDescription: Python Print text after certain number of blank lines


rawDescription: How to search & replace in Python?

description: Search & replace in Python


code:
from itertools import repeat, chain
m = ["a", "b", "c", "d", "e", "f", "g", "h"]
list(chain.from_iterable(zip(m, repeat(99))))[:-1]

rawDescription: Python for loop doesn't execute last iteration


rawDescription: Nested django templates

description: Nested django templates


code:
s = '[{"name":"Tom","adress":"adress1"},{"name":"Mari","adress":"adress2"}]'
import ast
ast.literal_eval(s)

rawDescription: Convert string to list in python

description: Convert string to list in python


code:
foo = [['one', 1], ['two', 1], ['three', 1]]
bar = [['three', 1], ['four', 1], ['five', 1]]
from collections import Counter
from collections import OrderedDict
from itertools import chain
L = [foo, bar]
counter = Counter()
for item in L:
    counter.update(dict(item))

order = OrderedDict(chain.from_iterable(L))
[[k, counter[k]] for k in order]

rawDescription: python: fast and easy way to compare these lists?

description: Python: fast and easy way to compare these lists


code:
import glob
import shutil

dest = 'c:/tmp/'

# Get all the files as a list with glob
files = glob.glob('c:/files/*.bin')

# move each file seperatly
for filename in files:
    shutil.move(filename, dest)

rawDescription: Why does the code : os.popen('move *.bin tmp) only move one file?


rawDescription: How to make filter regex not ignore minus sign in a line of text?

description: Make filter regex not ignore minus sign in a line of text


code:
from itertools import groupby

solve('2456890048') #or pass `str(2456890048)` if you've integers.
solve('245688888890048')

rawDescription: Best way of getting the longest sequence of even digits in an integer


code:
plt.xticks([range(30)], Sekwencja1,'ko')
plt.yticks([range(30)], Sekwencja2,'wo')

rawDescription: Amino acid sequences in pyplot (Same regions in both sequences)


code:
d = {1: 'Foo', 2: 'Bar', 3: 'Chazz', 4: 'Alpha', 6: 'Zorn', 7: 'Doe'}
sorted(d, key=d.get)

rawDescription: dictionary keys sorted by value

description: Dictionary keys sorted by value


code:
def my_view(request):
    mtcars = open('mtcars.html').read()
    context = {'mtcars': mtcars}
    return render(request, 'my_view.html', context)

rawDescription: How do I remove \n characters in django html rendering of an R xtable?

description: Remove \n characters in django html rendering of an R xtable


code:
data = """Civic        Honda Car
Honda        Manufacturer
VW           Manufacturer
Manufacturer .
Car          .
Beetle       VW Car
"""
g = read_graph(data.splitlines())
g
dump_graph(g)

rawDescription: Algorithm implementation in python

description: Algorithm implementation in python


rawDescription: setDefault for Nested dictionary in python

description: SetDefault for Nested dictionary in python


code:
import matplotlib.pyplot as plt
import matplotlib.patheffects as pe

x = [1, 2, 3]
y =[1, 2, 3]

fig, ax = plt.subplots()
ax.plot(x, y, linewidth=10, color='yellow')
ax.text(2, 2, 'label', ha='center', size=72,
       path_effects=[pe.withStroke(linewidth=10, foreground='w')])

# For the moment, hide everything else...
ax.axis('off')
fig.tight_layout()
fig.set(facecolor='white')

plt.show()

rawDescription: Remove matplotlib text plot border

description: Remove matplotlib text plot border


code: from bin import functions

rawDescription: How to import from another folder (python)

description: Import from another folder (python)


code:
class ExampleForm(forms.ModelForm):
    class Meta:
        model = Example

    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['description'].max_length = self.instance.description_length

rawDescription: Django form, change default max_length

description: Django form, change default max_length


code: [list(filter(lambda x: x > thresholds[idx],qts)) for idx,qts in enumerate(quotes)]

rawDescription: compare elements of list to elements of list of lists and conditionally create new lists

description: Compare elements of list to elements of list of lists and conditionally create new lists


code: a = Theta(np.zeros(3))

rawDescription: Create view to recarray subclass

description: Create view to recarray subclass


code:
[(name, int(perc) if perc else np.nan)
 for name, perc in re.findall(r'(\b[\w -]+\b)(?:\s+\((\d+)%\))?', inputtext)]

rawDescription: One Way to Grab both text and percentages regex python


code:
top = csr.execute("Select * from bigtop")
d=list(top)
a = np.asarray([[x[0] for x in top.description]] + d, dtype='object')

rawDescription: Get SQL headers from Numpy Array in python


code: result = df.resample('M', how='mean'); result

rawDescription: Sorting data in a .csv by month and year and calculating the mean


code:
def get_fib(n):
    fib_gen = fib()
    for _ in range(n):
        next(fib_gen)
    return next(fib_gen)

rawDescription: bottom up fibonacci in python using O(1) space

description: Bottom up fibonacci in python using O(1) space


rawDescription: Beautiful Soup - Class contains 'a' and not contains 'b'


rawDescription: Increasing speed of python code

description: Increasing speed of python code


code:
photodict = json.loads(quoted_resp)
for meta in photodict['photo']['exif']:
    if meta["tagspace"] == "GPS" and meta["tag"] == "GPSLongitude":
        print(meta["clean"]["_content"])

rawDescription: parse special json format with python

description: Parse special json format with python


code:
from pandas.io import sql
import MySQLdb

con = MySQLdb.connect()  # may need to add some other options to connect

rawDescription: How to insert pandas dataframe via mysqldb into database?

description: Insert pandas dataframe via mysqldb into database


code: super(Child, self).a_wrapped_method

rawDescription: Python : metaclass + wrapped methods + inheritance = problems


code: textRect.center = (center_x, center_y) # set center to (x, y) coordinates

rawDescription: Python/Pygame: Placing text in a specific location


code:
projects = []
for node in nodes:
    if node.project not in projects:
        projects.append(node.project)

rawDescription: Select all of django foreign key model if condition or part if another condition


code:
from random import shuffle

def remove_percentage(list_a, percentage):
    shuffle(list_a)
    count = int(len(list_a) * percentage)
    if not count: return []  # edge case, no elements removed
    list_a[-count:], list_b = [], list_a[-count:]
    return list_b

rawDescription: Is it possible to randomly *remove* a percentage/number of items from a list & then *append* them to another list?


code: glued.groupby(level=0, axis=1).mean()

rawDescription: Averaging data from multiple data files in Python with pandas


code:
class Student(object):
    def __init__(self, name, age, gender, level, grades=None):
        self.name = name
        self.age = age
        self.gender = gender
        self.level = level
        self.grades = grades or {}

    def setGrade(self, course, grade):
        self.grades[course] = grade

    def getGrade(self, course):
        return self.grades[course]

    def getGPA(self):
        return sum(self.grades.values())/len(self.grades)

# Define some students
john = Student("John", 12, "male", 6, {"math":3.3})
jane = Student("Jane", 12, "female", 6, {"math":3.5})

# Now we can get to the grades easily
print(john.getGPA())
print(jane.getGPA())

rawDescription: When should I be using classes in Python?


code: k = k.copy(k.bucket.name, k.name, {'myKey':'myValue'}, preserve_acl=True)

rawDescription: How to change metadata on an object in Amazon S3

description: Change metadata on an object in Amazon S3


code:
import numpy as np
n = len(nodes)
heatmap = np.zeros((n,n))

rawDescription: Heat Map Python

description: Heat Map Python


code:
frameName.bind('<Configure>', self.resize)

def resize(self, event):
    self.font = tkFont(size = widget_height)

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


rawDescription: How do nested functions work in Python?

description: How do nested functions work in Python


code:
s = "The quick brown fox jumps over the lazy dog"
l = [1, 8, 14, 18, 27]
l = [0] + l + [len(s)]
[s[x:y] for x,y in zip(l, l[1:])]

rawDescription: What's the pythonic way to cut a string at multiple positions?


code:
target_dir = '/tmp/dummy'
files = [ '/tmp/dir/file1', '/tmp/dir/subdir/file2', '/tmp/file3' ]

cp_parents(target_dir, files)

rawDescription: Copy a file into a directory with its original leading directories appended


code:
# Esablish a plugin by importing it
import plugin1

# Call the API
import master
master.callout()
master.dynamic_callout("shut up or get out")

rawDescription: How can I call a function from inside an imported module, aka design issue

description: Call a function from inside an imported module, aka design issue


code:
mask = b > history[..., -1:]
index = argmax(mask, axis=-1)

rawDescription: Gridwise application of the bisection method


code:
for slicelist, text in zip(lists_of_lists, just_a_list):
    for start, stop in zip(*([iter(slicelist)]*2)):
        print(text[int(start):int(stop) + 1])

rawDescription: Iterating between 2 lists

description: Iterating between 2 lists


code:
bp_dict = boxplot(data, vert=False) # draw horizontal boxplot
bp_dict.keys()
bp_dict.keys()

rawDescription: Overlaying the numeric value of median/variance in boxplots


code:
def generator_overlap_split_list(l,s):
    l2 = []
    for i in l:
        if i in s:
            yield l2
            l2 = []
        l2.append(i)
    if l2: yield l2

rawDescription: split a list in python

description: Split a list in python


code:
def word_features(name):
    features = {}
    features["firstletter"] = name[0].lower()
    features["lastletter"] = name[-1].lower()
    for letter in 'abcdefghijklmnopqrstuvwxyz':
        features["count(%s)" % letter] = name.lower().count(letter)
        features["has(%s)" % letter] = (letter in name.lower())
    return features

rawDescription: What area deals with the extraction of words with similar characteristics?


code:
def constrained_product(target, *args):
    pools = map(tuple, args)
    if len(pools) == 1:
        for y in pools[0]:
            if y == target:
                yield (y,)
    else:
        for y in pools[-1]:
            for x in constrained_product(target-y, *pools[:-1]):
                yield x + (y,)

rawDescription: Challenge: Creating a list of tuples of different combinations with different value 'options' in each location of the tuple.


rawDescription: regex - how to recognise a pattern until a second one is found

description: Regex - how to recognise a pattern until a second one is found


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

def main():
    # Set up 3D coordinates from -10 to 10 over a 200x100x100 "open" grid
    x, y, z = np.ogrid[-10:10:200j, -10:10:100j, -10:10:100j]

    # Generate a cube of interesting data
    data= np.sin(x*y*z) / (x*y*z)

    # Visualize it
    viewer = VolumeViewer(data)
    viewer.show()

class VolumeViewer(object):
    def __init__(self, data):
        self.data = data
        self.nframes = self.data.shape[0]

        # Setup the axes.
        self.fig, self.ax = plt.subplots()
        self.slider_ax = self.fig.add_axes([0.2, 0.03, 0.65, 0.03])

        # Make the slider
        self.slider = Slider(self.slider_ax, 'Frame', 1, self.nframes,
                            valinit=1, valfmt='%1d/{}'.format(self.nframes))
        self.slider.on_changed(self.update)

        # Plot the first slice of the image
        self.im = self.ax.imshow(data[0,:,:])

    def update(self, value):
        frame = int(np.round(value - 1))

        # Update the image data
        dat = self.data[frame,:,:]
        self.im.set_data(dat)

        # Reset the image scaling bounds (this may not be necessary for you)
        self.im.set_clim([dat.min(), dat.max()])

        # Redraw the plot
        self.fig.canvas.draw()

    def show(self):
        plt.show()

if __name__ == '__main__':
    main()

rawDescription: Delete image frame from 3d array

description: Delete image frame from 3d array


code:
import base64

timestamp = int.from_bytes(ba_object[:4], byteorder='big')
data = base64.b64decode(ba_object[4:])

rawDescription: Python 3 Struct unpack int and bytearray


code: y = zip(name[count], i)

rawDescription: enumerate is iterating of letters of strings in a list instead of elements

description: Enumerate is iterating of letters of strings in a list instead of elements


code:
grp = df.groupby('A')
grp.indices
grp.indices[3]

rawDescription: Finding consecutive segments in a pandas data frame


code: checked = [answer.pk for answer in form.cleaned_data['answer']]

rawDescription: Primary keys as choices in MultipleChoiceField


code:
def trade_spider(max_pages):
    for page_number in range(1, max_pages + 1):
        url = "http://munich.eventful.com/events/categories/festivals_parades?page_number={}".format(page_number)
        print(url)
        # just get the code, no headers or anything
        plain_text = requests.get(url).content
        # BeautifulSoup objects can be sorted through easy
        soup = BeautifulSoup(plain_text)
        category = soup.find('li', id='breadcrumb-label').string
        for mylist in soup.findAll('li', {'class': 'clearfix'}):
            link = mylist.find('a', {'data-ga-label': 'Event Title'})
            if link is not None:
                href = link.get('href')
                title = link.string  # just the text, not the HTML
                location = mylist.find("div", {"class": "event-meta"}).strong.string
                date = mylist.find("div", {"class": "event-meta"}).span.string
            print(title, category, href, date, location)

rawDescription: Page number request doesn't change for site when scraping with Python and Beautiful Soup


code:
def key1( a ): return a.attribute1
def key2( a ): return a.attribute2

someList.sort( key=key2, reverse=True )
someList.sort( key=key1 )

rawDescription: Python: List Sorting with Multiple Attributes and Mixed Order


code:
z = zipfile.ZipFile(targetFile, 'w')
(path, filename) = os.path.split(sourceFile)
bytes = file(sourceFile, 'rb')
info = zipfile.ZipInfo(filename)
info.external_attr = 33
z.writestr(info, bytes.read())
bytes.close()
z.close()

rawDescription: Preserve file attributes in ZipFile

description: Preserve file attributes in ZipFile


rawDescription: pandas - add column with normalized selected values

description: Pandas - add column with normalized selected values


code:
def f_1d(x):
    return (x,x)
d = numpy.column_stack(numpy.vectorize(f_1d)(a))

rawDescription: How can I iterate over an 1D array and build a 2D array in Numpy?

description: Iterate over an 1D array and build a 2D array in Numpy


code:
data = [{
'timestamp': 1366902000,
'localTimestamp': 1366902000,
'issueTimestamp': 1366848000,
'fadedRating': 0,
'solidRating': 0,
'swell': {
    'minBreakingHeight': 1,
    'absMinBreakingHeight': 1.06,
    'maxBreakingHeight': 2,
    'absMaxBreakingHeight': 1.66,
    'unit': "ft",
    'components': {
         'combined': {
         'height': 1.1,
         'period': 14,
         'direction': 93.25,
         'compassDirection': "W"
    },
    'primary': {
         'height': 1,
         'period': 7,
         'direction': 83.37,
         'compassDirection': "W"
    }
}
}
}
]

In [54]: data[0]['timestamp']
Out[54]: 1366902000

In [55]: data[0]['swell']['components']['primary']['height']
Out[55]: 1

rawDescription: python api call using JSON data

description: Python api call using JSON data


code:
im = ax.imshow(ar_plts[i],
             interpolation='nearest',
             origin='lower',
             vmin=0.0,vmax=1.0)

rawDescription: label matplotlib imshow axes with strings

description: Label matplotlib imshow axes with strings


rawDescription: Pandas series removing duplicates issue

description: Pandas series removing duplicates issue


code:
import glob
import pandas as pd

fmask = 'MonthlyDataSplit/Day/Day*.csv'
df = pd.concat((pd.read_csv(f, sep=',', usecols=['Year','Month','Day','AirTemperature']) for f in glob.glob(fmask)))
df.groupby(['Year','Month','Day']).mean().to_csv('my_csv.csv')

rawDescription: Create empty csv file with pandas

description: Create empty csv file with pandas


code:
from django.core.files import File  # you need this somewhere
import urllib

# The following actually resides in a method of my model

result = urllib.urlretrieve(image_url) # image_url is a URL to an image

# self.photo is the ImageField
self.photo.save(
    os.path.basename(self.url),
    File(open(result[0]))
    )

self.save()

rawDescription: Programmatically saving image to Django ImageField


code:
a1.shape
a1.strides

rawDescription: numpy tile without memory allocation

description: Numpy tile without memory allocation


rawDescription: Python: Force pprint to display unicode strings as strings?


code:
gb = df.groupby('type')
df2 = gb.aggregate({'xy': lambda x: list(x)})

rawDescription: Pandas - convert columns to grouped array coordinates


code:
class bidirectional_iterator(object):
    def __init__(self, collection):
        self.collection = collection
        self.index = 0

    def next(self):
        try:
            result = self.collection[self.index]
            self.index += 1
        except IndexError:
            raise StopIteration
        return result

    def prev(self):
        self.index -= 1
        if self.index < 0:
            raise StopIteration
        return self.collection[self.index]

    def __iter__(self):
        return self

rawDescription: Making a python iterator go backwards?

description: Making a python iterator go backwards


code: df[pd.eval('df.fold >=2 | df.fold <=-0.6')]

rawDescription: Pandas: How to extract rows of a dataframe matching Filter1 OR filter2


code:
class Event(db.Model):
     ...

class ActiveEventManager(models.Manager):
    def get_queryset(self):
        return super(ActiveEventManager, self).get_queryset().filter(active=True)

class ActiveEvent(Event):
    class Meta:
        proxy = True

    objects = ActiveEventManager()

class ArchiveEventManager(models.Manager):
    def get_queryset(self):
        return super(ArchiveEventManager, self).get_queryset().filter(active=False)

class ArchiveEvent(Event):
    class Meta:
        proxy = True

    objects = ArchiveEventManager()

rawDescription: Why can't I register multiple Django ModelAdmin with same Model?


code:
def PolyArea2D(pts):
    lines = np.hstack([pts,np.roll(pts,-1,axis=0)])
    area = 0.5*abs(sum(x1*y2-x2*y1 for x1,y1,x2,y2 in lines))
    return area

rawDescription: Convex Hull Area in Python?

description: Convex Hull Area in Python


code:
import json
with open('output.txt', 'w') as out_file:
    json.dump(your_list, out_file)

rawDescription: Python write complex nest list into file as it is


rawDescription: numpy.loadtxt and tab separated values: data type not understood

description: Numpy.loadtxt and tab separated values: data type not understood


rawDescription: Defining function with function object passed in as argument


code:
from twython import Twython
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status='See how easy using Twython is!')

rawDescription: How do I get the private IP address of the computer that I am using in python?

description: Get the private IP address of the computer that I am using in python


code:
x = [''.join(c for c in s if c not in string.punctuation) for s in x]
print(x)

rawDescription: Removing Punctuation From Python List Items


code:
def build_pseudo_header(src_ip, dest_ip, payload_len):
    source_ip_bytes = bytearray.fromhex(src_ip)
    dest_ip_bytes = bytearray.fromhex(dest_ip)
    next_header = struct.pack(">I", 58)
    upper_layer_len = struct.pack(">I", payload_len)
    return source_ip_bytes + dest_ip_bytes + upper_layer_len + next_header

rawDescription: Computing 16-bit checksum of ICMPv6 header


code:
from collections import defaultdict

INPUT = "RegulationTwoColumnTable_Documented_2013927.tsv"

# load the data as { "ABF1": set(["ABF1", "ACS1", "ADE5,7", ... ]) }
data = defaultdict(set)
with open(INPUT) as inf:
    for line in inf:
        a,b = line.rstrip().split(";")
        if a != b:          # no self-loops
            data[a].add(b)

# find all triplets such that A -> B -> C and  A -> C
found = []
for a,bs in data.items():
    bint = bs.intersection
    for b in bs:
        for c in bint(data[b]):
            found.append("{} {} {}".format(a, b, c))

rawDescription: Print Feedforward Loops in python

description: Print Feedforward Loops in python


code:
class MySpider(BaseSpider):
    name = 'myspider'

    def __init__(self, filename=None):
        if filename:
            with open(filename, 'r') as f:
                self.start_urls = f.readlines()

rawDescription: Pass Scrapy Spider a list of URLs to crawl via .txt file


code:
x, y = np.mgrid[xslice, yslice]
plt.contour(x, y, mask[xslcie, yslice])

rawDescription: Setting position of contour sub-plot in Matplotlib


code:
def numpy_there_v2(A,val):
    out = np.zeros(val,dtype=bool)
    out[A] = 1
    return out

rawDescription: Is there a numpy.there?

description: Is there a numpy.there


rawDescription: Put zeros in front of a number to make it 4 digits


code:
import threading

def send_data_to(proc, inp):
    proc.communicate(inp)

proc = subprocess.Popen(["MyCommandHere"], stdin=subprocess.PIPE)
threading.Thread(target=send_data_to, args=(proc, bytes(my_str_input + "\n", "ascii"))).start()

rawDescription: Use subprocess.communicate() to pipe stdin without waiting for process


rawDescription: Grabbing values from within a list of string arrays?


code:
data2 = chr(date & 0xFF) + chr((date >> 8) & 0xFF) + chr(time & 0xFF) + chr((time >> 8) & 0xFF)
data2
data2.encode("hex")

rawDescription: integer to byte without using struct in python

description: Integer to byte without using struct in python


code:
import re
dirs = ['a.py', 'b/a.py', 'b/c/a.py', 'b/c/d/a.py']
py_re = re.compile('(?:.*/)?[^/]*[.]py')
[ 'Matches' if py_re.match(x) else 'Non-Matching' for x in dirs ]

rawDescription: Is it possible to transform fnmatch.translate("**/*.py") into a semantically correct regex?


code:
cat_stdin, cat_stdout = os.popen2('cat')
cat_stdin.write('foo\n')
cat_stdin.close()
cat_stdout.read()

rawDescription: Translating code using subprocess in Python 2.7 to Python 2.3


code:
class Foo(object):
    __slots__ = ('bar', 'spam')
    @property
    def __dict__(self):
        return {s: getattr(self, s) for s in self.__slots__ if hasattr(self, s)}

f = Foo()
f.bar = 42
f.__dict__
f.spam = 'eggs'
f.__dict__
vars(f)
f.hello = 'world'

rawDescription: How can I convert python class with slots to dictionary?

description: Convert python class with slots to dictionary


code:
import datetime as DT
date = DT.date.today()-DT.timedelta(days=30)
c.execute("DELETE FROM storedTweets WHERE tweetDate < ?", [date])

rawDescription: Comparing dates from from two different sources


code:
import sys
import nose

def test_number_one():
    pass

def test_number_two():
    pass

if __name__ == '__main__':
    module_name = sys.modules[__name__].__file__

    nose.main(argv=[sys.argv[0],
                    module_name,
                    '--exclude=two',
                    '-v'
                    ])

rawDescription: Python Unit-Testing: In Nose is there a way to skip a test case from nose.run()?


code:
from flask.ext.login import login_required, current_user

@app.route('/hello/')
@login_required
def my_request_handler():
    return "Current user is %s" % current_user.username

rawDescription: Application Layout with Groups of single items in Python


code:
def __init__(self, rootWin):
    ...
    self.rootWin = rootWin
    ...

def frame(self):
    frame = Frame(self.rootWin)
    ...

rawDescription: How to automatically insert several tkinter items in Tk() window using classes

description: Automatically insert several tkinter items in Tk() window using classes


code:
def myfunc(item):
  if item == 2:
    item = 1
  return item

rawDescription: How to replace an object in python

description: Replace an object in python


rawDescription: Problems capturing Python subprocess output on Mac OS X


code:
from django.forms.models import BaseInlineFormSet
class ItemInlineFormSet(BaseInlineFormSet):
   def clean(self):
      super(ItemInlineFormSet, self).clean()
      total = 0
      for form in self.forms:
         if not form.is_valid():
            return #other errors exist, so don't bother
         if form.cleaned_data and not form.cleaned_data.get('DELETE'):
            total += form.cleaned_data['cost']
      self.instance.__total__ = total

class BuyerInlineFormSet(BaseInlineFormSet):
   def clean(self):
      super(BuyerInlineFormSet, self).clean()
      total = 0
      for form in self.forms:
         if not form.is_valid():
            return #other errors exist, so don't bother
         if form.cleaned_data and not form.cleaned_data.get('DELETE'):
            total += form.cleaned_data['cost']

      #compare only if Item inline forms were clean as well
      if self.instance.__total__ is not None and self.instance.__total__ != total:
         raise ValidationError('Oops!')

class ItemInline(admin.TabularInline):
   model = Item
   formset = ItemInlineFormSet

class BuyerInline(admin.TabularInline):
   model = Buyer
   formset = BuyerInlineFormSet

rawDescription: Validation of dependant inlines in django admin


code:
while done == False:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        for i in range(len(multi_players)):
            screen.blit(multi_players[i], multi_players_pos)

        pygame.display.flip()

    clock.tick(20)

pygame.quit()

rawDescription: Pygame display multiple images randomly

description: Pygame display multiple images randomly


rawDescription: Is there a way to NOT an arbitrary M x N matrix using numpy broadcasting?


rawDescription: Padding specified in style ignored by Ttk Frame


rawDescription: Output element with the greatest value in certain position. Python


code: p_prime = np.matrix([p[i] for i in index])

rawDescription: Translating Matlab (Octave) group coloring code into python (numpy, pyplot)


code:
def __init__(self, urls_file, N=10, *a, **kw):
    data = open(urls_file, 'r').readlines()[:N]
    self.allowed_domains = [urlparse(i).hostname.strip() for i in data]
    self.start_urls = ['http://' + domain for domain in self.allowed_domains]
    super(DownloadSpider, self).__init__(*a, **kw)

rawDescription: Crawling multiple sites with Python Scrapy with limited depth per site


code: df

rawDescription: Conditional Cell Substitution in Pandas, Python 2.7


code:
import Image
import numpy as np

def get_data(im, x_range, x_offset, y_range, y_offset):
    x_data = np.array([])
    y_data = np.array([])
    width, height = im.size
    im = im.convert('1')
    for x in xrange(width):
        for y in xrange(height):
            if im.getpixel((x, y)) == 0:
                x_data = np.append(x_data, x)
                y_data = np.append(y_data, height - y)
                break
    x_data = (x_data / width) * x_range + x_offset
    y_data = (y_data / height) * y_range + y_offset
    return x_data, y_data

im = Image.open('clean_data_2.png')
x_data, y_data = get_data(im,4.4-0.55,0.55,23000-2500,2500)

from pylab import *
plot(x_data, y_data)
grid(True)
savefig('new_data.png')
show()

rawDescription: Image analysis on scientific chromatograms


code:
with open('file01.txt') as fobj1, open('file02.txt') as fobj2:
    data1 = fobj1.readlines()
    data2 = fobj2.readline()

code = data2.split('|', 1)[0]

with open('file01.txt', 'w') as fobj_out:
    for line in data1:
        if line.split('|', 1)[0] == code:
            fobj_out.write(data2 + '\n')
        else:
            fobj_out.write(line)

rawDescription: Replacing data to different file

description: Replacing data to different file


code:
from sqlalchemy.ext.hybrid import hybrid_property

@hybrid_property
def name (self):
    first_name = self.first_name if self.first_name is not None else ""
    middle_name = self.middle_name if self.middle_name is not None else ""
    last_name = self.last_name if self.last_name is not None else ""
    return " ".join((first_name, middle_name, last_name)).strip()

@name.setter
def name (self,string):
    first_name = ""
    middle_name = ""
    last_name = ""
    split_string = string.split(' ')
    if len(split_string) == 1:
        first_name = string
    elif len(split_string) == 2:
        first_name, last_name = split_string
    elif len(split_string) == 3:
        first_name, middle_name, last_name = split_string
    else: #len(split_string) > 3:
        first_name = split_string[0]
        last_name = split_string[-1]
        middle_name = " ".join(split_string[1:-2])
    self.first_name = first_name
    self.middle_name = middle_name
    self.last_name = last_name

rawDescription: How to create a class attribute and class property within Elixir/SqlAlchemy

description: Create a class attribute and class property within Elixir/SqlAlchemy


code:
a = b = c = d = 4
a
b
c
d

rawDescription: Defining multiple variables at once in one line with one value?


code:
import pandas as pd
df = pd.DataFrame.from_records(data)

rawDescription: Selecting all columns from related model with django queryset


code:
k = ''
for i in range(0,8):
            key = random.randint(33,126)
            k += chr(key)
print('Eight-Character Key: ',k,end='')

rawDescription: How to display a string of integers and letters from a for loop

description: Display a string of integers and letters from a for loop


rawDescription: product of arrays of different sizes in numpy

description: Product of arrays of different sizes in numpy


code: random.sample(visited.nonzero(), k)

rawDescription: Python, random sample from a vector's non-zero indices


rawDescription: How to hide "cgi-bin", ".py", etc from my URLs?

description: Hide "cgi-bin", ".py", etc from my URLs


code:
import os
import goright
path = os.path.abspath(goright.__file__)[:-1]
with open(path) as f:
    content = f.read()
print(content)

rawDescription: read the code from another python script

description: Read the code from another python script


code:
@patch('module1.function1')
def my_test(function1):
    function1.side_effect = function_object
    # Do stuff

rawDescription: Python assign a function to another function


code:
def sort_by_month(entry):
    return meses_ord[entry['month']]

sorted(fechas_, key=sort_by_month)

rawDescription: Order a list of dictionaries based on another dictionary


rawDescription: Is print (N + 1) called every time the function is called or does it only print until N is 0?


code:
import nltk
import nltk.book as book
text1 = book.text1
c = nltk.ConcordanceIndex(text1.tokens, key = lambda s: s.lower())
print([text1.tokens[offset+1] for offset in c.offsets('monstrous')])

rawDescription: Calling NLTK's concordance - how to get text before/after a word that was used?


code:
import pandas as pd
import json

df = pd.read_csv('data', header=None)
dates, df = df[0], df.iloc[:, 1:]
df = pd.concat([df, dates.apply(lambda x: pd.Series(json.loads(x)))], axis=1,
               ignore_index=True)
print(df)

rawDescription: Python pandas.read_csv split column into multiple new columns using comma to separate


code: "/a/itemInfo/?video_id=" + video_id + "&ac=www&t=grp&r=" + a.getTime();

rawDescription: How to enter a parameter for a HTTP GET request that doesn't have a name?

description: Enter a parameter for a HTTP GET request that doesn't have a name


code:
def interlock(s1,s2):
    out = ""
    while s1 and s2: # keep looping until any string is empty
        out += s1[0] + s2[0]
        s1, s2 = s1[1:], s2[1:]
    return out +  s1 + s2 # add the remainder of any longer string

word_list = ["test", "col", "tele", "school", "tel", "sho","col" "aye"]

from itertools import permutations
# get all permutations of len 2 from our word list
perms = permutations(word_list,2)

st = set(word_list)
for a, b in perms:
    res = interlock(a,b)
    if res in st:
        print(res)
school

rawDescription: Looping a function over a list in Python


code:
import numpy as np
import scipy.integrate as si

def test_fn(x, c):
    return c / x

def main():
    lower_limit =  8.0
    target_area =  2.5
    c_val       = 42.0
    for upper_limit in np.arange(8., 10., 0.1):
        area = si.quad(test_fn, lower_limit, upper_limit, args=(c_val,))
        if area >= target_area:
            print("Area is {} at ul={}".format(area, upper_limit))
            break

if __name__=="__main__":
    main()

rawDescription: Integrate in a if statement? (python)

description: Integrate in a if statement? (python)


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

import urlparse

import cherrypy

config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  },
  '/' : {
     'tools.postoverride.on' : True,
   }
}

def postOverride():
  cherrypy.request.params.update(cherrypy.request.body.params)

cherrypy.tools.postoverride = cherrypy.Tool('before_handler', postOverride)

class HelloWorld:

  @cherrypy.expose
  def index(self, name):
    html = """<form method="post">
      <input type="text" name="name" value="%s" /></form>
      Hello %s!""" % (name, name)
    return html

if __name__ == '__main__':
  cherrypy.quickstart(HelloWorld(), '/', config)

rawDescription: CherryPy combining querystring value with form value in POST body


code:
for index, (value,num) in enumerate(sorted_list, start=1):
    print("{}.\t{:<5}\t{:>5}".format(index, value,num))

rawDescription: Creating numbered list of output

description: Creating numbered list of output


code:
@foo
def bar():
    pass

rawDescription: Nested python decorator?

description: Nested python decorator


code: [dict(x.items() + y.items()) for x, y in zip(lis1, lis2)]

rawDescription: zip 2 lists of dictionaries into 1

description: Zip 2 lists of dictionaries into 1


code:
import os
os.environ["THEANO_FLAGS"] = "mode=FAST_RUN,device=gpu,floatX=float32"
import theano

rawDescription: Theano config directly in script

description: Theano config directly in script


code:
entries = []
for i in range (1, 4): # or more
    e = NewEntry(master=MainFrame,idnumber=str(i))
    entries.append(e)
# Or more simply,
# entries = [NewEntry(master=MainFrame, idnumber=str(i)) for i in range(1,4)]

rawDescription: How get value from Tkinter Var in class?

description: How get value from Tkinter Var in class


code:
l = [l1, l2, l3]
[''.join(item) for item in zip(*l)]

rawDescription: How to concatenate strings in multiple lists at the same index

description: Concatenate strings in multiple lists at the same index


code:
if talk.upper() == "HOW ARE YOU":
    perform_action()

rawDescription: How would I save time with or statements in Python?


code: min(((d[s],s) for s in d if s.startswith('a')))[1][1:]

rawDescription: Python dictionaries - find second character in a 2-character string which yields minimum value


code:
import socket
socket.inet_aton("127.0.0.1")    # valid
socket.inet_aton("127.1")        # oh yes this is valid too!
socket.inet_aton("127.0.0,1")    # this isn't

rawDescription: validating IP address - python

description: Validating IP address - python


code:
import pandas as pd

df = pd.DataFrame()
df['ID'] = [1, 1, 1, 2, 2]
df['Type'] = ['A', 'B', 'Q', 'B', 'R']
df['Status'] = [0, 0, 1, 0, 1]

g = df.groupby("ID")[["Type","Status"]]
df2 = g.apply(pd.DataFrame.reset_index, drop=True).unstack()

rawDescription: Pivot Pandas Dataframe and calculate 'columns' parameter


code: #!C:/Python25/python.exe -u

rawDescription: Python cgi and stdin

description: Python cgi and stdin


code: [(x == y == 1) for x, y in zip(Actual, Predicted)]

rawDescription: How to compare two arrays in python based on a value

description: Compare two arrays in python based on a value


code:
import re
content = '''
[CONTENT BEFORE TABLE]

[IP ADDRESSES AND OTHER INFO]

[CONTENT AFTER TABLE]
'''
pat = r"(.*)
(.*)
(.*)"
re.match(pat, content, re.DOTALL)
re.match(pat, content, re.DOTALL).group(2)

rawDescription: Extracting a table from webpage with regex


code:
from numpy import cumsum
from operator import itemgetter

d={'dan':7, 'mike':2, 'john':3}

#unzip keys from values in a sorted order
keys, values = zip(*sorted(d.items(), key=itemgetter(1)))
total = sum(values)

# calculate cumsum and zip with keys into new dict
d_cump = dict(zip(keys, (100*subtotal/total for subtotal in cumsum(values))))

rawDescription: creating cumulative percentage from a dictionary of data

description: Creating cumulative percentage from a dictionary of data


rawDescription: Why do different methods of same object have the same `id`?


rawDescription: Checking to see if array elements are equal


code:
print(counter1['a'] == counter2['a'])
# True

rawDescription: How to compare the value of the key in Dict 1 is "==" or"!=" value of the same key in Dict2,if exists

description: Compare the value of the key in Dict 1 is "==" or"!=" value of the same key in Dict2,if exists


code:
my_list.append('x')
my_list

rawDescription: __getattr__ throwing maximum recursion error when __setattr__ implemented


code:
with open("yourfilepath.json", "r") as f:
    obj = json.loads(f.read())

rawDescription: Write Python dictionary obtained from JSON in a file


code:
def parse_links(self, response):
    hxs = Selector(response)
    links = hxs.xpath('//a[contains(@href, "topic")]')
    for link in links:
        title = ''.join(link.xpath('./@title').extract())
        url = ''.join(link.xpath('./@href').extract())
        meta={'title':title,}
        yield Request(url, callback = self.parse_posts, meta=meta,)

parse_start_url = parse_links

rawDescription: python Scrapy CrawlSpider: Rule doesn't apply after logged in, only crawled the first page

description: Python Scrapy CrawlSpider: Rule doesn't apply after logged in, only crawled the first page


code: import operator

rawDescription: Find the Common first_name from Django Auth user Model


rawDescription: How to list X numbers in base of Y?

description: List X numbers in base of Y


rawDescription: dictionary in python problem

description: Dictionary in python problem


code:
[[[{k:v[0] for (k,v) in change_dict.items()} for change_dict in list_of_dicts]
  for list_of_dicts in list_of_lists]
 for list_of_lists in mydata]

rawDescription: LDAP Python query and converting the appropriate dictionary


rawDescription: Extracting Groups

description: Extracting Groups


code:
output
combination :E2R
PrACCEL
combination :C4W
PEAwCEL
combination :E6G
PEACCgL
combination :E2R_C4W
PrAwCEL
combination :E2R_E6G
PrACCgL
combination :C4W_E6G
PEAwCgL
combination :E2R_C4W_E6G
PrAwCgL

rawDescription: how to make two or more combinations of specific letter?

description: Make two or more combinations of specific letter


rawDescription: Check if string contains a certain amount of words of another string


code: [list(l[0]) for l in mylist]

rawDescription: Split words in a nested list into letters


code: df = pd.read_table('path', sep=' ', skiprows=4, names = ['date', 'time'])

rawDescription: How to skip text being used as column heading using python

description: Skip text being used as column heading using python


rawDescription: Parsing an escape character in Python

description: Parsing an escape character in Python


code: if myboolean==true : ...

rawDescription: if True and if False statements

description: If True and if False statements


code:
import scrapy

class PremierleagueItem(scrapy.Item):
    round = scrapy.Field()
    date = scrapy.Field()
    time = scrapy.Field()
    place = scrapy.Field()
    opponent = scrapy.Field()
    results = scrapy.Field()
    clubName = scrapy.Field()
    matches = scrapy.Field()

class PremierleagueSpider(scrapy.Spider):
    name = "premierleague"
    allowed_domains = ["worldfootball.net"]
    start_urls = [
        "http://www.worldfootball.net/competition/eng-premier-league/"
    ]

    # get teams in the match
    def parse(self, response):

        for sel in response.xpath('//div[@id="tabelle_0"]/div[@class="data"]/table[1]/tr'):

            clubName = sel.xpath('.//td[3]/a/text()').extract()

            if clubName:
                item = PremierleagueItem()

                item['clubName'] = clubName

                clubHref = sel.xpath('.//td[2]/a/@href').extract_first()
                clubUrl = response.urljoin(clubHref)

                request = scrapy.Request(clubUrl, callback=self.parse_get_historic_results_link)

                request.meta['item'] = item
                yield request

    def parse_get_historic_results_link(self, response):

        item = response.meta['item']

        href2 = response.xpath('//div[@class="navibox2"]/div[@class="data"]/ul[5]/li[2]/a[1]/@href').extract_first()
        url2 = response.urljoin(href2)

        request = scrapy.Request(url2, callback=self.parse_seasons)

        request.meta['item'] = item
        yield request

    def parse_seasons(self, response):

        item = response.meta['item']

        for sel in response.xpath('(//table[@class="standard_tabelle"])[1]/tr/td[2]/a'):
            href = sel.xpath('.//@href').extract_first()
            url = response.urljoin(href)

            request = scrapy.Request(url, callback=self.parse_results)
            request.meta['item'] = item

            yield request

    @staticmethod
    def parse_results(response):

        item = response.meta['item']

        item['matches'] = []
        for sel in response.xpath('(//table[@class="standard_tabelle"])[1]/tr[position() > 3]'):
                matchDict = dict(zip((
                    'round',
                    'date',
                    'place',
                         'opponent',
                'results'), filter(None, map(unicode.strip,(sel.xpath("./td[normalize-space(.)]//text()").extract())))))
                item['matches'].append(matchDict)
        yield item

rawDescription: My scraper yields too many items instead of merging them all into only a small bunch


code: import pdb; pdb.set_trace()

rawDescription: Breaking down numpy code

description: Breaking down numpy code


code: my_expr = originalTextFor(my_expr)

rawDescription: Pyparsing - literal text with line breaks in varying locations


code:
def add_value_to_dict(d, key, value):
    d[key] = value

logging_dict = LoggingDict()

add_value_to_dict(logging_dict, 'testkey', 'testvalue')

rawDescription: why types/class unification majorly in python

description: Why types/class unification majorly in python


code:
#!/usr/bin/env python
import ctypes
import numpy
from _add_vectors import add_vectors

#Random vectors to add:
a = numpy.double([1,2,3,4])
b = numpy.double([3,4,5,6,7])

#Zero out the return value:
c = numpy.double([0,0,0,0,0])
add_vectors(a, b, c)
print(a)
print(b)
print(c)

rawDescription: C function called via Python determines wrong array size


code:
df.Sales
df.Sales.str.replace("$", "")
pd.to_numeric(df.Sales.str.replace("$", ""))
pd.to_numeric(df.Sales.str.replace("$", "")).sum()

rawDescription: Add values in column of Panda Dataframe

description: Add values in column of Panda Dataframe


rawDescription: I need to replace all the characters of string in python


code: len(re.findall(r'(?=(%s))' % re.escape(needle), haystack))

rawDescription: How can I find the number of overlapping sequences in a String with Python?

description: Find the number of overlapping sequences in a String with Python


code:
def count_neighbours(arr1, arr2, rad):
    rad2 = rad * rad
    ret = np.empty((len(arr1),), dtype=np.intp)
    for j, point in enumerate(arr1):
        delta = point - arr2
        delta *= delta
        dist2 = np.sum(delta, axis=1)
        ret[j] = np.count_nonzero(dist2 <= rad2)
    return ret

rawDescription: Trying to perform an operation on all sub arrays inside a numpy array without using a for (or similar) loops


rawDescription: Convert Pandas Series to DateTime in a DataFrame


code: positions = re.finditer("test", string)

rawDescription: Converting iterator to list changes the iterator


code:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(100)

def geometric_brownian_motion(T=1, N=100, mu=0.1, sigma=0.01, S0=20):
    """
    http://stackoverflow.com/a/13203189/190597 (unutbu)
    """
    dt = float(T) / N
    t = np.linspace(0, T, N)
    W = np.random.standard_normal(size=N)
    W = np.cumsum(W) * np.sqrt(dt)  # standard brownian motion ###
    X = (mu - 0.5 * sigma ** 2) * t + sigma * W
    S = S0 * np.exp(X)  # geometric brownian motion ###
    return S

N = 10 ** 6
a = geometric_brownian_motion(T=1, mu=0.1, sigma=0.01, N=N)
b = geometric_brownian_motion(T=1, mu=0.2, sigma=0.01, N=N)

cov = np.cov(a, b)
print(cov)
# [[ 0.38234755  0.80525967]
#  [ 0.80525967  1.73517501]]
beta = cov[1, 0] / cov[0, 0]
print(beta)
# 2.10609347015

plt.plot(a)
plt.plot(b)
plt.show()

rawDescription: Correlation between columns in DataFrame


code:
for domain, ip in addresses.items():
    banner, body = http_banner_grabber(ip, method="GET", http_type='HTTP/0.9')
    print('*' * 24)
    print(domain, ip, 'GET HTTP/0.9')
    print(banner)

rawDescription: Banner grabbing HTTP

description: Banner grabbing HTTP


code:
import pandas as pd
import io

one="""iq, name
69, joe
120, james"""

two="""iq_start, iq_end, category
130,500, Very Superior
120,129,    Superior
110,119,    High Average
90,109, Average
80,89,  Low Average
70,79,  Borderline
0,69,   Extremely Low"""

three="""iq, career
69 , manual work
120, doctor"""

df1 = pd.read_csv(io.BytesIO(one), skipinitialspace=True)
df2 = pd.read_csv(io.BytesIO(two), skipinitialspace=True)
df3 = pd.read_csv(io.BytesIO(three), skipinitialspace=True)

iqmap = pd.Series(df2.category.values, index=df2.iq_start).sort_index()

df = pd.merge(df1, df3)
df["category"] = iqmap.asof(df.iq).values
df.set_index("iq", inplace=True)
df.T.to_dict()

rawDescription: Using pandas to merge data and output Json


code:
union = dict_1.copy()
union.update(dict_2)

rawDescription: Different __hash__ and __eq__ methods for use in set


rawDescription: Designing a joint function

description: Designing a joint function


code:
from threading import Event, RLock

class Token:
    _internal = RLock()
    _marker = False
    def __init__(self):
        # TODO set header
        self._header = None

    def _renew(self):
        # TODO refresh the header
        pass

    def get(self):
        with self._internal:
            if self._marker:
                self._renew()
                self._marker = False
            return self._header

    # Marks the header to be refreshed at the next get()
    def set_renew(self):
        with self._internal:
            self._marker = True

rawDescription: Python: Is there a thread safe way to know if lock.acquire() has blocked (and continue blocking)?


code:
class TrainCar:
    def __init__(self, data):
        # this is the contents of our train car
        self.data = data
        # This is the reference to the next node, or the train car's connector.
        # Accessing it gets you the next TrainCar, if one exists
        self.next_car = None

rawDescription: just another evil hangman quesiton

description: Just another evil hangman quesiton


code:
import sys, pygame, os, math

# Force static position of screen
os.environ['SDL_VIDEO_CENTERED'] = '1'

# Constants
LEFT = 'left'
RIGHT = 'right'

BLACK = (0, 0, 0)
GRAY = (70, 70, 70)
WHITE = (255, 255, 255)

WIN_W = 16*32
WIN_H = 800

SHIP_WIDTH = WIN_W/15
SHIP_HEIGHT = WIN_H/15

class Entity(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

class Ship(Entity):
    def __init__(self, container):
        Entity.__init__(self)
        self.speed = 5
        self.image = pygame.Surface((SHIP_WIDTH, SHIP_HEIGHT)).convert()
        self.rect = self.image.get_rect()
        self.rect.centerx = container.centerx
        self.rect.y = container.bottom - self.rect.height * 2
        self.container = container

    def update(self):
        key = pygame.key.get_pressed()
        if key[pygame.K_w]:
            self.rect.centery -= self.speed
        if key[pygame.K_s]:
            self.rect.centery += self.speed
        if key[pygame.K_d]:
            self.rect.centerx += self.speed
        if key[pygame.K_a]:
            self.rect.centerx -= self.speed

        self.rect.clamp_ip(self.container)

class Camera(object):
    def __init__(self, camera_func, width, height):
        self.camera_func = camera_func
        self.state = pygame.Rect(0, 0, width, height)

    def apply(self, target):
        return target.rect.move(self.state.topleft)

    def update(self, target):
        self.state = self.camera_func(self.state, target.rect)

def simple_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    return pygame.Rect(-l+WIN_W/2, -t+WIN_H/2, w, h)

def complex_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    l, t, _, _ = -l+WIN_W/2, -t+WIN_H/2, w, h

    l = min(0, l)                           # stop scrolling at the left edge
    l = max(-(camera.width-WIN_W), l)   # stop scrolling at the right edge
    t = max(-(camera.height-WIN_H), t) # stop scrolling at the bottom
    t = min(0, t)                           # stop scrolling at the top
    return pygame.Rect(l, t, w, h)

class CameraGroup(pygame.sprite.Group):
    def __init__(self, camera):
        pygame.sprite.Group.__init__(self)
        self.camera = camera

    def draw(self, surface):
        sprites = self.sprites()
        surface_blit = surface.blit
        for spr in sprites:
            self.spritedict[spr] = surface_blit(spr.image, self.camera.apply(spr))
        self.lostsprites = []

class Platform(Entity):
    def __init__(self, x, y):
        Entity.__init__(self)
        self.image = pygame.Surface((32, 32))
        self.image.convert()
        self.image.fill(GRAY)
        self.rect = pygame.Rect(x, y, 32, 32)

    def update(self):
        pass

def main():
    # Initialize Everything
    pygame.init()
    fps = 60
    clock = pygame.time.Clock()
    play = True
    pygame.display.set_caption('Raiden')
    screen = pygame.display.set_mode((WIN_W, WIN_H), pygame.SRCALPHA)

    # Load Level
    platforms = []
    x = y = 0
    level = [
        "PPPPPPPPPPPPPPPP",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "PPPP           P",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "PPPP           P",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "P           PPPP",
        "P              P",
        "PPPP           P",
        "P              P",
        "PPPP           P",
        "P              P",
        "P           PPPP",
        "P              P",
        "P              P",
        "PPPP           P",
        "P              P",
        "P              P",
        "P           PPPP",
        "P              P",
        "PPPP           P",
        "P              P",
        "P           PPPP",
        "P              P",
        "PPPP           P",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "PPPP           P",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "P           PPPP",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "PPPP           P",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "P              P",
        "PPPPPPPPPPPPPPPP",]

    total_level_width = len(level[0])*32
    total_level_height = len(level)*32
    total_rect = pygame.rect.Rect(0, 0, total_level_width, total_level_height)

    # Create Groups
    camera = Camera(complex_camera, total_level_width, total_level_height)
    shipGroup = CameraGroup(camera)
    backgroundGroup = CameraGroup(camera)

    # build the level
    for row in level:
        for col in row:
            if col == "P":
                p = Platform(x, y)
                platforms.append(p)
                backgroundGroup.add(p)
            x += 32
        y += 32
        x = 0

    # Create Game Objects
    ship = Ship(total_rect)

    # Add Game Objects to Groups
    shipGroup.add(ship)

    # Gameplay
    while play:
        # Checks if window exit button pressed
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()

        camera.update(ship)
        # Update
        ship.update()

        # Print Background/Sprites
        screen.fill(WHITE)

        backgroundGroup.draw(screen)
        shipGroup.draw(screen)

        # Limits frames per iteration of while loop
        clock.tick(fps)
        # Writes to main surface
        pygame.display.flip()

if __name__ == "__main__":
    main()

rawDescription: Adding scrolling to a top/down shooter

description: Adding scrolling to a top/down shooter


code:
fig, axes = plt.subplots(nrows=4, sharex=True)
for y, ax in zip(ydata, axes):
    ax.plot(x, y, color='salmon')
    ax.locator_params(axis='y', nbins=5, prune='both')
plt.show()

rawDescription: Python Numpy 2D plot set total number of y-tics with autoscaling


code:
from itertools import islice

def split_every(n, iterable):
    i = iter(iterable)
    piece = list(islice(i, n))
    while piece:
        yield piece
        piece = list(islice(i, n))

rawDescription: split a generator/iterable every n items in python (splitEvery)

description: Split a generator/iterable every n items in python (splitEvery)


code:
from webapp2_extras.appengine.auth.models import User as Webapp2User

class User(Webapp2User):
    username = ndb.StringProperty(required=True)

rawDescription: Adding a username property to webapp2 User model after entity has been created (with Simpleauth)


code:
df[key] = df[key].mul(d[key])
df

rawDescription: Using lambda function to multiply columns of a pandas dataframe by a different value for each column


code:
def findKSmallest( self, k, rightSteps=0 ):
    if rightSteps >= k: #We went right more than k times
        return []
    leftSmallest = self.left.findKSmallest( k, rightSteps ) if self.left != None else []
    rightSmallest = self.right.findKSmallest( k, rightSteps + 1 ) if self.right != None else []
    mySmallest = sorted( leftSmallest + [self.data] + rightSmallest )
    return mySmallest[:k]

rawDescription: Python recursion - how to exit early

description: Python recursion - how to exit early


code: gene.join(df, how="outer")

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


code:
df
df.index.get_level_values('Period')
df.index.get_level_values('Period') != 0
df[df.index.get_level_values('Period') != 0]
df.ix[df.index.get_level_values('Period') != 0, 'Value'] = 0
df

rawDescription: pandas multi-index how to mask the data by the second level

description: Pandas multi-index how to mask the data by the second level


rawDescription: Create a subset of a DataFrame dependant on column name


rawDescription: comparing numpy structured arrays

description: Comparing numpy structured arrays


rawDescription: Making lookup table in python, writing to a binary file that can be read in in a C program


code:
longest = max([len(x[0]) for x in data])

for j in data:
    a = j[0].ljust(longest)
    b = str(j[1])
    print(' '.join([a, b]))

rawDescription: Python: Is there a way to pretty-print a list?


code:
import xml.etree.ElementTree as ET
root = ET.parse(filename).getroot()

# The dot represents current nested level from root, else you must include other parent tags here
l_list = []
for node in root.findall("./l"):
    # tag.text is the attribute for the text between the tag
    l_list.append(node.text)

bib_list = []
for node in root.findall("./bib"):
    bib_list.append(node.text)

rawDescription: Python parsing multiple xml tags

description: Python parsing multiple xml tags


code:
def kthsmallest(A, B, k):
    if k < 1:
        return None
    a_len, b_len = len(A), len(B)
    if a_len == 0:
        return B[k-1] # let it die if B is too short, I don't care
    if b_len == 0:
        return A[k-1] # see above
    # Handle edge case: if k == a_len + b_len, we would
    # get an out-of-bounds index, since i + j <= a_len+b_len - 2
    # for valid indices i and j
    if a_len + b_len == k:
        if A[-1] < B[-1]:
            return B[-1]
        else:
            return A[-1]
    # Find indices i and j approximately proportional to len(A)/len(B)
    i = (a_len*(k-1)) // (a_len+b_len)
    j = k-1-i
    # Make sure the indices are valid, in unfortunate cases,
    # j could be set to b_len by the above
    if j >= b_len:
        j = b_len-1
        i = k-1-j
    if A[i] <= B[j]:
        if j == 0 or B[j-1] <= A[i]:
            return A[i]
        # A[i] < B[j-1] <= B[j]
        return kthsmallest(A[i:], B[:j], k-i)
    # B[j] < A[i], symmetrical to A[i] < B[j]
    if i == 0 or A[i-1] <= B[j]:
        return B[j]
    # B[j] < A[i-1]
    return kthsmallest(A[:i], B[j:], k-j)

rawDescription: Finding the kth-smallest element in union of sorted arrays


code:
import csv

def get_html_table(data):
    s = '
\n'
    for row in data:
        s += '
'
        for cell in row:
            s += r'{}	'.format(cell)
        s += '
\n'
    s += '
'
    return s

with open('testscore.txt') as ifile, open('output.html', 'wb') as ofile:
    data = []
    for row in list(csv.reader(ifile))[1:]:
        data.append([row[0], row[1], row[3], '{0:0.2f}'.format(float(row[6]))])
    ofile.write(get_html_table(data))

rawDescription: Creating a table a CSV and publishing the student results to a website?


code:
for trial, line in parse(open('test.txt', 'r')):
    print(trial, line)

rawDescription: Extracting information between strings in a text file


rawDescription: Efficient way of appending / extracting list elements


code:
import random

import tkinter as tk

# --- constants --- # UPPERCASE name

RES_X = 800
RES_Y = 600

# --- classes --- # CamelCase name

class Enemy(object):
    '''single enemy'''

    def __init__(self, canvas):

        # access to canvas
        self.canvas = canvas

        self.radius = 12.5 # random

        self.color = random.choice( ('black', 'red', 'green', 'blue', 'yellow') )

        self.x = random.uniform(self.radius, RES_X-self.radius)
        self.y = random.uniform(self.radius, RES_Y-self.radius)

        self.x1 = self.x-self.radius
        self.y1 = self.y-self.radius

        self.x2 = self.x+self.radius
        self.y2 = self.y+self.radius

        self.oval = self.canvas.create_oval(self.x1, self.y1, self.x2, self.y2, fill=self.color, outline=self.color)

        self.moving = True

        self.start()

    def start(self):
        '''start moving'''

        self.moving = True

        # move this enemy after random time
        random_time = random.randint(150, 3000)
        root.after(random_time, self.move)

    def stop(self):
        '''stop moving'''

        self.moving = False

    def move(self):

        if self.moving: # to stop root.after
            direction = random.randint(1,4)

            if direction == 1: # up
                self.y -= self.radius
                self.y1 -= self.radius
                self.y2 -= self.radius
            elif direction == 2: # down
                self.y += self.radius
                self.y1 += self.radius
                self.y2 += self.radius
            elif direction == 3: # left
                self.x -= self.radius
                self.x1 -= self.radius
                self.x2 -= self.radius
            elif direction == 4: # right
                self.x += self.radius
                self.x1 += self.radius
                self.x2 += self.radius

            self.canvas.coords(self.oval, self.x1, self.y1, self.x2, self.y2)

            # move this enemy after random time
            random_time = random.randint(150, 3000)
            root.after(random_time, self.move)

class EnemiesGroup(object):

    def __init__(self, canvas):

        self.canvas = canvas

        self.enemies = list()

        self.moving = True

    def add_new_enemy(self):

        # can be only 5 enemies
        if len(self.enemies) < 5:
            e = Enemy(self.canvas)

            # stop new enemy if all enemies are stoped
            e.moving = self.moving

            self.enemies.append(e)
        else:
            print("You have 5 enemies - I can't add more.")

    def stop_all_enemies(self):
        for e in self.enemies:
            e.stop()

        # all enemies are stoped
        self.moving = False

    def start_all_enemies(self):
        for e in self.enemies:
            e.start()

        # all enemies are moving
        self.moving = True

# --- functions --- # lower_case name

def add_new_enemy():

    enemies_group.add_new_enemy()

    # add next enemy after random time
    timer = random.randint(150, 3000)
    root.after(random_time, add_new_enemy)

# --- main ---

root = tk.Tk()
root.title("")

canvas = tk.Canvas(root, width=RES_X, height=RES_Y, bg="white")
canvas.pack()

# enemies

enemies_group = EnemiesGroup(canvas)

for _ in range(5):
    enemies_group.add_new_enemy()

# add new enemy after random time
random_time = random.randint(150, 3000)
root.after(random_time, add_new_enemy)

# buttons to control all enemies

button_stop = tk.Button(root, text='STOP', command=enemies_group.stop_all_enemies)
button_stop.pack()

button_start = tk.Button(root, text='START', command=enemies_group.start_all_enemies)
button_start.pack()

button_add = tk.Button(root, text='ADD NEW ENEMY', command=enemies_group.add_new_enemy)
button_add.pack()

root.mainloop()

rawDescription: appending code to create multiple random moving sprites - python tkinter

description: Appending code to create multiple random moving sprites - python tkinter


rawDescription: How can I easily determine if a Boto 3 S3 bucket resource exists?

description: Easily determine if a Boto 3 S3 bucket resource exists


code:
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.decomposition import TruncatedSVD
data = fetch_20newsgroups()
vectorizer = TfidfVectorizer(min_df=3, max_df=.95, stop_words='english')
lsa = TruncatedSVD(n_components=10)
km = KMeans(n_clusters=3)
X = vectorizer.fit_transform(data.data)
X_lsa = lsa.fit_transform(X)
km.fit(X_lsa)

rawDescription: sklearn decomposition top terms

description: Sklearn decomposition top terms


rawDescription: Transform irregular quadrilateral to rectangle in python matplotlib


rawDescription: Generating a map/graph for a traveling salesmanproblem (Python)


code:
def qs_ancestors(queryset):
    if isinstance(queryset, EmptyQuerySet):
        return queryset
    new_queryset = queryset.none()
    for obj in queryset:
        new_queryset = new_queryset | obj.get_ancestors()
return new_queryset

rawDescription: efficient function to retrieve a queryset of ancestors of an mptt queryset

description: Efficient function to retrieve a queryset of ancestors of an mptt queryset


code:
mi, ma, bs, bks = buckets(discrete_set)
buckelems = list(bks.elements())

rawDescription: create distribution from a list and generate random numbers which follow that distribution in Python

description: Create distribution from a list and generate random numbers which follow that distribution in Python


code: self.btn_a1 = Button('Text', self)

rawDescription: Custom button PyQT4

description: Custom button PyQT4


code:
# parse the page HTML with the form to get the form target and any input names and values... (except for a submit and reset button)
# You can use XML.dom.minidom or htmlparser
# form_target gets parsed into "http://mysite.com/blah.php"
# input1_name gets parsed into "in1"
# input1_value gets parsed into "abc"

form_url = form_target + "?" + input1_name + "=" + input1_value
# form_url value is "http://mysite.com/blah.php?in1=abc"

# Then open the new URL which is the same as clicking the submit button
s = urllib2.urlopen(form_url)

rawDescription: Python: Clicking a button with urllib or urllib2


rawDescription: Sorting and using maps in Python

description: Sorting and using maps in Python


code:
_base_js_escapes = (
    ('\\', r'\u005C'),
    ('\'', r'\u0027'),
    ('"', r'\u0022'),
    ('>', r'\u003E'),
    ('<', r'\u003C'),
    ('&', r'\u0026'),
    ('=', r'\u003D'),
    ('-', r'\u002D'),
    (';', r'\u003B'),
    (u'\u2028', r'\u2028'),
    (u'\u2029', r'\u2029')
)

# Escape every ASCII character with a value less than 32.
_js_escapes = (_base_js_escapes +
               tuple([('%c' % z, '\\u%04X' % z) for z in range(32)]))

def escapejs(value):
    """Hex encodes characters for use in JavaScript strings."""
    for bad, good in _js_escapes:
        value = mark_safe(force_unicode(value).replace(bad, good))
    return value

rawDescription: How can I use Django built-in filters with Jinja2 using Appengine SDK?

description: Use Django built-in filters with Jinja2 using Appengine SDK


code:
import re

sentence_end = re.compile(r'(?<=[.?!])\s+')

for sentence in sentence_end.split(nX):
   pn(sentence)

rawDescription: How can I do lines of a single string sleep before being printed?

description: Do lines of a single string sleep before being printed


rawDescription: dataframe pandas subset series

description: Dataframe pandas subset series


code:
from tkinter import *
from functools import partial
from tkinter import messagebox
root = Tk()
root.title("Calculator")
root.geometry("317x145")

menubar = Menu(root)

class Calculator(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        master.bind("<Key>", self.key)
        display = Frame(root, bd=0, width=1000, height=1000, relief=SUNKEN)
        buttons = Frame(root, bd=0, width=7, height=1, relief=GROOVE)
        display.grid(column=0, row=0, padx=0, pady=0)
        buttons.grid(column=0, row=1, padx=1)
        numbers = StringVar()
        self.results = Entry(display, textvariable=numbers, width=31, fg="black", bg="snow", font="Verdana")
        self.results.pack()
        self.results.grid(column=0, row=0)

        numbers=["7", "4", "1", "8", "5", "2", "9", "6", "3"]
        for i in range(9):
            n=numbers[i]
            Button(buttons, bg="snow", text=n, width=7, height=1, command=self.show_up(n), relief=RAISED).grid(row=i%3, column=i//3)
        Clear = Button(buttons, bg="snow", text="C", width=7, height=1, command=self.clear, relief=RAISED)
        Clear.grid(padx=2, pady=2, column=3, row=0)
        Equals = Button(buttons, bg="snow", text="=", width=7, height=1, command=self.equals, relief=RAISED)
        Equals.grid(padx=2, pady=2, column=4, row=3)
        All_clear = Button(buttons, bg="snow", text="AC", width=7, height=1, command=self.all_clear, relief=RAISED)
        All_clear.grid(padx=2, pady=2, column=4, row=0)
        Bracket_one = Button(buttons, bg="snow", text="(", width=7, height=1, command=self.bracket_one, relief=RAISED)
        Bracket_one.grid(padx=2, pady=2, column=2, row=3)
        Bracket_two = Button(buttons, bg="snow", text=")", width=7, height=1, command=self.bracket_two, relief=RAISED)
        Bracket_two.grid(padx=2, pady=2, column=3, row=3)
        Zero = Button(buttons, bg="snow", text="0", width=7, height=1, command=self.zero, relief=RAISED)
        Zero.grid(padx=2, pady=2, column=0, row=3)
        Decimal_point = Button(buttons, bg="snow", text=".", width=7, height=1, command=self.decimal_point, relief=RAISED)
        Decimal_point.grid(padx=2, pady=2, column=1, row=3)
        Multiplication = Button(buttons, bg="red", text="x", width=7, height=1, command=self.multiplication, relief=RAISED)
        Multiplication.grid(padx=2, pady=2, column=3, row=1)
        Division = Button(buttons, bg="powder blue", text="/", width=7, height=1, command=self.division, relief=RAISED)
        Division.grid(padx=2, pady=2, column=4, row=1)
        Addition = Button(buttons, bg="yellow", text="+", width=7, height=1, command=self.addition, relief=RAISED)
        Addition.grid(padx=2, pady=2, column=3, row=2)
        Subtraction = Button(buttons, bg="green", text="-", width=7, height=1, command=self.subtraction, relief=RAISED)
        Subtraction.grid(padx=2, pady=2, column=4, row=2)

    def key(self, event):
        if event.char.isdigit():
            self.results.insert(END, event.char)
        elif event.char in ('\x08', '\x7f'):
            self.clear()

    def show_up(self, x):
        return lambda: self.results.insert(END, x)

    def equals(self):
        try:
            result = eval(self.results.get())
        except:
            result = "Error"
        self.all_clear()
        self.results.insert(0, result)
    def zero(self):
        self.results.insert(END, "0")
    def bracket_one(self):
        self.results.insert(END, "(")
    def bracket_two(self):
        self.results.insert(END, ")")
    def all_clear(self):
        self.results.delete(0, END)
    def clear(self):
        self.results.delete(len(self.results.get()) - 1)
    def multiplication(self):
        self.results.insert(END, "*")
    def division(self):
        self.results.insert(END, "/")
    def addition(self):
        self.results.insert(END, "+")
    def subtraction(self):
        self.results.insert(END, "-")
    def decimal_point(self):
        self.results.insert(END, ".")

if __name__ == '__main__':
    Calculator(root)
    root.config(menu=menubar)
    root.mainloop()

rawDescription: Binding number and operator buttons to calculator buttons


rawDescription: python, count characters in last line string

description: Python, count characters in last line string


code:
myargs = ['-v', '-m', '-a', '-f', '"//filesrver/eggs/" "http://webserver1/python_eggs/" "http://webserver2/python_eggs/"', 'trunk-99']
setuptools.command.easy_install.main( myargs )

rawDescription: What's the correct way to add extra find-links to easy_install when called as a function?


code:
sess.query(User).\
           join(User.scores).\
           filter(Score.created_at > someday).\
           group_by(User).\
           order_by(func.sum(Score.amount))

rawDescription: SQLAlchemy filter query by related object


rawDescription: Finding the max in a complex list - Python


rawDescription: Find all text files not containing some text string


code:
from __future__ import print_function
from __future__ import division

# some imports
import numpy as np
import glob
import sys
import multiprocessing
import os
import timeit

# creating some temporary data
tmp_dir = os.path.join('tmp', 'nptest')
if not os.path.exists(tmp_dir):
    os.makedirs(tmp_dir)
    for i in range(100):
        x = np.random.rand(10000, 50)
        file_path = os.path.join(tmp_dir, '%05d.npz' % i)
        np.savez_compressed(file_path, x=x)

def read_x(path):
    data = dict(np.load(path))
    return data['x']

def serial_read(files):
    x_list = list(map(read_x, files))
    return x_list

def parallel_read(files):
    pool = multiprocessing.Pool(processes=4)
    x_list = pool.map(read_x, files)
    return x_list

files = glob.glob(os.path.join(tmp_dir, '*.npz'))
#files = files[0:5] # to test on a subset of the npz files

# Timing:
timeit_runs = 5

timer = timeit.Timer(lambda: serial_read(files))
print('serial_read: {0:.4f} seconds averaged over {1} runs'
      .format(timer.timeit(number=timeit_runs) / timeit_runs,
      timeit_runs))
# 1 loops, best of 3: 7.04 s per loop

timer = timeit.Timer(lambda: parallel_read(files))
print('parallel_read: {0:.4f} seconds averaged over {1} runs'
      .format(timer.timeit(number=timeit_runs) / timeit_runs,
      timeit_runs))
# 1 loops, best of 3: 3.56 s per loop

# Examples of use:
x = serial_read(files)
print('len(x): {0}'.format(len(x))) # len(x): 100
print('len(x[0]): {0}'.format(len(x[0]))) # len(x[0]): 10000
print('len(x[0][0]): {0}'.format(len(x[0][0]))) # len(x[0]): 10000
print('x[0][0]: {0}'.format(x[0][0])) # len(x[0]): 10000
print('x[0].nbytes: {0} MB'.format(x[0].nbytes / 1e6)) # 4.0 MB

rawDescription: Loading several npz files in a multithreadedly


rawDescription: python regex with unicode to match a city name

description: Python regex with unicode to match a city name


rawDescription: Calculate date variance based on common id


code:
for i, j in IT.product(range(nrows), range(ncols)):
    arr = cellArray[i*ncols+j].image
    x, y = i*cellHeight, j*cellWidth
    display[x:x+cellHeight, y:y+cellWidth, :] = arr

rawDescription: Faster way than concatenate of combining multiple cv2 images (numpy arrays) in python?


code:
hello

hi

rawDescription: More elegant way to produce a space python


rawDescription: Python way to convert categorical values into binary in the same column


code:
def format_elapsed_time(seconds):
    seconds = int(seconds + 0.5)  # round to nearest second
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)

format_elapsed_time(90381.33)

rawDescription: python - get time in specific format

description: Python - get time in specific format


code:
class A(object):
    def __init__(self, shared_list):
        self.shared_list = shared_list
    def add(self, num):
        self.shared_list.append(num)

rawDescription: What is the proper way to share a list between class instances?


code:
n = 3
s = "The quick brown fox jumps over the lazy dog."
zip(*(s[i:] for i in xrange(n)))

rawDescription: Find consecutive combinations

description: Find consecutive combinations


rawDescription: select a chunk with maximum score in a string python

description: Select a chunk with maximum score in a string python


code:
from inspect import iscode, ismethod, getsource
from textwrap import dedent

def nested_sources(ob):
    if ismethod(ob):
        ob = ob.__func__
    try:
        code = ob.__code__
    except AttributeError:
        raise TypeError('Can\'t inspect {!r}'.format(ob)) from None
    for c in code.co_consts:
        if not iscode(c):
            continue
        name = c.co_name
        # Skip <setcomp>, <dictcomp>, <listcomp> or <genexp>
        if not name.startswith('<') or name == '<lambda>':
            yield dedent(getsource(c))

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


code:
from rest_framework import serializers

class PersonSerializer(serializers.Serializer):
    """
    Person/Car serializer
    """
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField()
    attributes = serializers.SerializerMethodField()

    def get_attributes(self, obj):
        return {"name": obj.name}

rawDescription: Django Rest Framework approach for JSON API standards


code:
from StringIO import StringIO
import pandas as pd
import matplotlib.pyplot as plt
from mpldatacursor import datacursor

f = StringIO(
"""931,Oxfordshire,9314125,123255,Larkmead School,Abingdon,125,124,20,SUPP,8
931,Oxfordshire,9314126,123256,John Mason School,Abingdon,164,164,25,6,16
931,Oxfordshire,9314127,123257,Fitzharrys School,Abingdon,150,149,9,0,11
931,Oxfordshire,9316076,123298,Our Lady's Abingdon,Abingdon,57,57,SUPP,SUPP,16
""")
df = pd.read_csv(f, names=['A','B','C','D','E','F','G', 'H','I','J', 'K'],
                 header=None)
df.replace('SUPP', 3.0, inplace=True)
df = df.convert_objects(convert_numeric=True)
df['KG'] = df['K']*1.0/df['G']
plt.plot(df['KG'], marker='o')

l, = plt.plot(df['KG'], marker='o', linestyle='', visible=False)
datacursor(l, hover=True, point_labels=df['E'])

plt.show()

rawDescription: How to show data labels when you mouse over data

description: Show data labels when you mouse over data


rawDescription: 'CheckboxSelectMultiple' options -not aligned


code:
new_res = {}
for e in response:
    if e['country'] not in new_res:
        new_res[e['country']] = e['values']
    else:
        new_res[e['country']].extend(e['values'])

rawDescription: How to carry out this aggregation in python

description: Carry out this aggregation in python


code:
o1 = object()
o2 = object()
o1 == o2

rawDescription: Python: Fastest Way to compare arrays elementwise


code:
cats = db.GqlQuery("SELECT * FROM Cats").fetch(50)
for cat in cats:
    ...

rawDescription: Google Appengine: objects passed to a template changes their addresses in memory


code:
def getffdirs():

  dirs = {}
  path = os.curdir
  for d in os.listdir(path):

    if os.path.isdir(d):
        print("Entering " + d)
        dirs[d] = [] # add directory with empty list

        curPath = os.path.join(path, d)
        for f in os.listdir(curPath):

            if os.path.isfile(f):
                print("file " + f)
                dirs[d].append(f) # add files to appropriate directory
  return dirs

rawDescription: Python nested loop

description: Python nested loop


code:
for picture in pictures:
    picture.is_in_article = (picture in article.pictures)

rawDescription: GAE template code to check is item in the list


code:
import collections
import os

#** I'm guessing you want to put your devices into this dict, but you never put anything into it
devices = collections.defaultdict(lambda: collections.defaultdict(dict))
# bundles = collections.defaultdict(dict)

for filename in os.listdir('.'):
    if os.path.isfile(filename):
        if '.net' in filename:
            dev = open(filename)

            for line in dev:

                line = line.strip()
                values = line.split(' ')
                #** declare bundle_name out here, it is better form since we will make use of it in the immediate scopes below this
                bundle_name = ''

                if values[0] == 'interface':
                    bundle_name = values[1]
                    if '/' in bundle_name:
                        pass
                    else:
                        if len(values) == 2:
                            #** This is assuming you populated devices somewhere else??
                            devices[filename][bundle_name] = []

                if 'secondary' in values:
                    pass
                elif values[0] == 'ipv4' and values[1] == 'address' and len(values) == 4:
                    #** ur_device was not declared in this scope, it is a bad idea to use it here, instead index it out of the devices dict
                    #** it also might be worth having a check here to ensure devices[filename] actually exists first
                    devices[filename][bundle_name].append(
                        {
                            'ip_address': values[2],
                            'subnet_mask': values[3],
                        }
                    )

            dev.close()

rawDescription: Python: defaultdict(dict) how to create nested dictionary?


code:
parameters = raw_input()
sx, sy, sstartfrom, sjump, suntil = parameters.split()
x = "0123456789".index(sx)
y = "0123456789".index(sy)
startfrom = int(sstartfrom)
jump = int(sjump)
until = int(suntil)
for i in range(startfrom, until+jump, jump):
    si = str(i)
    booz = sx in si or i%x == 0
    bang = sy in si or i%y == 0
    print [[si, 'BANG'],['BOOZ','BOOZ-BANG']][booz][bang]

rawDescription: A simple prog in Python. Involves digits of numbers


code:
Output
{'America/Anguilla',
 'America/Antigua',
 'America/Argentina/Buenos_Aires',
 ...,
 'Cuba',
 'EST5EDT',
 'Jamaica',
 'US/East-Indiana',
 'US/Eastern',
 'US/Michigan'}

rawDescription: pytz: return Olson Timezone name from only a GMT Offset

description: Pytz: return Olson Timezone name from only a GMT Offset


rawDescription: Theano: Using theano.scan with theano.scan_module.until


code:
s = '''foo = 'some',"stuff?#, maybe 'nested#' " # #but now this is all a comment to capture ,'that "could be?#" nested#', ? but still capture this?! and "this?! "'''
[j for i in re.findall(r'^((?:"[^"]*"|\'[^\']*\'|[^\'"#])*)#(.*)', s) for j in i]

rawDescription: Regular Expression Split on character not in Qualified String (python)


code: numpy.array([(key,val) for (key,val) in result.iteritems()],dtype)

rawDescription: python dict to numpy structured array

description: Python dict to numpy structured array


code:
from klepto.archives import dir_archive
# does not hold entries in memory, each entry will be stored on disk
demo = dir_archive('demo', {}, serialized=True, cached=False)
demo['a'] = 10
demo['b'] = 20
demo['c'] = min
demo['d'] = [1,2,3]

rawDescription: Saving pickle object at each iteration without writing whole object each time


code: df.iloc[0:2] = df.iloc[0:2].fillna('')

rawDescription: Pandas: parse merged header columns from Excel


code:
#I assume the data is in 'text' as a string.
data = text.split()
Movie, Year, oscars, nominations = ''.join(data[:-3]), data[-3], data[-2], data[-1]

rawDescription: Separating contents of different types stored in a list using python


code:
def search_func(lst, x):
    if lst and x in lst: # test for emptiness and for membership
        return "success"
    else:
        return "failure"

rawDescription: Search function python

description: Search function python


code:
class VoiceRecognizer(object):
    def __init__(self, *args, **kwargs):
        self.last_phrase = None

    def voiceRecognition(self):
        # your code here
        self.last_phrase = whatUserSaid
        return whatUserSaid

rawDescription: Python 2.7 Get return value from function without running what is in the function again?


code:
class myResource(ModelResource):
   class Meta:
      queryset = myModel.objects().all()
      allowed_methods = ['get','post']
      authentication = ApiKeyAuthentication()
      authorization = CustomDjangoAuthorization()

rawDescription: how to limit GET access to resources using DjangoAuthorization() in tastypie

description: Limit GET access to resources using DjangoAuthorization() in tastypie


rawDescription: What is the difference between `np.histogram` and `plt.hist`? Why don't these commands plot the same graphics?


code:
def random_split(items, size):
    sample = set(random.sample(items, size))
    a = [x for x in items if x in sample]
    b = [x for x in items if x not in sample]
    return a, b

rawDescription: Random split list, keeping the original order in new lists


code:
def edu_info(user1):
    user_1_cities = []
    user_1_schools = []
    user_1_state = []
    first_one = Education.objects.filter(owner=user1)
    for i in first_one:
        user_1_cities.append(str(i.city))
        user_1_schools.append(str(i.school))
        user_1_state.append(str(i.state))
    info = {}
    info['cities'] = user_1_cities
    info['schools'] = user_1_schools
    info['states'] = user_1_state
    return info

rawDescription: Basic Match Making for Django and Python


code: mystring = re.sub(",", "", mystring)

rawDescription: How do I replace commas in a string

description: Replace commas in a string


code: somelist = [random.randint(1, 1000000) for _ in xrange(10000)]

rawDescription: Invalid syntax when creating lists

description: Invalid syntax when creating lists


code:
import sys
from PyQt5 import QtWidgets

class MyTable(QtWidgets.QTableWidget):
    def __init__(self, *args):
        QtWidgets.QTableWidget.__init__(self, *args)
        self.setheader()
        self.resizeColumnsToContents()
        self.resizeRowsToContents()

    def setheader(self):
        self.setHorizontalHeaderLabels(['Label 1', 'Label 2', 'Label 3'])
        self.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
        #self.horizontalHeader().setStretchLastSection(True) # This is another possible option

def main(args):
    app = QtWidgets.QApplication(args)
    table = MyTable(5, 3)
    table.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main(sys.argv)

rawDescription: Resize the height of the header in QTableWidget in PyQt


code:
re.search(r'.*?,', "abcd,abcde,abc, f")
re.search(r'.*,', "abcd,abcde,abc, f")

rawDescription: regex returns None on parsing address

description: Regex returns None on parsing address


code: df[["Name", "ranks"]]

rawDescription: Using Python to Combine CSV Elements From Columns to Rows


rawDescription: Python Regular Expression Escape or not

description: Python Regular Expression Escape or not


code:
import tornado.httpserver
import tornado.ioloop
import tornado.web

import xmlrpclib

server = xmlrpclib.ServerProxy('http://advogato.org/XMLRPC')

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.write(repr(server.test.sumprod(3, 5)))

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Make asynchronous xmlrpc (client call) in Tornado


code:
p_lines = []
g_lines = []
with open('D:\\mydirectory\\soggetti.txt','r') as file:
    for line in file:
        fields = line.split("|")
        if fields[3] == "P":
            p_lines.append(line)
        elif fields[3] == "G":
            g_lines.append(line)

file_pf = open("D:\\mydirectory\\file_pf.txt","w")
file_pf.writelines(p_lines)
file_pf.close()

file_pg = open("D:\\mydirectory\\file_pg.txt","w")
file_pg.writelines(g_lines)
file_pg.close()

rawDescription: Python: faster method to read and create file


code: from random import uniform

rawDescription: Create a typewriter-effect animation for strings in Python


code:
# setup
def distance(nplet):
    '''Takes a pair or triplet (an "n-plet") as a list, and returns its distance.
    A smaller return value means better agreement.'''
    # your choice of implementation here. Example:
    return variance(nplet)

# algorithm
def brute_force(*lists):
    return min(itertools.product(*lists), key = distance)

rawDescription: Finding the most similar numbers across multiple lists in Python


code:
import struct, binascii
hex_string = "DEADBEEF"
binascii.unhexlify(hex_string)  # Hexa decimal -> binary data
struct.unpack('4B', binascii.unhexlify(hex_string))  # 4 = 8 / 2
struct.unpack('4B', binascii.unhexlify(hex_string)) == (0xDE, 0xAD, 0xBE, 0xEF)
struct.unpack('{}B'.format(len(hex_string) // 2), binascii.unhexlify(hex_string))

rawDescription: Perl unpack to Python Conversion

description: Perl unpack to Python Conversion


rawDescription: Python Variables and Equations

description: Python Variables and Equations


code: base = df.index.get_indexer_for((df[df.A == 2].index))

rawDescription: pandas get position of a given index in DataFrame

description: Pandas get position of a given index in DataFrame


code:
def kill_at(max_x, max_y):
    def _kill_at(particle):
        if particle.x < -max_x or particle.x > max_x or particle.y < -max_y or particle.y > max_y:
            particle.kill()
    return _kill_at

rawDescription: How to implement a particle engine

description: Implement a particle engine


rawDescription: progress of loop indicator

description: Progress of loop indicator


rawDescription: Accessing a file relatively in Python if you do not know your starting point?


code:
def readlines(self):
    lines = []
    for line in iter(self.readline, ''):
        lines.append(line)
    return lines

# or equivalently

def readlines(self):
    lines = []
    while True:
        line = self.readline()
        if not line:
            break
        lines.append(line)
    return lines

rawDescription: Reading a file without newlines

description: Reading a file without newlines


rawDescription: Python: Make last item of array become the first


rawDescription: zipped array returns as <zip object at 0x02B6F198>

description: Zipped array returns as <zip object at 0x02B6F198>


rawDescription: Update array values for rows and columns given by a condition


rawDescription: Python: Combine several nested lists into a dictionary