code:
import numpy
data = numpy.random.random(100)
bins = numpy.linspace(0, 1, 10)
digitized = numpy.digitize(data, bins)
bin_means = [data[digitized == i].mean() for i in range(1, len(bins))]

rawDescription: binning data in python with scipy/numpy

description: Binning data in python with scipy/numpy


code:
class MyList(QListView):

    itemSelectionChanged = pyqtSignal()

    def selectionChanged(self, selected, deselected):
        super(MyList, self).selectionChanged(selected, deselected)
        self.itemSelectionChanged.emit()

rawDescription: How to updated ListView 2 based on Item clicked on ListView 1

description: Updated ListView 2 based on Item clicked on ListView 1


code:
max(collections.Counter((s for _, s in b)).values())
collections.Counter((s for _, s in b)).most_common(1)

rawDescription: Check string in list for multiple occurrence


code:
def draw (self, context):
    # (...) we're skipping some code here, obviously
    act = context.active_object
    if act.type == 'MESH':
        op_icon = 'ZOOMIN'
    else:
        op_icon = 'EMPTY_DATA'

    row = layout.column(align=True)
    row.operator('rbm.set_bullet_point', icon=op_icon)
    row.operator('rbm.set_rocket_point', icon=op_icon)
    # (...) rest of the code

rawDescription: How to change Operator's label in Blender 2.63 depending on the context?

description: Change Operator's label in Blender 2.63 depending on the context


code:
from jinja2 import Template

template = Template("""

        {% if caption %}

{{caption}}

        {% endif %}

            {% for r in head %}

                {% for c in r %}
                <{{c.type}} class="{{c.class}}">{{c.value}}
                {% endfor %}

            {% endfor %}

            {% for r in body %}

                {% for c in r %}
                <{{c.type}} id="T_{{uuid}}{{c.id}}" class="{{c.class}}">
                {% if c.value is number and c.value|int < c.value %}
                         {{c.value|round(precision)}}
                {% else %}
                         {{c.value}}
                {% endif %}
                {% endfor %}

            {% endfor %}

        """)

st = pd.core.style.Styler(v1)
st.template = template
st.render()

rawDescription: different rendering results using jinja2 between centos and windows

description: Different rendering results using jinja2 between centos and windows


code:
ip = get_ipython()
latex_formatter = ip.display_formatter.formatters['text/latex']
latex_formatter.for_type_by_name('sympy.galgebra.ga', 'MV', MVlatex)

rawDescription: Nice output for geometric algebra in ipython notebook


code:
values = [value for name, value in request.POST.iteritems()
                if name.startswith('n_')]

rawDescription: Getting all request input values

description: Getting all request input values


code:
import numpy as np
np.testing.assert_allclose([1], [[1]])

rawDescription: Test if two numpy arrays are (close to) equal, including shape


code:
obj = form.save(commit=False)
obj.sender = request.user
obj.save()

rawDescription: What's the cleanest way to add arbitrary data to ModelForm?


code:
#config.py
pass

rawDescription: Getting all hard-coded paths out of the code, how to handle the config file?


code:
import csv
from collections import defaultdict
from collections import namedtuple

Record = namedtuple('Record', ['product', 'part_number', 'category'])

mydict = defaultdict(dict)
with open('inventory.csv', 'rb') as inf:
    for rec in map(Record._make, csv.reader(inf)):
        mydict[rec.category][rec.product] = rec.part_number  # more readable

rawDescription: Creating nested dict using csv.DictReader


code:
x=np.arange(5)
np.array([my_formula(i) for i in x])

rawDescription: How to get current value of ndarray in function?

description: Get current value of ndarray in function


code:
class CronForm(forms.Form):
    days = forms.ModelChoiceField(queryset=Date.objects.all().order_by('alias'),
           widget=forms.Select(attrs={"onChange":'submit()'}))

rawDescription: Django modelchoicefield submit

description: Django modelchoicefield submit


code:
def get_values(list_o_dicts, key):
    return [a_dict[key] for a_dict in list_o_dicts]

rawDescription: generate list using a particular key from a list of objects

description: Generate list using a particular key from a list of objects


code: cm = np.corrcoef(a1.flat, a2.flat)

rawDescription: percentage difference between two images in python using correlation coefficiant

description: Percentage difference between two images in python using correlation coefficiant


rawDescription: return an unpacked list in python

description: Return an unpacked list in python


code: ['thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']

rawDescription: How to replace each letters in multiple words

description: Replace each letters in multiple words


code:
from collections import deque

def dfs(root):
    stack = deque([root])
    while stack:
        node = stack.pop()
        yield node
        if node.branches is not None:
            for child in reversed(node.branches):
                stack.append(child)

rawDescription: Mapping a list of inputs to the lowest level of nested lists


code:
{'Referral': {'referral_type': u'food', 'ok_to_mail': u'False', 'okay_to_call': u'False', 'okay_to_leave_message': u'True'},
 'data_model_name': ['NOMSEXITInterview', 'Referral'],
 'NOMSEXITInterview': {'INTTYPE_2': u'2', 'INTDUR_2': u'3', 'GENDER_2': u'3', 'EMPLOY_2': u'6'}}

rawDescription: how to handle two dimensional dict in python?

description: Handle two dimensional dict in python


rawDescription: Output file formatting and rearrangement


code: response = raw_input("What would you like to do next?")

rawDescription: Present blank screen, wait for key press -- how?


code:
re.search("window.open\('(.+?)'",
          "window.open('page.asp?ProductID=3679','productwin','width=700,height=475,scrollbars,resizable,status');"
         ).group(1)

rawDescription: How can i use scrapy to parse links in JS?

description: Use scrapy to parse links in JS


code:
parser = argparse.ArgumentParser()

subparsers = parser.add_subparsers(title = 'subcommands')

parser_create = subparsers.add_parser('create')
parser_create.add_argument('path')
parser_create.add_argument('-s', '--skeleton')
parser_create.set_defaults(target=create)

parser_build = subparsers.add_parser('build')
parser_build.set_defaults(target = build)

args = parser.parse_args()
args.target(**{k: v for k, v in vars(args).items() if k != 'target'})

rawDescription: Nested options with argparse

description: Nested options with argparse


rawDescription: Creating a Python list from a list of tuples


code:
import numpy as np
# generate some fake data
n = 300
mjd_vec = np.random.rand(n)
delta_vec = np.random.rand(n)
mjd_list = list(mjd_vec)
delta_list = list(delta_vec)
avg_time = 123

def f1():
    w_sum = j_index = 0
    n = len(delta_list)
    for j in range(0, n - 1, 1):
        for k in range(j + 1, n, 1):
            w = 1. / np.exp((mjd_list[k] - mjd_list[j]) / avg_time)
            w_sum = w_sum + w
            P = delta_vec[j] * delta_vec[k]
            j_index = j_index + w * np.sign(P) * np.sqrt(np.abs(P))
    return w_sum, j_index

def f2():
    n = len(delta_vec)
    jj, kk = np.triu_indices(n, 1)
    ww = 1. / np.exp((mjd_vec[kk] - mjd_vec[jj]) / avg_time)
    w_sum = np.sum(ww)
    PP = delta_vec[jj] * delta_vec[kk]
    j_index = np.sum(ww * np.sign(PP) * np.sqrt(np.abs(PP)))
    return w_sum, j_index

rawDescription: Nested python loop revisited

description: Nested python loop revisited


code:
timeit("x=islice(open('afile'), 4003, 4005); print next(x) + next(x)", 'from itertools import islice', number=1)
timeit("print getline('afile', 4003) + getline('afile', 4004)", 'from linecache import getline', number=1)
timeit("getline('afile', 4003) + getline('afile', 4004)", 'from linecache import getline', number=10**5)
timeit("''.join(islice(open('afile'), 4003, 4005))", 'from itertools import islice', number=10**5)

rawDescription: Python fastest access to line in file

description: Python fastest access to line in file


code:
import pickle

class ABC(object):
    pass
d = {'keyname1': ABC()}

# Dump!
pickle.dump(d, open('filename.pkl', 'wb'))

rawDescription: unpickling python 2.6 object in python 3.1.1

description: Unpickling python 2.6 object in python 3.1.1


rawDescription: Fill in Email When Authenticating Via LDAP in Django


code: df = df.interpolate('time')

rawDescription: Resampling and merging data frame with python


code:
def expectation(self):
    responsibilities = (self.mixing_coefficients[:, None, None] *
                        gaussian_probability(self.image_matrix,
                                             self.means[:, None, None],
                                             self.variances[:, None, None] ** 0.5))
    return responsibilities / responsibilities.sum(0)

rawDescription: Speeding up guassian EM algorithm

description: Speeding up guassian EM algorithm


code:
#ifndef PYTHONPATH
#   define PYTHONPATH L".\\DLLs;.\\lib;.\\lib\\plat-win"

rawDescription: How to create a completely autonomous Python environment?

description: Create a completely autonomous Python environment


rawDescription: pandas - how to combine selected rows in a DataFrame

description: Pandas - how to combine selected rows in a DataFrame


rawDescription: Some nudges for a first-time scraper

description: Some nudges for a first-time scraper


rawDescription: Spark computation for suggesting new friendships


code: for s in Section.objects.all():exec("for j in s.children():print j")

rawDescription: How to create a single-line script with two for loops, in the debugger, in python 2.7

description: Create a single-line script with two for loops, in the debugger, in python 2.7


code:
forced_rentals = []
for force_row in range(4,forced_sheet.nrows):
        Fnum = forced_sheet.cell_value(force_row, 0)
        Fnum_type = type(Fnum)
        if type(Fnum) is float:
                Fnum = str(Fnum)
                Fnum = Fnum.replace('.0','')
        if Fnum[-2:] == '/1':
                Fnum = Fnum.replace('/1','')
        for book_row in range(1,bookings_sheet.nrows):
                Bnum = bookings_sheet.cell_value(book_row,0)
                Bnum_type = type(Bnum)
                if type(Bnum) is float:
                        Bnum = str(Bnum)
                        Bnum = Bnum.replace('.0','')
                if Bnum[-2:] == '/1':
                        Bnum = Bnum.replace('/1','')
                if Fnum == Bnum:
                        booNum = str(bookings_sheet.cell_value(book_row,0))
                        renCODate = bookings_sheet.cell_value(book_row,2)
                        renCOLoc = str(bookings_sheet.cell_value(book_row,4))
                        renUnit = str(bookings_sheet.cell_value(book_row,13))
                        renAgent = str(bookings_sheet.cell_value(book_row,12))
                        forced_rentals += [[booNum,renCODate,renCOLoc,renUnit,renAgent]]
                        break

rawDescription: Trouble comparing 2 excel sheets in Python using nested for loop


code:
admin: {passwd: 123, user: admin@admin.com}
basicUser: {passwd: pass45, user: basic@basic.com}

rawDescription: Variables from txt file

description: Variables from txt file


code:
result.index = result.index.droplevel(0)
print(result)

rawDescription: Fancy indexing in pandas

description: Fancy indexing in pandas


code:
import scipy as sp
import scipy.optimize

def f(x):
    b1, b2, c3 = x
    e1 = sp.cos(b1) + sp.cos(b2) - 0.0166
    e2 = sp.sin(b1) + sp.sin(b2) + 0.3077*c3 - 0.6278
    e3 = sp.cos(b1) - sp.cos(b2) + 5.4155*c3 - 4.3547
    return e1, e2, e3

res = sp.optimize.root(f, [0.5, 1.0, 1.0])
print('b1 = {}, b2 = {}, c3 = {}'.format(*res.x))

rawDescription: Which variable is minimized by scipy.optimize.minimize/How does it work?


code: df3.columns =  df3.columns[:-1].tolist() + ['population_movav']

rawDescription: Concatenating/Merging Data Frames and Editing column names - Python/Pandas


rawDescription: Create a dictionary for the token, tags of a text


code:
import scrapy
from scrapy.loader import ItemLoader
from scrapy.loader.processors import MapCompose, Join

class DmozItem(scrapy.Item):
    title = scrapy.Field()
    link = scrapy.Field()
    desc = scrapy.Field()

class DmozItemLoader(ItemLoader):
    default_input_processor = MapCompose(unicode.strip)
    default_output_processor = Join()

    default_item_class = DmozItem

class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allowed_domains = ["dmoz.org"]
    start_urls = [
        "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
        "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
    ]

    def parse(self, response):
        for sel in response.xpath('//ul[@class="directory-url"]/li'):
            loader = DmozItemLoader(selector=sel)

            loader.add_xpath('title', 'a/text()')
            loader.add_xpath('link', 'a/@href')
            loader.add_xpath('desc', 'text()')

            yield loader.load_item()

rawDescription: Scrapy dmoz tutorial, no data for desc in csv file


code:
from numbers import Number
def key(x):
    val = my_dictionary[x]['c']
    return  val if isinstance(val, Number) else float("-inf")
print(max(my_dictionary, key=key))

rawDescription: key in nested dictionary if it contains NaN value?

description: Key in nested dictionary if it contains NaN value


code:
seats = [[True, True, True, False, True, True, True, False, False, True],
         [True, True, True, True, True, True, True, False, False, True],
         [True, True, True, False, True, True, True, False, False, True],
         [True, True, True, False, True, True, True, False, False, True],
         [True, True, True, True, True, True, True, False, False, True]]

for index, row in enumerate(seats):
    consecutive_seats = 0
    for seat in row:
        if seat:
            consecutive_seats += 1
            if consecutive_seats >= 6:
                print('There are at least six seats available on row', index)
                break
        else:
            consecutive_seats = 0

rawDescription: Finding consecutive values in a multidimensional array - python


code:
dynamic_assertion(response, ("address", "city"), "New York")
dynamic_assertion(response, ("address", "city"), "Boston")
response["items"][2]["address"]["city"] = "Boston" # make response invalid
dynamic_assertion(response, ("address", "city"), "New York")
dynamic_assertion(response, ("address", "city"), "Boston")

rawDescription: Create Dynamic Python Dictionary Reference Path


code: p = pointer(f)

rawDescription: Python: ctypes and Pointer to Structure

description: Python: ctypes and Pointer to Structure


code:
from dateutil.parser import parse
dt = parse(xsdDateTime)

rawDescription: Parse xsd:dateTime formatted string to python datetime


code: r'\1 xby '

rawDescription: How to replace all occurrences of regex as if applying replace repeatedly

description: Replace all occurrences of regex as if applying replace repeatedly


code: df.lookup(df.index, w)

rawDescription: Pandas: optimizing some python code by getting rid of DataFrame.apply()


code:
def expand_x_1(p):
    ex = [1]
    for i in range(p):
        ex.append(ex[-1] * -(p-i) / (i+1))
    return ex[::-1]

def aks_test(p):
    if p < 2: return False
    ex = expand_x_1(p)
    ex[0] += 1
    return not any(mult % p for mult in ex[0:-1])
    print('# p: (x-1)^p for small p')
    for p in range(12):
        print('%3i: %s' % (p, ' '.join('%+i%s' % (e, ('x^%i' % n) if n else '')
                                   for n,e in enumerate(expand_x_1(p)))))

print('\n# small primes using the aks test')
print([p for p in range(101) if aks_test(p)])

rawDescription: AKS Primes algorithm in Python

description: AKS Primes algorithm in Python


code:
import os

result = []
for parent, ds, fs in os.walk(dirname):
    if 'foo.txt' in fs:
        result.append(parent)

rawDescription: collect all directories matching criteria from directory tree in python

description: Collect all directories matching criteria from directory tree in python


rawDescription: Initialize/Create/Populate a Dict of a Dict of a Dict in Python


code:
import pandas as pd
df = pd.read_csv("data.csv", index_col="Date")
df.index = pd.DatetimeIndex(df.index)
df = df.reindex(pd.date_range("2011-01-01", "2011-10-31"), fill_value="NaN")
df.to_csv('test.csv')

rawDescription: Add missing date index in dataframe

description: Add missing date index in dataframe


code:
for a in soup.select('.listing li a'):
    print(a['href'], a.get_text(strip=True))

rawDescription: python BeautifulSoup get all href in Children of div

description: Python BeautifulSoup get all href in Children of div


code:
ii = np.arange(cols)
ixy = np.array([dX*ii, dY*(ii%2)])
arr1 = sub[None,:,:] + ixy.T[:,None,:]

rawDescription: Method for generating row-column arrays with other arrays


code:
d = {('Foo', 0): 0, ('Bar', 0): 0}
for (k, j), v in list(d.items()): # list key-value pairs for safe iteration
    del d[k,j] # remove the old key (and value)
    d[(k.lower(), j)] = v # set the new key-value pair

d

rawDescription: When the key is a tuple in dictionary in Python


rawDescription: Why does my negative slicing in Python not work?


code: [func_list[i](i) for i in range(4)]

rawDescription: Python: pass a function call's list index as its own argument


code:
def namtupiter(c):
    from collections import namedtuple
    fields = tuple(i[0] for i in c.description)
    Row = namedtuple('Row', fields)
    # make Row a tuple and a "dict" (well, kind of...) at the same time.
    # Don't lose tuple property, so only process strings and pass everything
    # other to super().
    Row.__getitem__ = lambda self, item: getattr(self, item) if isinstance(item, basestring) else super(Row, self).__getitem__(item)
    for i in c:
        try:
            # try to access i as a dict
            yield Row(*(i[f] for f in fields))
        except TypeError:
            # it is no dict -> try tuple
            yield Row(*i)

class CursorNTRowsMixIn(object):
    _fetch_type = 0 # tuples
    def _do_get_result(self):
        super(CursorNTRowsMixIn, self)._do_get_result()
        # create a named tuple class
        from collections import namedtuple
        if self.description:
            self.RowClass = namedtuple('Row', tuple(i[0] for i in self.description))
    def _fetch_row(self, size=1):
        rows = super(CursorNTRowsMixIn, self)._fetch_row(size)
        # turn every row into a Row().
        return tuple(self.RowClass(*i) for i in rows)

class NTCursor(CursorStoreResultMixIn, CursorNTRowsMixIn,
               BaseCursor):
    pass

class SSNTCursor(CursorUseResultMixIn, CursorNTRowsMixIn,
               BaseCursor):
    pass

rawDescription: Can I combine python's `for` statement with SQL like this: `for id, name, ctime in db.select('table_name', where='...')`

description: Combine python's `for` statement with SQL like this: `for id, name, ctime in db.select('table_name', where='...')`


code: pd.ewma(df["avg"], span=60, freq="D")

rawDescription: computing an EWMA of a DataFrame by time

description: Computing an EWMA of a DataFrame by time


code:
@mod.route('/save_transaction', methods=['GET', 'POST'])
def save_transaction():
    follow_num = request.args.get('PAYMENT_ID')
    amount = request.args.get('PAYMENT_AMOUNT')
    memo = request.args.get('SUGGESTED_MEMO')

    #Save Data

    return jsonify(result='ok')

rawDescription: How to redirect to an external url with parameters and POST method?

description: Redirect to an external url with parameters and POST method


code:
print(r.status_code)
print(r.text)

rawDescription: Creating a new Jenkins job with python Requests


font_face: Source Code Pro

rawDescription: Specific font_face based on syntax in Sublime Text 2


code:
def Authorize(action):
    def request_checked(func):
        def _f(self, req, resp, *args, **kw):
            u = getUserInfoFromSession(req)
            if isAuthorizedTo(u.get('id'), action):
                return func(self, req, resp, *args, **kw)
            else:
                raise falcon.HTTPUnauthorized('Not Authorized', 'Permission Denied')
        return _f
    return request_checked

rawDescription: how to pass arguments to falcon.before hook?

description: Pass arguments to falcon.before hook


code:
from file2 import *

file.hello()

rawDescription: How to import all imports of another .py file

description: Import all imports of another .py file


rawDescription: List on numbers into list of dates

description: List on numbers into list of dates


rawDescription: Pandas calcuating percentage in data summary


code:
from pylab import imshow, show, get_cmap
from numpy import random

Z = random.random((50,50))   # Test data

imshow(Z, cmap=get_cmap("Spectral"), interpolation='nearest')
show()

rawDescription: 100x100 image with random pixel colour

description: 100x100 image with random pixel colour


code:
import hashlib
publicKeyHash = hashlib.sha256.digest(publicKey)
bigInt = 0
for byte in publicKeyHash[:7]:
  bigInt <<= 8
  bigInt |= byte

rawDescription: Rewriting Java BigInteger function in python


code: b[:,None] == a

rawDescription: How to generate a bool 2D arrays from two 1D arrays using numpy

description: Generate a bool 2D arrays from two 1D arrays using numpy


rawDescription: Python decimal rounding

description: Python decimal rounding


code:
import json
from urllib import urlopen

url = urlopen('http://api.openweathermap.org/data/2.5/forecast/daily?q={}&mode=json&units={}'.format(getname,temp_type)).read()
#where getname is the name of city.
#and temp_type is either C(Celsius) or F(Fahrenheit)
result = json.loads(url)
out_file = open("weather.json","w")
json.dump(result,self.out_file, indent=4)
#indent = 4, just to make it easy to read.
out_file.close()

rawDescription: Save app data in Weather App

description: Save app data in Weather App


code:
besedilo = "Dober dan Slovenija"
[i for i, c in enumerate(besedilo) if c == 'o']

rawDescription: Find indexes for a certain character in string


code: a[:, None].shape

rawDescription: Numpy array slicing using commas

description: Numpy array slicing using commas


code: return {'timestamps': list_of_timestamps, 'values': list_of_values, 'avg_coffee_consumption': 12e9}

rawDescription: Best approach for extensible return object in python


code:
import codecs

for fd in source_fds_list:
   with open(destination_url, 'ab') as destn_fd:
       with fd:
           start = fd.read(2)
           if start != codecs.BOM_UTF16_LE:
               destn_fd.write(start)
           shutil.copyfileobj(fd, destn_fd)

rawDescription: shutil.copyfileobj method in python copies BOM character also while merging files

description: Shutil.copyfileobj method in python copies BOM character also while merging files


code:
import supervisor.xmlrpc
import xmlrpclib

proxy = xmlrpclib.ServerProxy('http://127.0.0.1',
                               transport=supervisor.xmlrpc.SupervisorTransport(
                                    None, None, serverurl='unix://'+socketpath))

proxy.supervisor.getState()

rawDescription: Use Python xmlrpclib with unix domain sockets?


code:
dict_number = {}  # an empty dictionary

for term,score in list_number:
    dict_number[term] = int(score)

rawDescription: trying to make sense of a Python code

description: Trying to make sense of a Python code


code:
def histogram(d):
    #for k in d: #use this one if you don't want to display empty values
    for k in range(min(d), max(d)+1):  #use that one to start at the minium number thrown and display zeros for empty values
        print("%3i : %3i : %s" % (k,d[k],d[k]*"*"))

rawDescription: Performing sum of dice and generating the percentage with histogram


code:
for i in xrange(10):
    pass

rawDescription: Why are there no control structures for python FOR loop?


code:
import numpy as np
...
myarr = np.array(mylist)
val = myarr[tuple(index)]
print(val)

rawDescription: Using a list as "list of indexes" to address elements of another list


code:
d = {}
for x in data:
    d.setdefault(x['author'], []).append(x)

rawDescription: How to initialize an a priori unknown number of list

description: Initialize an a priori unknown number of list


rawDescription: Iterate over jinja array

description: Iterate over jinja array


code:
erik_tweets = [x for x in tweets
               if x['user']['name'] == 'Erik Allik']

rawDescription: How to save and handle tweets saved as JSON in Python

description: Save and handle tweets saved as JSON in Python


code: abc

rawDescription: Convert Numpy array of ASCII codes to string


code:
def knightofni(obj):
    obj.number = 1
    obj.who = "We've encountered Knight of Ni."

def frenchman(obj):
    obj.number = 4
    obj.who = "We've encountered French."

rawDescription: Change object's variable from different file


code:
d = {}
with open("data", 'rb') as data:
  for line in data:
    key, val = line.split(' ')
    d[key] = float(val)

ids = [max(sublist, key=lambda k: d[k]) for sublist in li]

rawDescription: Python - a clean approach to this problem?


rawDescription: Benefits of panda's multiindex?

description: Benefits of panda's multiindex


code:
df1.join(df2)
sqlContext.sql('SELECT * FROM df1 JOIN df2')

rawDescription: How do you perform basic joins of two RDD tables in Spark using Python?

description: Perform basic joins of two RDD tables in Spark using Python


rawDescription: Indexing a pandas dataframe by integer

description: Indexing a pandas dataframe by integer


rawDescription: printing list of categories as a column

description: Printing list of categories as a column


code: F = treecomp(T, L)

rawDescription: Composition of a hierarchy of functions

description: Composition of a hierarchy of functions


rawDescription: Comparing data flow graphs quickly in Python


code:
GOOGLE_PLUS_SCOPE = "https://www.googleapis.com/auth/plus.me"
GOOGLE_PLUS_SERVICE_NAME = "plus"
GOOGLE_PLUS_VERSION = "v1"

rawDescription: Get user info from YouTube Google API in Python (API v3)


rawDescription: Find numbers in string, modify and re-join


code:
dct = {'name1':[3],'name2':[1],'name3':[2]}
lst = sorted([[k, v] for k, v in dct.items()], key=lambda ls : ls[1][0], reverse = True)
print(lst)

rawDescription: How to sort a dictionary by descending order numerically

description: Sort a dictionary by descending order numerically


rawDescription: Runtime Optimization of sympy code using numpy or scipy


code:
#!/usr/bin/env python

import os

homedir = os.path.expanduser('~')
bash_history = open(homedir+"/.bash_history", 'r')

rawDescription: reading .bash_history file through python script

description: Reading .bash_history file through python script


code:
with concurrent.futures.ProcessPoolExecutor(max_workers=N) as executor:
    ans = executor.map(your_func, (your_arguments for _ in range(n_trials)))

rawDescription: Multiprocessing Python Sampling Distribution Simulation (no interdependence between function calls)


code:
def split_tasks(lst, n):
    # sorts the list from largest to smallest
    sortedlst = sorted(lst, key=lambda x: x[1], reverse=True)
    # dict storing the total time for each set of tasks
    totals = dict((x, 0) for x in range(n))
    outlst = [[] for x in range(n)]
    for v in sortedlst:
        # since each v[1] is getting smaller, the place it belongs should
        # be the outlst with the minimum total time
        m = min(totals, key=totals.get)
        totals[m] += v[1]
        outlst[m].append(v)
    return outlst

rawDescription: Split tests into even time slaves

description: Split tests into even time slaves


code:
for i,board in enumerate([board1, board2, board3, board4]):
    print("Checking board %d:" % (i+1))
    res = check(board)
    print(res)
    print('---')

rawDescription: Determine if all the elements of a matrix are connected in Python


rawDescription: How to declare an array in python

description: Declare an array in python


code: {{ counter.increment }}

rawDescription: 2D forloop counter django template

description: 2D forloop counter django template


code:
def f(obj_name, given_dct):
    """
    Converts given dct (body) to a pretty formatted string.
    Resulting string used for file writing.

    Args:
        obj_name: (str) name of the dict
    Returns:
        (str)
    """

    string = pp.pformat(given_dct, width=1)[1:]

    new_str = ''
    for num, line in enumerate(string.split('\n')):
        if num == 0:
            # (pprint module always inserts one less whitespace for first line)
            # (indent=1 is default, giving everything one extra whitespace)
            new_str += ' '*4 + line + '\n'
        else:
            new_str += ' '*3 + line + '\n'

    return obj_name + ' = {\n' + new_str

s = f(obj_name='MY_DCT', given_dct=d)

rawDescription: Indentation of pformat() output

description: Indentation of pformat() output


rawDescription: Python - for with counter

description: Python - for with counter


code:
access = wrap_prop(z(), "bar")
access.val = 20
access.val # yahoo \o/

rawDescription: Create a reference to a variable (similar to PHP's "=&")?


rawDescription: How do I create multiple dictionaries based on nested for loops?

description: Create multiple dictionaries based on nested for loops


code: return 1 + self._foo

rawDescription: How to call a data member of the base class if it is being overwritten as a property in the derived class?

description: Call a data member of the base class if it is being overwritten as a property in the derived class


rawDescription: pythonic format for indices

description: Pythonic format for indices


code:
def dec(f):
    def wrap():
        """wrap"""
        return f()
    return wrap

@dec
def test():
    """test"""
    return test.__name__, test.__doc__

test()

rawDescription: Python introspection: access function name and docstring inside function definition


code:
a = [ ['x1_{}'.format(x), 'x1_{}'.format(x)] for x in range(1,101)]
b = []
for i in a:
  b.extend(i)

rawDescription: Python: creating string array with integers


code:
import pandas as pd
pd.DataFrame(dat, columns=['user', 'gender', 'some number'])

rawDescription: Make single column of numpy array another datatype


code:
p = r-1
a = 1
while p > 0 and combination[p] + a > n:
  p -= 1
  a += 2

rawDescription: Generating non-consecutive combinations

description: Generating non-consecutive combinations


code:
with os.fdopen(wout, "w", bufsize=bufsize) as f:
    subprocess.check_call(cmd, stdout=f)

rawDescription: Flushing a pipe (os.pipe) before closing


code:
import pprint
lst = c.search_tweets(author='Nancy')
pprint.pprint(lst)
lst = c.search_tweets(author='Mike', string="gladly")
pprint.pprint(lst)
lst = c.search_tweets(string="Hi")
pprint.pprint(lst)
# All tweets
lst = c.search_tweets()
pprint.pprint(lst)

rawDescription: How do I search a list that is located in a class?

description: Search a list that is located in a class


code:
def writeText(x):
    for row in x.iteritems():
        with open(str(row[0])+'.txt', 'w+') as f:
            f.write(str(row[1]))

df.apply(writeText)

rawDescription: How to call the index value of the data frame as an arg in apply function with python-pandas?

description: Call the index value of the data frame as an arg in apply function with python-pandas


code:
def options_text(self):
    options = []
    for field in self.option_fields():
        if getattr(self, field.name) is not None:
            options.append("%s: %s" % (unicode(field.verbose_name),
                                       getattr(self, field.name)))
    return ", ".join(options).strip()

def __unicode__(self):
    """
    Display the option names and values for the variation.
    """
    return ("%s %s" % (unicode(self.product), self.options_text())).strip()

rawDescription: How to break the item name and size in Django Cartridge cart page?

description: Break the item name and size in Django Cartridge cart page


rawDescription: Using encode method in Python. Any workaround similar to map()?


code:
from matplotlib import pylab
pylab.plot(range(10), range(10))
pylab.show()

rawDescription: Keep a figure "on hold" after running a script


code:
json_obj = {"numFound" : 1,
             "start" : 0,
             "rows" : 3,
             "briefRecords" : [
                {"progressivoId" : 0,
                 "codiceIdentificativo" : "IT\\ICCU\\LO1\\0120590",
                 "autorePrincipale" : "Savoia, Carlo",
                 "titolo" : "Per la inaugurazione dell'Asilo infantile Strozzi nei locali della caserma Filippini già convento della Vittoria / parole di mons. Carlo Savoia",
                 "pubblicazione" : "Mantova : Tip. Eredi Segna, 1870",
                 "livello" : "Monografia",
                 "tipo" : "Testo a stampa",
                 "numeri" : [],
                 "note" : [],
                 "nomi" : [],
                 "luogoNormalizzato" : [],
                 "localizzazioni" : [],
                 "citazioni" : []
                }
             ],
             "facetRecords" : [
                {"facetName" : "level" ,
                 "facetLabel" : "Livello bibliografico" ,
                 "facetValues" : [["Monografia" , "m" , "1"]]},
                {"facetName" : "tiporec" ,
                 "facetLabel" : "Tipo di documento" ,
                 "facetValues" : [["Testo a stampa" , "a" , "1"]]},
                {"facetName" : "nomef" ,
                 "facetLabel" : "Autore" ,
                 "facetValues" : [["savoia, carlo" , "savoia, carlo" , "1"]]},
                {"facetName" : "soggettof" ,
                 "facetLabel" : "Soggetto" ,
                 "facetValues" : [["mantova - asili infantili" , "mantova - asili infantili" , "1"]]},
                {"facetName" : "luogof" ,
                 "facetLabel" : "Luogo di pubblicazione" ,
                 "facetValues" : [["mantova" , "mantova" , "1"]]},
                {"facetName" : "lingua" ,
                 "facetLabel" : "Lingua" ,
                 "facetValues" : [["italiano" , "ita" , "1"]]},
                {"facetName" : "paese" ,
                 "facetLabel" : "Paese" ,
                 "facetValues" : [["italia" , "it" , "1"]]}
             ]
            }

rawDescription: Parsing a complex JSON object with Python: search a specific key/value pair


code: pyserv = 1

rawDescription: how can you Import an os variable into PYTHON and have it update?


code:
with open('yourfile') as fh:
    for line in fh:
        result += line
        if line.find('>>>FOOBAR<<<') > -1:
            break

rawDescription: Regular Expression String Mangling Efficiency in Python - Explanation for Slowness?


rawDescription: how can I create a python array with a specific len each element all initialize to 0

description: Create a python array with a specific len each element all initialize to 0


code:
A = matrix([[1,2,3]])
B = A.tolist()
B
B = A.tolist()[0]
B

rawDescription: Convert a matrix to a list

description: Convert a matrix to a list


code:
while True:
    raw = raw_input("Enter values: ")
    if not raw:  # user input was empty
        break
    ...  # rest of the code

rawDescription: Process multiple input values in Python

description: Process multiple input values in Python


code:
for row in X:
    fh.write(asbytes(format % tuple(row) + newline))

rawDescription: What are the possible numpy value format strings?


code:
import urllib.parse

method = "POST"
url = "https://secure.trademe.co.nz/Oauth/RequestToken"

params = [('oauth_callback', 'http://www.website-tm-access.co.nz/trademe-callback'),
            ('oauth_consumer_key', 'C74CD73FDBE37D29BDD21BAB54BC70E422'),
            ('oauth_nonce', '7O3kEe'),
            ('oauth_signature_method', 'HMAC-SHA1'),
            ('oauth_timestamp', 1285532322),
            ('oauth_version', 1.0),
            ('scope', "MyTradeMeRead,MyTradeMeWrite")]

print('POST&%(url)s&%(params)s' %  { 'url' : urllib.parse.quote_plus(url), 'params' : urllib.parse.quote_plus(urllib.parse.urlencode(params)) })

rawDescription: How do I URL encode this

description: URL encode this


code:
from operator import methodcaller

sorted(list_of_objects, key=methodcaller('method_name'))

rawDescription: sort list of objects by return of object method

description: Sort list of objects by return of object method


code: d[key] = value

rawDescription: Python: Dictionary within dictionary?

description: Python: Dictionary within dictionary


code: ["|".join(values) for values in zipped]

rawDescription: Zip string-subset from tuples in a list

description: Zip string-subset from tuples in a list


rawDescription: Using Python rdflib: how to include literals in sparql queries?


code:
import operator
import itertools

def pairwise(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    return a, b

def sum_products(l):
    return sum(itertools.imap(operator.mul, *pairwise(l)))

rawDescription: Can this be written as a python reduce function?


code: resultList = list(TableClass.select(IN(TableClass.q.id, [1, 2, 4])))

rawDescription: how to do 'select in' operation in sqlobject

description: Do 'select in' operation in sqlobject


code: data['hello'] = ['hello' in item for item in data['state']]

rawDescription: Binomial classification using a list comprehension python


code: {'PathB': '/Change/this/path', 'PathA': '/Some/path/to/directory'}

rawDescription: Combine XML files similar to ConfigParser's multiple file support


code:
subparsers = parser.add_subparsers(dest='action', help='do this')
parser_act_one = subparsers.add_parser('actone')
parser_act_one.add_argument('function', type=str)
parser_act_two = subparsers.add_parser('acttwo')
parser_act_two.add_argument('function', type=str)

rawDescription: Python Argsparser add a single argument to subparser without a name


code:
def func():
    return 'hi'
func  # Below is a string representation of the function object itself
func()  # The () calls func.  Below is the return value of the function

rawDescription: Why is StringVar().set(LocalScript) receiving a function id instead of a return value


code:
s1 = u'서용교'
type(s1)
s1
print(s1)

s2 = u'\\uc9c0\\ubc29\\uc790\\uce58\\ub2e8\\uccb4'
type(s2)
# put that unicode string between double-quotes
# so that json module can interpret it
ts2 = u'"%s"' % s2
ts2
import json
json.loads(ts2)
print(json.loads(ts2))

rawDescription: how to convert unicode string on unicode format with python?

description: Convert unicode string on unicode format with python


code:
import sys
from time import sleep

for c in "Hello":
    sys.stdout.write(c)
    sleep(0.1)
sys.stdout.write('\n')

rawDescription: Python code, Time delay on console text

description: Python code, Time delay on console text


code: src_match('this is <img src="my example" />','my example')

rawDescription: how to match an image tag's link with regex

description: Match an image tag's link with regex


code:
import time
import sys

for x in range(10):
    time.sleep(1)
    print("a", end="")
    sys.stdout.flush()

rawDescription: Sleeping and printing without newline?

description: Sleeping and printing without newline


code:
a_array+1
a+1

rawDescription: Automatically truncate numpy arrays

description: Automatically truncate numpy arrays


code: x

rawDescription: Pandas groupby two columns then get dict for values


rawDescription: Scrapy : How to pass list of arguments through command prompt to spider?


code:
from selenium import webdriver

dr = webdriver.PhantomJS()

dr.get('http://www.jeevansathi.com/search/quick/169903999/1')
ul = dr.find_element_by_id("profileInfo2")
print()

rawDescription: Getting empty list while parsing

description: Getting empty list while parsing


rawDescription: Returning specific content

description: Returning specific content


code:
threading.current_thread().name = 'MyName'
assert threading.current_thread().name == 'MainThread' # will fail

rawDescription: Check if current thread is main thread, in Python


code:
g = Graph.Full(3)
vs = VertexSeq(g)

rawDescription: Getting vertex list from python-igraph

description: Getting vertex list from python-igraph


code: results = [t[1] for t in mylist if t[0] == 10]

rawDescription: Select value from list of tuples where condition


rawDescription: How to calculate p-value for two lists of floats?

description: Calculate p-value for two lists of floats


code:
import traceback

def f():
    g()

def g():
    for line in traceback.format_stack():
        print(line.strip())

f()

# Prints:
# File "so-stack.py", line 10, in <module>
#     f()
# File "so-stack.py", line 4, in f
#     g()
# File "so-stack.py", line 7, in g
#     for line in traceback.format_stack():

rawDescription: Print current call stack from a method in Python code


code:
from subprocess import check_output

res = check_output(["nodejs","path_to/test.js"])

rawDescription: Save Javascript variable value and read it in python


code:
import operator
import functools
xs = ["hello", "world"]
functools.filter(functools.partial(operator.eq, "hello"), xs)

rawDescription: Python partially apply a string equality function


code:
class GroupMembers(models.Model):
    group = models.ForeignKey(Group)
    person = models.ForeignKey(Person)
    is_main_user = models.BooleanField(default=False)

rawDescription: Getting the first item item in a many-to-many relation in Django


code: [['login1', 'fname1', 'lname1', 'mail1'], ['login2', 'fname2', 'lname2', 'mail2'], ['login3', 'fname3', 'lname3', 'mail3'], ['login4', 'fname4', 'lname4', 'mail4']]

rawDescription: Make a list of list with string in a text file in Python 3


rawDescription: Python: print unicode string stored as a variable


code:
import ruamel.yaml as yaml

yaml_str = """\
--- !MyData
name: theName
param: parameter
data_file: file.csv
"""

class Parent:
    def __init__(self, name, data_file, path=None):
        self._name = name
        self._data_file = (path + data_file) if path is not None else data_file

class Load(Parent):
    def __init__(self, name="",
             param = "param",
             useDataFile=False,
             data_file = "none",
             path=None,
             **kwargs):

        super().__init__(name=name,
                         data_file = data_file, path=path)

class LoadConstructor:
    def __init__(self, path=None):
        self._path = None

    def set_path(self, path):
        self._path = path

    def __call__(self, loader, node):
        values = loader.construct_mapping(node, deep=True)
        values['path'] = self._path
        return Load(**values)

load_constructor = LoadConstructor()
yaml.add_constructor(u'!MyData', load_constructor)

# using the above:
# set the default path
load_constructor.set_path('/my/path/to/csv/')
# parse YAML documents
for item in yaml.load_all(yaml_str):
    if type(item) is Load:
        print('data file:', item._data_file)

rawDescription: How to pass a parameter to a class constructor called by yaml.load_all

description: Pass a parameter to a class constructor called by yaml.load_all


rawDescription: Grabbing all results for a certain query Yelp API using Python


code:
@decorator
def foo():
    ...

rawDescription: Understanding the difference between these two decorators


code:
class Test(object):

    VALIDATED = {'a', 'b'}

    def __init__(self):
        self.a = None
        self.b = None

    def __setattr__(self, attr, val):
        if attr in self.VALIDATED:
            pass  # add your checking
        super(Test, self).__setattr__(attr, val)

rawDescription: Use a function to write different class attributes


code:
rows = root.clipboard_get().split('\n')
rows = [row.strip() for row in rows]

for row in rows:
    browser.get('https://wwww.corp/soft.html')
    time.sleep(2)
    browser.find_element_by_xpath("//*[@id='agent_list_filter_id_2']").clear()

    browser.find_element_by_xpath("//*[@id='agent_list_filter_id_2']").send_keys(row)
    browser.find_element_by_xpath("//*[@id='content-column']/div[4]/form/div[1]/span/span[1]").click()
    browser.find_element_by_xpath("//*[@id='action-select-all']/span/span").click()
    browser.find_element_by_xpath("//*[@id='action-delete']/span/span").click()
    browser.find_element_by_xpath("//*[@id='btn_save']").click()

rawDescription: Create variables no matter the nr of rows of the data in clipboard


rawDescription: What Regex to use in this example

description: What Regex to use in this example


code:
try:
    client.info('/tmp')
except pysvn.ClientError:
    print('not working copy')
else:
    print('working copy')

rawDescription: pysvn: How to find out if local dir is under version control?

description: Pysvn: How to find out if local dir is under version control


code:
def reverse_id(id):
    parts = id.split('-')
    return '-'.join((parts[1], parts[0], parts[2]))
order_dict = dict((x, i) for i, x in enumerate(ordered_branches))
order_dict.update((reverse_id(x), i) for x, i in order_dict.items())

rawDescription: Sorting the contents of one list via the contents of another (Python)


code:
import numpy as np
indicators = []
state_names = []
for column_name in df.columns:
    column = df[column_name].values
    one_hot = (column[:, np.newaxis] == np.unique(column)).astype(float)
    indicators.append(one_hot)
    state_names = state_names + ["%s__%s" % (column_name, state) for state in np.unique(column)]

X_1hot = np.hstack(indicators)

rawDescription: How can an interaction design matrix be created from categorical variables?


code:
from django.db import models

class_map = {}

def depends_field_pre_save(self, model_instance, add):
    """
    if default is not callable or it is not a model add, lets skip our hook
    """
    if not add or not callable(self.default):
        super(self.__class__, self).__init__(self,*args, **kwargs)
    value = self.default(model_instance)
    setattr(model_instance, self.attname, value)
    return value

def FieldDepends(field_class):
    """
    return a dervied class from field_class which supports dependent default
    """
    if field_class in class_map:
        # we already created this class so return that
        return class_map[field_class]

    new_class = type('Depends'+field_class.__name__, (field_class,), {'pre_save':depends_field_pre_save })

    class_map[field_class] = new_class

    return new_class

rawDescription: Simple multiplication in model's attribute django?


code:
class MetaA(type):
    """ like ___metaclass__ above """

class A(metaclass=MetaA):

    _x = None

...

rawDescription: class property that can be accessed and set by all instances (also of subclasses)

description: Class property that can be accessed and set by all instances (also of subclasses)


code:
from itertools import permutations

data = {'letters': ['a','b','c'],
        'numbers': ['one','two'],
        'others': ['here','there']}

poss = [(v,k) for k, vv in data.items() for v in vv]
results = (list(zip(*p)) for p in permutations(poss, 2))
results = [p[0] + ('-'.join(p[1]),) for p in results]

rawDescription: Combinations between values of lists

description: Combinations between values of lists


code:
import time
# at the beginning of the script
startTime = time.time()
# ...
def getUptime():
    """
    Returns the number of seconds since the program started.
    """
    # do return startTime if you just want the process start time
    return time.time() - startTime

rawDescription: How to retrieve the process start time (or uptime) in python

description: Retrieve the process start time (or uptime) in python


code:
# make test.py the testing script instead of depending on
# debug_alpha to handle hardcoded namespaces
import debug_alpha
from alpha import *

# wrap the function in its original module
# and override the wrapped function in this namespace
foo = debug_alpha._wrapFunc(foo)

print(foo())
print(bar())

rawDescription: Wrapping a function imported with import *?


rawDescription: Sort in Python changing column order

description: Sort in Python changing column order


code:
import pygame

# Constants
WIDTH = 700
HEIGHT = 500
SCREEN_AREA = pygame.Rect(0, 0, WIDTH, HEIGHT)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# Initialization
pygame.init()
screen = pygame.display.set_mode([WIDTH, HEIGHT])
pygame.mouse.set_visible(0)
pygame.display.set_caption("Breakout Recreation WIP")
clock = pygame.time.Clock()

# Variables
paddle = pygame.Rect(350, 480, 50, 10)
ball = pygame.Rect(10, 250, 15, 15)
paddle_movement_x = 0
ball_direction = (1, 1)
balls = 3
done = False

while not done and balls > 0:

    # Process events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            paddle_movement_x = -2
        elif keys[pygame.K_RIGHT]:
            paddle_movement_x = 2
        else:
            paddle_movement_x = 0

    # Move paddle
    paddle.move_ip(paddle_movement_x, 0)
    paddle.clamp_ip(SCREEN_AREA)

    # Move ball
    ball.move_ip(*ball_direction)
    if ball.right > WIDTH or ball.left < 0:
        ball_direction = -ball_direction[0], ball_direction[1]
    elif ball.top < 0 or paddle.colliderect(ball):
        ball_direction = ball_direction[0], -ball_direction[1]
    elif ball.bottom > HEIGHT:
        balls = balls - 1
        ball_direction = (1, 1)
        ball = pygame.Rect(10, 250, 15, 15)

    ball.clamp_ip(SCREEN_AREA)

    # Redraw screen
    screen.fill(BLACK)
    pygame.draw.rect(screen, WHITE, paddle)
    pygame.draw.rect(screen, WHITE, ball)
    pygame.display.flip()
    clock.tick(100)

pygame.quit()

rawDescription: Sprite Health in Pygame

description: Sprite Health in Pygame


code:
from itertools import product

def print_good_points(p, dimensions=7):
    for coords in product(range(p), repeat=dimensions):
        args = coords + (p,)
        if isagoodpoint(*args):
            print(*coords)

rawDescription: How can I get rid of multiple nested for loops?

description: Get rid of multiple nested for loops


rawDescription: New pandas dataframe from meta information of existing DF


code:
with open(full_path, 'a+') as csvfile:
    linewriter = csv.DictWriter(csvfile, fieldorder, delimiter='|',
                            quotechar='"', quoting=csv.QUOTE_MINIMAL)
    linewriter.writerow(data)

rawDescription: Scraping tables and writing rows to CSV

description: Scraping tables and writing rows to CSV


code:
from django.conf import settings

def some_context_processor(request):
    my_dict = {
        'site_url': settings.SITE_URL,
        'site_name': settings.SITE_NAME,
    }

    return my_dict

rawDescription: Using Django settings in templates

description: Using Django settings in templates


code:
import redis
from rq.queue import Queue, get_failed_queue
from rq.job import Job
redis = Redis()
for i, key in enumerate(self.redis.keys('rq:job:*')):
    job_number = key.split("rq:job:")[1]
    job = Job.fetch(job_number, connection=self.redis)
    job.delete()

rawDescription: Redis still fills up when results_ttl=0, Why?


code: import dis

rawDescription: Longest increasing subsequence in Python (For vs While loop)


code:
self.entries = {}
for i in range(72):
    self.entries[i] = None

rawDescription: Python attributes from variables?

description: Python attributes from variables


rawDescription: Manipulate a new column after 'df.size()' function?


code: iframe_content = iframe.text

rawDescription: Best way to locate this element in selenium?

description: Locate this element in selenium


rawDescription: Reading a large amount of numbers in python


code:
words = word_tokenize(raw)
ents = [ [ e for e in word_tokenize(entity[0]) ] for entity in entity_results ]

for word_idx in range(len(words)):
    for ent in ents:
        # Check the word against the first word in the entity
        if words[word_idx].upper() in ( e[0].upper() for e in ents ):
            match = True
            # Check all words in entity
            for ent_idx in range(len(ent)):
                if ent[ent_idx] != words[word_idx + ent_idx]:
                    match = false
                    break
            if match:
                print(" ".join([words[word_idx]] + ent))
            else:
                print(words[word_idx])
        else:
            print(words[word_idx])

rawDescription: Match items in list to string: How to evaluate the F1 ratio of Alchemy API NER result? Python


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

a = np.random.randn(500)*5
plt.plot(a, mlab.normpdf(a, np.mean(a), np.std(a)))
plt.show()

rawDescription: Smoothening a normal/gaussian plot in matplotlib


code: [t[-1] for t in inputlist]

rawDescription: Python values out of list

description: Python values out of list


code:
...

if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
    player = pygame.image.load(images[counter])
    counter = (counter + 1) % len(images)
    playerY = playerY + 5
...

rawDescription: Pygame How to use walking animations

description: Pygame How to use walking animations


code:
data_dict = {"DNS": {u'link': u'dns-prefetch'}, "Page": {u'link': u'prefetch'}}
return render_to_response("ABC.html", data_dict)

rawDescription: How to write django templates for this

description: Write django templates for this


rawDescription: How to stream twitter mentions with tweepy?

description: Stream twitter mentions with tweepy


code: pd.concat([pd.DataFrame(d) for d in data])

rawDescription: JSON to Stacked DataFrame

description: JSON to Stacked DataFrame


code:
class MyWidget(QtGui.QWidget):
    _sizehint = None

    def setSizeHint(self, width, height):
        self._sizehint = QtCore.QSize(width, height)

    def sizeHint(self):
        if self._sizehint is not None:
            return self._sizehint
        return super(MyWidget, self).sizeHint()

rawDescription: pyqt : resize qdockwidget in maya

description: Pyqt : resize qdockwidget in maya


code:
Ethernet(src='\x00\x03G\xb2M\xe4', dst='\x00\x03G\x06h\x18', data=IP(src='\n\x00\x01\x1c',
dst='\n\x00\x01\x10', sum=39799, len=60, p=1, ttl=128, id=35102, data=ICMP(sum=24667,
type=8, data=Echo(id=512, seq=60160, data='abcdefghijklmnopqrstuvwabcdefghi'))))

Ethernet(src='\x00\x03G\x06h\x18', dst='\x00\x03G\xb2M\xe4', data=IP(src='\n\x00\x01\x10',
dst='\n\x00\x01\x1c', sum=43697, len=60, p=1, ttl=255, id=64227, data=ICMP(sum=26715,
data=Echo(id=512, seq=60160, data='abcdefghijklmnopqrstuvwabcdefghi'))))

rawDescription: Packet sniffing in Python (Windows)

description: Packet sniffing in Python (Windows)


code:
for pair in zip(input[::2], input[1::2]):
    number = "".join(pair)

rawDescription: convert string of numbers to letters python

description: Convert string of numbers to letters python


rawDescription: Summing over lists in python - is there a better way?


code:
import numpy as np
import pandas as pd

df = pd.DataFrame(
    {'A' : ['foo', 'foo', 'foo', 'foo',
            'bar', 'bar', 'bar', 'bar'],
     'B' : ['one', 'one', 'two', 'three',
            'two', 'two', 'one', 'three'],
     'C' : [1, np.NaN, 1, 2, np.NaN, 1, 1, 2],
     'D' : [2, '', 1, 1, '', 2, 2, 1]})
df['D'].replace('', np.NaN, inplace=True)

result = df.groupby(['A']).agg({'C': lambda x: x.sum()/x.count(), 'D':'sum'})
print(result)

rawDescription: Aggregate groups in Python Pandas and spit out percentage from a certain count


rawDescription: Converting String Date to Timestamp and back python


rawDescription: Merge values of same key, in list of dicts


code:
class UserProfile(models.Model):
    # This line is required.Links Userprofile to a User model instance.
    user = models.OneToOneField(User)

    # The additional attributes we wish to include.
    website = models.URLField(blank=True)
    picture = models.ImageField(upload_to='profile_images', blank=True)

    # Override th __unicode__() method to return out something meaningful!
    def __unicode__(self):
        return self.user.username

rawDescription: Modify default registration form in Django-registration-redux


rawDescription: Building a numpy array (matrix) from several dataframes


rawDescription: Why won't my for loop work? (Python)

description: Why won't my for loop work? (Python)


code: (x, y), (MA, ma), angle = cv2.fitEllipse(cnt)

rawDescription: How to find the area of an ellipse obtained using cv.fitEllipse(contour)?

description: Find the area of an ellipse obtained using cv.fitEllipse(contour)


code:
mylist = []
mylist.append( (id1, name1) )
mylist.append( (id2, name2) )
# ..

rawDescription: How to store two different values returned from query into list data types to be used later(plpy python)

description: Store two different values returned from query into list data types to be used later(plpy python)


rawDescription: python pyfits, reading header information and using in caculation

description: Python pyfits, reading header information and using in caculation


code: sorted(yourlist, key=lambda x: (not x.startswith('pt='), x))

rawDescription: Sort lists in python based on a rule

description: Sort lists in python based on a rule


code:
x0, y0 = x.mean(), y.mean()
angle = np.arctan2(y - y0, x - x0)

idx = angle.argsort()
x, y = x[idx], y[idx]

fig, ax = plt.subplots()
ax.plot(x, y, color='lightblue')
ax.margins(0.05)
plt.show()

rawDescription: Numpy way to sort out a messy array for plotting


code:
d = {'a': 1, 'b': 2}
s = frozenset(d.items())
hash(s)
dict(s) == d

rawDescription: How to remove duplicate dictionaries from a list in Python?

description: Remove duplicate dictionaries from a list in Python


code:
class Simul(object):

    def __init__(self, width, height):
        board_1 = [[None for _ in range(width)] for _ in range(height)]
        board_2 = [[None for _ in range(width)] for _ in range(height)]
        self.boards = [board_1, board_2]
        self.current = 0
        self.pretty = {None: ' ', 0: '-', 1: 't', 2: 'H'}
        self.w = width
        self.h = height

    def print_board(self):
        for row in self.boards[self.current]:
            for cell in row:
                print(self.pretty[cell], end='')
            print()

    def run(self):
        BOARD = self.boards[self.current]
        other_board = self.boards[- self.current + 1]
        for row in range(self.h):
            for col in range(self.w):
                cur_cell = BOARD[row][col]
                set_h = False
                for DX, DY in ((-1,-1), (-1,+0), (-1,+1), (+0,-1), (+0,+1),  (+1,-1), (+1,+0), (+1,+1)):
                    try:
                        if BOARD[row+DY][col+DX] == 2 and cur_cell == 0:
                            other_board[row][col] = 2
                            set_h = True
                            break
                    except IndexError:
                        pass

                if set_h:
                    continue

                if cur_cell == 2:
                    other_board[row][col] = 1
                elif cur_cell == 1:
                    other_board[row][col] = 0
                elif cur_cell == 0:
                    other_board[row][col] = 0
        self.current = - self.current + 1

if __name__ == '__main__':
    simul = Simul(10, 5)
    for col in range(10):
        simul.boards[0][3][col] = 0
    for row in range(3):
        simul.boards[0][row][4] = 0
    simul.boards[0][3][4] = 2
    simul.print_board()
    simul.run()
    simul.print_board()

rawDescription: Cellular Automata algorithm doesn't seem to work


code: crdscl=thescale

rawDescription: list[i] in "for" statement does not return the right values

description: List[i] in "for" statement does not return the right values


code:
def add_position_to_content(lint):
    for i in range (len(lint)):
        lint[i] += i
    return lint

rawDescription: add the position of the element to the element in the list

description: Add the position of the element to the element in the list


code:
s = '''<Model version = "1" importVersion = "12.2">
        <Create>
            <SubNetwork networkType = "WRAN" userLabel="AHPTUR14">
                <ManagedElement sourceType = "CELLO">
                    <ManagedElementId string = "rbs064841"/>
                    <primaryType type = "RBS"/>
                    <managedElementType types = ""/>
                    <associatedSite string = "Site=site06484"/>
                    <nodeVersion string = "W12B"/>
                    <platformVersion string = "Cello 12.2"/>
                    <swVersion string = ""/>
                    <vendorName string = "ERICSSON"/>
                    <userDefinedState string = ""/>
                    <managedServiceAvailability int = "1"/>
                    <isManaged boolean = "true"/>
                    <neMIMVersion string = "vS.1.150"/>
                    <connectionStatus string = "ON"/>
                </ManagedElement>
            </SubNetwork>
             <SubNetwork networkType = "WRAN" userLabel = "AHPT78">
                <ManagedElement sourceType = "CELLO">
                    <ManagedElementId string = "rbs04798"/>
                    <primaryType type = "RBS"/>
                    <managedElementType types = ""/>
                    <associatedSite string = "Site=site06484"/>
                    <nodeVersion string = "W12B"/>
                    <platformVersion string = "Cello 12.2"/>
                    <swVersion string = ""/>
                    <vendorName string = "ERICSSON"/>
                    <userDefinedState string = ""/>
                    <managedServiceAvailability int = "1"/>
                    <isManaged boolean = "true"/>
                    <neMIMVersion string = "vS.1.150"/>
                    <connectionStatus string = "ON"/>
                </ManagedElement>
            </SubNetwork>
            <SubNetwork networkType = "WRAN" userLabel = "AHPT4">
                <ManagedElement sourceType = "CELLO">
                    <ManagedElementId string = "rbs04456"/>
                    <primaryType type = "RBS"/>
                    <managedElementType types = ""/>
                    <associatedSite string = "Site=site06484"/>
                    <nodeVersion string = "W12B"/>
                    <platformVersion string = "Cello 12.2"/>
                    <swVersion string = ""/>
                    <vendorName string = "ERICSSON"/>
                    <userDefinedState string = ""/>
                    <managedServiceAvailability int = "1"/>
                    <isManaged boolean = "true"/>
                    <neMIMVersion string = "vS.1.150"/>
                    <connectionStatus string = "ON"/>
                </ManagedElement>
            </SubNetwork>
        </Create>
    </Model>'''

rawDescription: How to extract part of xml file

description: Extract part of xml file


code:
# You can use comments
[mysection]
myvar = special_value

rawDescription: python: simple way to input python data from file

description: Python: simple way to input python data from file


rawDescription: Replace space between a letter and a number with a comma?


rawDescription: Is there a way to suppress ssh `user logged in` text, through fabric?


code:
# Done once
int_to_four_bytes = struct.Struct('<I').pack

# Done many times (you need to mask here, because your number is >32 bits)
y1, y2, y3, y4 = int_to_four_bytes(x & 0xFFFFFFFF)

rawDescription: Fast way to split an int into bytes

description: Fast way to split an int into bytes


code:
def fun(s):
    substitute = lambda i: s[:i]+'cd'+s[i+2:]
    match = lambda i: s[i:i+2]=='ab'
    return map(substitute, filter(match, range(len(s)-1)))

rawDescription: map string sequence with a condition

description: Map string sequence with a condition


rawDescription: Comparing a numpy array object to multiple conditions


rawDescription: how to combine 3 complex data frames in pandas

description: Combine 3 complex data frames in pandas


code:
def addRow(self, shapeCSVObj):
   override = shapeCSVObj.rowOverride
   if override:
      for feature in selectedFeatures:
          self.rows.pop(0)
          feat_Attributes = []
          feat_Attributes.extend([self.iface.activeLayer().name()+'_'+str(feature.id())])
          feat_Attributes.extend(['',]*(len(self.header)-1))
          self.beginResetModel()
          self.rows.insert(0,feat_Attributes)
          shapeCSVObj.rowOverride = False
          self.endResetModel()

          shapeCSVObj.on_BaseRow_Changed()

          break

rawDescription: (PyQt) Uncheck pushbutton from outside button's class?


code:
data.Price.plot(marker='*')
annotate_plot(data, 'Price', 'Volume')
plt.show()

rawDescription: Include labels for each data point in pandas plotting


code: [part0, None, part1, None, part2, ..., partN, '--', '']

rawDescription: How to extract line 1 to line 3 which are in the middle of the document?

description: Extract line 1 to line 3 which are in the middle of the document


rawDescription: Python merge two dictionnaries

description: Python merge two dictionnaries


code:
KWARGS_TO_FUNCTIONS = {
    'bar':fn_bar,
    'baz':fn_baz,
    'qux':fn_qux,
    'haz':fn_haz,
}

def foo(**kwargs):
    for k, v in kwargs.items():
        if v:
            try:
                KWARGS_TO_FUNCTIONS[k](v)
            except KeyError:
                pass # We didn't want that kwarg.

rawDescription: Basic Python metaprogramming: populating dictionaries?


rawDescription: Find the number of ways a sequence can be rearranged


code:
from bs4 import BeautifulSoup
import urllib2

teams = ("http://baseball.fantasysports.yahoo.com/b1/2282/players?status=A&pos=B&cut_type=33&stat1=S_S_2015&myteam=0&sort=AR&sdir=1")
page = urllib2.urlopen(teams)
soup = BeautifulSoup(page, "html.parser")

players = soup.findAll('div', {'class':'ysf-player-name Nowrap Grid-u Relative Lh-xs Ta-start'})

playersLines = [span.get_text('\t',strip=True) for span in players]

with open('output.txt', 'w') as f:
    for line in playersLines:
        output = line.encode('utf-8')
        f.write(output+'\n')

rawDescription: BeautifulSoup - how to arrange data and write to txt?


code:
import re
subject = """These concepts are represented by simple Python classes.
Edit the polls/models.py file so it looks like this:

[code]
from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
[/code]"""

regex = re.compile(r'(?s)\[code\].*?\[/code\]|(\n)')
def myreplacement(m):
    if m.group(1):
        return "<br />"
    else:
        return m.group(0)
replaced = regex.sub(myreplacement, subject)
print(replaced)

rawDescription: Regex to match all new line characters outside of some tag


code:
import numpy as np
def findCells(points, bounds):
    # make sure points is n by 2 (pool.map might send us 1D arrays)
    points = points.reshape((-1,2))

    # check for each point if all coordinates are in bounds
    # dimension 0 is bound
    # dimension 1 is is point
    allInBounds = (points[:,0] > bounds[:,None,0])
    allInBounds &= (points[:,1] > bounds[:,None,1])
    allInBounds &= (points[:,0] < bounds[:,None,2])
    allInBounds &= (points[:,1] < bounds[:,None,3])

    # now find out the positions of all nonzero (i.e. true) values
    # nz[0] contains the indices along dim 0 (bound)
    # nz[1] contains the indices along dim 1 (point)
    nz = np.nonzero(allInBounds)

    # initialize the result with all nan
    r = np.full(points.shape[0], np.nan)
    # now use nz[1] to index point position and nz[0] to tell which cell the
    # point belongs to
    r[nz[1]] = nz[0]
    return r

def findCellsParallel(points, bounds, chunksize=100):
    import multiprocessing as mp
    from functools import partial

    func = partial(findCells, bounds=bounds)

    # using python3 you could also do 'with mp.Pool() as p:'
    p = mp.Pool()
    try:
        return np.hstack(p.map(func, points, chunksize))
    finally:
        p.close()

def main():
    nPoints = 1e6
    nBounds = 1e4

    # points = np.array([[ 1.5, 1.5],
    #                    [ 1.1, 1.1],
    #                    [ 2.2, 2.2],
    #                    [ 1.3, 1.3],
    #                    [ 3.4, 1.4],
    #                    [ 2. , 1.5]])

    points = np.random.random([nPoints, 2])

    # bounds = np.array([[0,0,2,2],
    #                    [2,2,3,3]])

    # bounds = np.array([[0,0,1.4,1.4],
    #                    [1.4,1.4,2,2],
    #                    [2,2,3,3]])

    bounds = np.sort(np.random.random([nBounds, 2, 2]), 1).reshape(nBounds, 4)

    r = findCellsParallel(points, bounds)
    print(points[:10])
    for bIdx in np.unique(r[:10]):
        if np.isnan(bIdx):
            continue
        print("{}: {}".format(bIdx, bounds[bIdx]))
    print(r[:10])

if __name__ == "__main__":
    main()

rawDescription: Assign numpy array of points to a 2D square grid


code:
def integral(integrand,initial_value,dt):
    placeholder = Stream(initial_value,lambda : None)
    int_rec = cons_stream(initial_value,
                          add_streams(scale_stream(integrand,dt),
                                      placeholder))
    placeholder._compute_rest = lambda:int_rec
    return int_rec

rawDescription: SICP "streams as signals" in Python

description: SICP "streams as signals" in Python


code:
import Tkinter as tk

def populateListbox(lstt):
    listbox.insert("end", *lstt)

root = tk.Tk()
listbox = tk.Listbox(root)
listbox.pack()
lst = ["one", "two", "three", "four"]
btn = tk.Button(root, text="Populate listbox", command = lambda: populateListbox(lst))
btn.pack()

root.mainloop()

rawDescription: how to allow Tkinter to generate a listbox from list input

description: Allow Tkinter to generate a listbox from list input


code:
import json

with open('myfile.json', 'r') as f:
  j = json.load(f)

rawDescription: How do I dump text file contents into dictionary

description: Dump text file contents into dictionary


code:
@receiver (pre_social_login, sender=SocialLogin)
def check_pre_social_login(sender, **kwargs):
    social_login = kwargs['sociallogin']
    request = kwargs['request']
    session = request.session
    invite_key = social_login.state.get('invite_key')
    if invite_key:
        session['invite_key'] = invite_key

@receiver ([user_signed_up, user_logged_in], sender=User)
def check_for_invite(sender, **kwargs):
    request = kwargs['request']
    session = request.session
    invite_key = session.get('invite_key')
    if invite_key:
        invite = get_object_or_404(ResourceInvite, key=invite_key)
        process_invite(kwargs['user'], invite, True)
        del session['invite_key']

def process_invite(user, invite, accept):
    ...
    # process invite here

rawDescription: How to implement an invite flow using django allauth for signup/signin?

description: Implement an invite flow using django allauth for signup/signin


code:
class Organism(object):
    @classmethod
    def reproduce(cls):
        return cls()

rawDescription: Create new class instance from class method


code:
# app/templatetags/shuffle.py
import random
from django import template
register = template.Library()

@register.filter
def shuffle(arg):
    aux = list(arg)[:]
    random.shuffle(aux)
    return aux

rawDescription: Django template: how to randomize order when populating page with objects?


code:
import wx

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.panel = wx.Panel(self)

        self.label1 = wx.StaticText(self.panel)
        self.fileCtrl = wx.FilePickerCtrl(self.panel)
        self.mailRadio = wx.RadioButton(self.panel)
        self.uploadRadio = wx.RadioButton(self.panel)

        row1 = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, 'this is row one'), orient=wx.HORIZONTAL)
        row1.Add(self.label1,0,wx.TOP | wx.RIGHT,7)
        row1.Add(self.fileCtrl)

        row2 = wx.BoxSizer(wx.HORIZONTAL)
        actionBox = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, 'asdfasdf'), orient=wx.VERTICAL)
        actionRow1 = wx.BoxSizer(wx.HORIZONTAL)
        actionRow1.Add(wx.StaticText(self.panel, -1, 'blah blah ', (5, 5)))
        actionRow1.Add(self.mailRadio)
        actionRow2 = wx.BoxSizer(wx.HORIZONTAL)
        actionRow2.Add(wx.StaticText(self.panel, -1, 'lah dee dah', (5, 5)))
        actionRow2.Add(self.uploadRadio,5)
        actionBox.Add(actionRow1,0,wx.EXPAND)
        actionBox.Add(actionRow2)
        row2.Add(actionBox)

        wrapper = wx.FlexGridSizer(2,1,5,5)
        wrapper.AddGrowableCol(0)
        wrapper.Add(row1,0,wx.TOP | wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,15)
        wrapper.Add(row2,0,wx.ALL | wx.ALIGN_CENTER,15)
        self.panel.SetSizerAndFit(wrapper)
        self.Centre()
        self.Fit()

        self.Show()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: wxPython controls not clickable

description: WxPython controls not clickable


code: MYNAME

rawDescription: Extract words from text files with python


code:
cond = ("col0 == 'blue' | col1 == 'blue' | col2 == 'blue' | col3 == 'blue' | "
        "col4 == 'blue' | col5 == 'blue' | col6 == 'blue' | col7 == 'blue' | "
        "col8 == 'blue' | col9 == 'blue'")
rows = [row[:] for row in table.where(cond)]

rawDescription: Set type in pytables

description: Set type in pytables


code:
a = np.array([0, 0])  # or a = np.zeros([2]), but that's not important here
a = np.hstack(([2, 3], a[1:]))
a

rawDescription: Why are slices in Python 3 still copies and not views?


code: col_to_add = ['two', 'three']

rawDescription: Concatenate a list of series into a uid

description: Concatenate a list of series into a uid


rawDescription: pandas row specific apply

description: Pandas row specific apply


code:
class MyClass(object):

    myclassattr = 0 # class attribute

    def __init__(self, attr):
        self.myinstattr = attr # instance attribute
        if MyClass.myclassattr == 0:
            print("First!")
        MyClass.myclassattr += 1

rawDescription: Methods to link common class attributes between objects? (not inheritance)


rawDescription: NaN value when using Lambert Function in Python - in Enthought Canopy


code:
sum(1 for candidate in list_of_all
    if candidate.property1 and candidate.property2 == property2)

rawDescription: python table lookups: list of tuples vs. database

description: Python table lookups: list of tuples vs. database


code:
np.tensordot(image, W, ([2], [1])).shape
np.einsum('ijk,lk->ijl', image, W).shape
x = np.rollaxis(image,2,1)
Wx = np.dot(W,x)
y = np.rollaxis(Wx,0,3)
np.allclose(np.tensordot(image, W, ([2], [1])), y)
np.allclose(np.tensordot(image, W, ([2], [1])), np.einsum('ijk,lk->ijl', image, W))

rawDescription: Python vectorization of image processing task


code:
def pytest_generate_tests(metafunc):
    for arg in metafunc.funcargnames:
         if arg == "conf":
            if metafunc.config.option.keyword != 'smoke':
                confs = pytest.skip("Smoke tests must....")
            else:
                with open('tests/test_smoke.json', 'r') as fp:
                    confs = loads(fp.read().decode("utf-8-sig"))

            metafunc.parametrize("conf", confs)

rawDescription: Skip parametrized tests generated by pytest_generate_tests at module level


code: index = np.array((temp['X'], temp['Y'], temp['Z']))

rawDescription: create np array index from 3 seperate columns of a pd dataframe

description: Create np array index from 3 seperate columns of a pd dataframe


rawDescription: Calculating EuropeanOptionImpliedVolatility in quantlib-python


code:
d = datetime.datetime.now()
d
d.weekday()  # Monday
(d.weekday() + 1) % 7

rawDescription: Python retreive DayOfWeek as integer

description: Python retreive DayOfWeek as integer


code:
a = cplxarr.copy()
a.real *= factarr
a

rawDescription: Scale the real part of complex numpy array


code:
c.pyx
import types
NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)

def mk_value(s, currency_sign='', thousand_sep='', decimal_sep='.'):
    if isinstance(s, bool): # make boolean into a 0/1 value
        if s:
            result = 1
        else:
            result = 0

    elif isinstance(s, NumberTypes): # keep numbers as/is
        result = s

    else: # convert a string
        # prepare the string for conversion
        if currency_sign:
            s = s.replace(currency_sign, '')
        if thousand_sep:
            s = s.replace(thousand_sep, '')
        if decimal_sep != '.':
            s = s.replace(decimal_sep, '.')
        s = s.strip()
        # convert the string
        if not s: # if the string is empty, it's not a number
            result = None
        else:
            try: # try int
                result = int(s)
            except ValueError:
                try: # if there's an error, try float
                    result = float(s)
                except ValueError:
                    # if the conversion gave an error, the string is not a number
                    result = None
    return result

rawDescription: Fastest and/or most pythonic way to convert string into a number


rawDescription: How to count elements in a list of lists of strings

description: Count elements in a list of lists of strings


code:
cursor.executemany("INSERT INTO place_id "
                   "(company, google_name, place_id, formatted_address) "
                   "VALUES (%(company)s, %(google_name)s, %(place_id)s, %(formatted_address)s",
                   (i._asdict() for i in items))

rawDescription: Python: adding named tuples to MySQL in a for loop


code:
import os
os.system("run-client.bat param1 param2")

rawDescription: Running a batch file with parameters in python OR F#


rawDescription: Groupby or pivot in pandas?

description: Groupby or pivot in pandas


code: format(10, 'b') # show 10 as a binary number

rawDescription: Algebra in Python (something better than a switch?)


code: return Button(on_press=partial(self.popup_display, "multiline\ntitle", "bar "*80))

rawDescription: Kivy : Relative size of text displaying in a popup


code:
def do_something(lines):
    print("I've got:")
    print(''.join(lines))

lines = []

with open("file.txt") as f:
    for i, line in enumerate(f):
        if line.startswith('@'):
            lines = []

        lines.append(line)
        if 'development' in line:
            do_something(lines)

rawDescription: How to search backward several lines in Python 3?

description: Search backward several lines in Python 3


code: self.bind(wx.EVT_MENU, subPanel(None, -1, 'TEST'),id=1)

rawDescription: How do I Create an instance of a class in another class in Python


code:
def fast_geometric_matrix_multiplication(matrix1, matrix2):
    return np.prod(matrix1, axis=1)[:, None] * np.prod(matrix2, axis=0)

rawDescription: Geometric Matrix Multiplication

description: Geometric Matrix Multiplication


code:
order = [1,0,3,2]
names = MyArray2.dtype.names
MyArray3 = MyArray2[[names[i] for i in order]]

rawDescription: Numpy recarray sort of columns and stack


code:
from django.conf.urls import url
from django.contrib.flatpages import views
urlpatterns = [
    url(r'^(?i)(?P<url>.*)$', views.flatpage, name='django.contrib.flatpages.views.flatpage'),
]

rawDescription: django flatpages and redirects app - case-sensitivity

description: Django flatpages and redirects app - case-sensitivity


code:
url_template = 'http://somewhere.com/relatedqueries?limit=%(limit)d&query=%(seedterm)s'
url = url_template % dict(limit=2, seedterm='seedterm')

rawDescription: Extracting data from a URL result with special formating


code: pd.read_csv(io.BytesIO(text), ...)

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


code: help(nt.Point)  # which outputs...

rawDescription: Adding docstrings to namedtuples?

description: Adding docstrings to namedtuples


code:
merged = df.merge(df1, on=['id','year','CalendarWeek','DayName','interval'])
merged = merged.reset_index()

rawDescription: How to select rows in a DataFrame based on rows in another DataFrame using Python

description: Select rows in a DataFrame based on rows in another DataFrame using Python


code:
import inspect #from standard library

import plugin

mapping = {}

for v in plugin.__dict__.itervalues():
    if inspect.isfunction(v) and v.hasattr('command_name'):
        mapping[v.command_name] = v

rawDescription: Most Pythonic way to provide function metadata at compile time?


code:
#!/usr/bin/env python
import numpy as np
import os

def memory_usage():
    pid=os.getpid()
    return next(line for line in open('/proc/%s/status'%pid).read().splitlines()
            if line.startswith('VmSize')).split()[-2]

N,M=5000,10

def python_lists_to_array(k):
    list_of_arrays = map(lambda x: x*np.ones(M), range(k))
    arr = np.array(list_of_arrays)
    return arr

def numpy_all_the_way(k):
    arr=np.empty((N,M))
    for x in range(k):
        arr[x]=x*np.ones(M)
    arr.resize((k,M))
    return arr

if __name__=='__main__':
    print('Initial memory usage: %s'%memory_usage())
    arr=python_lists_to_array(5000)
    print('After python_lists_to_array: %s'%memory_usage())
    arr=numpy_all_the_way(5000)
    print('After numpy_all_the_way: %s'%memory_usage())

rawDescription: Pythonic way to create a numpy array from a list of numpy arrays


code:
with open(json_file_path, "w") as json_file:
    for data in data_iterable:
        json_file.write("{}\n".format(json.dumps(data)))

rawDescription: Update json file

description: Update json file


code:
nc_files = ['20080305.faieb3p4e.nc', '20080306.faieb3p4e.nc']
for fname in nc_files:
    fd = nc.Dataset(fname, 'r')
    ... # do stuff

rawDescription: make loop of many file with python

description: Make loop of many file with python


code: OPTIONS, TRACE, GET, HEAD, POST

rawDescription: Showing allowed HTTP methods

description: Showing allowed HTTP methods


code: x = "There are {} on the table".format(objects)

rawDescription: Building up a string using a list of values


code:
import pyb
usb_vcp = pyb.USB_VCP()

rawDescription: Micropython updating board V 1.0

description: Micropython updating board V 1.0


code: [dict(zip(keys, l)) for l in t ]

rawDescription: Convert list of lists to list of dictionaries


code:
0 is None
0 is False
0 in [None,False]
0 in [False]
0 == None
0 == False

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


code:
def foo():
    print("foo called")

rawDescription: AutoKey Python - How do I create a global function library


code: df1 == df2

rawDescription: Compare columns of 2 different Data frames


code:
from types import MethodType

class MyClass(object):
    def __init__(self, defaultmembers, members):
        # defaultmembers is a list
        # members is a dict
        for func in defaultmembers:
            name =  func.__name__
            setattr(self, name , func)
            setattr(self, name , MethodType(getattr(self, name), self))
        for name, func in members.items():
            setattr(self, name, func)
            setattr(self, name , MethodType(getattr(self, name), self))

rawDescription: On-demand creation of member methods using __getattr__()


rawDescription: accessing columns within an array within a for loop

description: Accessing columns within an array within a for loop


code:
import struct, socket

# x.x.x.x string -> integer
ip2int = lambda ipstr: struct.unpack('!I', socket.inet_aton(ipstr))[0]
print(ip2int("192.168.0.4"))
# -> 3232235524

rawDescription: python increment ipaddress

description: Python increment ipaddress


code:
class MyModelAdmin(admin.ModelAdmin):
    def get_list_display(self, request):

        def display_confirm_button(obj):
            out = logic_that_requires_user(request.user)
            return out

        return ['field1', 'field2', get_list_display, ...]

rawDescription: How to get current user in custom methods in Django Admin?

description: Get current user in custom methods in Django Admin


code:
def reverse_sentence(fn): # a decorator accepts a function as its argument
    def __inner(s,*args,**kwargs): #it will return this modified function
       string_reverse = []
       for i in s.split():
           string_reverse.append("".join(list((reversed(i)))))
       return fn(" ".join(string_reverse),*args,**kwargs)
    return __inner # return the modified function which does your string reverse on its first argument

rawDescription: Can we design any function using a decorator?


code:
lines = open(file_in).readlines()

out_list = "['" + "','".join(lines) + "']"

rawDescription: Basic Python loop question - problem reading a list from a text file


code:
total = float(raw_input('enter a number: '))
while True:
    number = raw_input('enter a number: ')
    if number == '':
        break
    total+=float(number)

rawDescription: Python-Multiple user inputs

description: Python-Multiple user inputs


code: VCS_OpenDevice.__doc__ = 'My docstring'

rawDescription: Adding docstrings to python functions pulled from dll using ctypes


code:
import ctypes
i = ctypes.c_int(4)
hex(id(i))
hex(ctypes.addressof(i))

rawDescription: What is the difference between id(obj) and ctypes.addressof(obj) in CPython


code:
class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ('bio', 'gender', 'city', 'country')

class UserSerializer(serializers.ModelSerializer):

    profile = ProfileSerializer()

    class Meta:
        model = User
        fields = ('url', 'username', 'password', 'email', 'groups', 'profile')

rawDescription: Django rest framework extended user profile


code:
from PIL import Image

abs_img_src = 'test.png'

pill_img = Image.open(abs_img_src)
pill.show()

rotated_img = pill_img.rotate(90)
rotated_img.show()

rawDescription: Rotate photo via python

description: Rotate photo via python


code:
p = multiprocessing.Process()
p.start()
# Some time later ...
print('PID is ' + str(p.pid))

rawDescription: getting ProcessId within Python code

description: Getting ProcessId within Python code


code: rec = np.rec.fromarrays((t, data), dtype=[('t','f8'),('data','i2')])

rawDescription: how to make a numpy recarray from column arrays

description: Make a numpy recarray from column arrays


code:
@pytest.yield_fixture(scope="class") # <-- note class scope
def oneTimeSetUp(request, browser): # <-- note the additional `request` param
    print("Running one time setUp")
    if browser == 'firefox':
        driver = webdriver.Firefox()
        print("Running tests on FF")
    else:
        driver = webdriver.Chrome()
        print("Running tests on chrome")

    ## add `driver` attribute to the class under test -->
    if request.cls is not None:
        request.cls.driver = driver
    ## <--

    yield driver
    print("Running one time tearDown")

rawDescription: pytest -> How to use fixture return value in test method under a class

description: Pytest -> How to use fixture return value in test method under a class


rawDescription: Division by Zero Errors

description: Division by Zero Errors


rawDescription: How to use a conditional statement based on DataFrame boolean value in pandas

description: Use a conditional statement based on DataFrame boolean value in pandas


code: slice = arr[:2,:2]

rawDescription: Python: slicing a multi-dimensional array


rawDescription: Get an attribute in a template from a ManyToMany relationship in Django


code:
inst_name = 'instance' + inst_number
instance = globals()[inst_name]
instance.execute()

rawDescription: Writing a Python script to execute with a console command


code:
@route('/')
def index():
    refresh()
    return template('index', **my_dict)

rawDescription: How can I refresh data from yahoo finance API every time webpage is viewed in Python?

description: Refresh data from yahoo finance API every time webpage is viewed in Python


code: zip(*[iter(l)]*size) # Assuming 2 was the input

rawDescription: Python transforming one dimensional array into two dimensional array


rawDescription: What's the equivalent of PHP's "$my_array[]" in Python?


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

class UserProfile(models.Model):
    # This field is required.
    user = models.OneToOneField(User)

    # Other fields here
    accepted_eula = models.BooleanField()
    favorite_animal = models.CharField(max_length=20, default="Dragons.")

rawDescription: How to fields to the User model

description: Fields to the User model


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

import os

import cherrypy
from mako.lookup import TemplateLookup
from mako.template import Template

path   = os.path.abspath(os.path.dirname(__file__))
config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  }
}

lookup = TemplateLookup(directories=[os.path.join(path, 'view')])

class App:

  @cherrypy.expose
  def index(self):
    template = lookup.get_template('index.html')
    return template.render(foo = 'bar')

  @cherrypy.expose
  def directly(self):
    template = Template(filename = os.path.join(path, 'view', 'index.html'))
    return template.render(foo = 'bar')

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

rawDescription: Blank page through Mako template rendering in python / cherrypy


rawDescription: Avoid overflow when adding numpy arrays

description: Avoid overflow when adding numpy arrays


code:
import datetime
string = "2011-10-01 19:25:01"
dt = datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S")

rawDescription: Number Trouble with Regex in Python

description: Number Trouble with Regex in Python


rawDescription: Python beautiful soup how to get deep nested elements


code:
html = '''

	blah1blah1-1

	blah2blah2-1

	blah3blah3-1

	blah4blah4-1

	blah5blah5-1

'''

import lxml.html
root = lxml.html.fromstring(html)
print(root.xpath('.//table[3]/tr[position()>=2]/td[2]/a[2]/text()'))

rawDescription: Writing clean code in beautifulsoup

description: Writing clean code in beautifulsoup


code:
first_synset = next(wn.all_synsets())
dir(first_synset)

rawDescription: How can I print the entire contents of Wordnet (preferably with NLTK)?

description: Print the entire contents of Wordnet (preferably with NLTK)


code:
def drawTop():
    print (term.yellow("  CICS   000009/1           Centro Educacional Charles Darwin                 z\OS 3.2   "))
    print (term.yellow("  TERMINAL: 2297              Sistema de Controle de Notas                  VITÓRIA/ES   "))
    print (term.yellow(" ======================================================================================= "))

rawDescription: Clear only part of the screen in Python

description: Clear only part of the screen in Python


code:
loop = asyncio.get_event_loop()
coro = hello_world(loop)
asyncio.ensure_future(coro)
loop.run_forever()
loop.close()

rawDescription: Execute coroutine from `call_soon` callback function


rawDescription: Find a value within nested json dictionary in python


rawDescription: Function which is similar to numpy's diff


code: [list(g) for k,g in groupby((line.strip() for line in open('myfile.txt')), bool) if k]

rawDescription: itertools.takewhile within a generator function - why is it evaluated once only?

description: Itertools.takewhile within a generator function - why is it evaluated once only


code:
class Page(db.Model):
    url = db.StringProperty(required=True)
    has_items = db.BooleanProperty(default=False)

rawDescription: Google app engine python problem

description: Google app engine python problem


code:
import re
print(re.sub('a', '\U0001D15D', 'abc' ))
print(re.sub('a', u'\U0001D15D', 'abc' ).encode('unicode_escape'))

rawDescription: How to convert some character into five digit unicode one in Python 3.3?

description: Convert some character into five digit unicode one in Python 3.3


code: df['diff'] = df.groupby('A').shift(1) - df['B']

rawDescription: Shifted difference between columns respecting grouping


code:
import MyProduct

MyProduct.MyCoreBindings

rawDescription: What is the proper way to construct a Python package/module referencing a .PYD?


code:
dispatcher={'add':add}
w='add'
try:
    function=dispatcher[w]
except KeyError:
    raise ValueError('invalid input')

rawDescription: How to convert a string to a function in python?

description: Convert a string to a function in python


rawDescription: QTableWidget Integer

description: QTableWidget Integer


code:
def BVXNor(a, b):
    return BitVecRef(Z3_mk_bvxnor(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)

rawDescription: How do I encode bv-redand using the z3 Python API?

description: Encode bv-redand using the z3 Python API


code: soup = BeautifulSoup(data, "lxml")

rawDescription: Python extract info from a local html file


code:
import re
from pprint import pprint

import requests
from bs4 import BeautifulSoup

data = {}

# this pattern would help us to extract uid and src needed to make a GET request
pattern = re.compile(r"UID_(\w+)-SRC_(\w+)")

# making a web-scraping session
with requests.Session() as session:
    response = requests.get("http://www.tripadvisor.com/Attraction_Review-g143010-d108269-Reviews-Cadillac_Mountain-Acadia_National_Park_Mount_Desert_Island_Maine.html")
    soup = BeautifulSoup(response.content, "lxml")

    # iterating over usernames on the page
    for member in soup.select("div.member_info div.memberOverlayLink"):
        # extracting uid and src from the `id` attribute
        match = pattern.search(member['id'])
        if match:
            username = member.find("div", class_="username").text.strip()
            uid, src = match.groups()

            # making a GET request for the overlay information
            response = session.get("http://www.tripadvisor.com/MemberOverlay", params={
                "uid": uid,
                "src": src,
                "c": "",
                "fus": "false",
                "partner": "false",
                "LsoId": ""
            })

            # getting the grades dictionary
            soup_overlay = BeautifulSoup(response.content, "lxml")
            data[username] = {grade_type: soup_overlay.find("span", text=grade_type).find_next_sibling("span", class_="numbersText").text.strip(" ()")
                              for grade_type in ["Excellent", "Very good", "Average", "Poor", "Terrible"]}

pprint(data)

rawDescription: Scraping information from hoverbox

description: Scraping information from hoverbox


code:
bar1
75
bar2
76

rawDescription: Parsing HTML5 data-* attribute values with Selenium in Python


code:
from itertools import islice

def yield_specific_lines_from_file(filename, start, stop):
    with open(filename, 'rb') as ifile:
        yield from islice(ifile, start, stop)

lines = list(yield_specific_lines_from_file('test.txt', 10, 20))

rawDescription: Get data out of a file without iterating through it multiple times


code:
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=5, ncols=5)
plt.setp(axes.flat, xticks=[], yticks=[], zorder=0)

ax = axes[0,0]
ax.annotate('Testing this out and seeing what happens', xy=(0.5, 0.5),
            xytext=(1.1, .5), textcoords='axes fraction', zorder=100)

fig.texts.append(ax.texts.pop())

plt.show()

rawDescription: How to prevent a matplotlib annotation being clipped by other axes

description: Prevent a matplotlib annotation being clipped by other axes


code:
from itertools import islice

with open('largefilename', 'r') as largefile:
    for line in islice(largefile, N):
        # Process the first N lines, one by one
        output_file.write(line)

rawDescription: get 1sr N lines from a file of size 4GB python

description: Get 1sr N lines from a file of size 4GB python


code:
None
None
10
10

rawDescription: Super and child class sharing a variable


code: df['col3'] = (df.col2 > 0).astype('int')

rawDescription: Python Pandas Use if-else to populate new column


rawDescription: Fastest way to iterate through a pandas dataframe?


code: sorted(lst, key=lambda x: x[1])

rawDescription: How to sort an itertools grouper array in python

description: Sort an itertools grouper array in python


code:
inverse = {}
for key, values in adict.items():
    for value in values:
        inverse.setdefault(value, set()).add(key)

rawDescription: How do I inverse sort a dictionary that has sets as values?

description: Inverse sort a dictionary that has sets as values


code: cur = connection.cursor()

rawDescription: Error : function' object has no attribute 'execute'


code:
import heapq
from operator import itemgetter

thirty_largest = heapq.nlargest(30, d.iteritems(), key=itemgetter(1))

rawDescription: How to find to 30 biggest numbers from 1000 in dict?

description: Find to 30 biggest numbers from 1000 in dict


code: return query.fetch(300)

rawDescription: GAE Datastore ndb models accessed in 5 different ways


code:
Namespace(filter=[['include:a.txt,b.txt', 'exclude:c.txt,', 'd.txt']])
Namespace(filter=[['a.txt']])
Namespace(filter=[['include:b.txt'], ['exclude:d.txt']])
Namespace(filter=[['exclude:c.txt'], ['b.txt']])

rawDescription: Handling string with delimiters in argparse


code:
import requests
s = requests.Session()
#Sets language to english and saves cookie in Session s
s.get('http://www.gyte.edu.tr/?cl=2')
#Page in english
r = s.get("http://www.gyte.edu.tr/kategori/54/9/laboratories.aspx")

rawDescription: Python liburl grab site content with language


code:
def load_info():
    def load(x):
        if not x:
            return ''
        info = simplejson.loads(x)
        return '%s-%s' % (info['id'], info['name']) # the output format for info
    return load

rawDescription: AppEngine bulkloader export Model with self-defined Property


rawDescription: How to convert a string with multiple dictionaries, so json.load can parse it?

description: Convert a string with multiple dictionaries, so json.load can parse it


code:
import pprint
pprint.pprint(author)

rawDescription: Python,Sorting a dictionary

description: Python,Sorting a dictionary


code:
from PyQt4.QtGui import *
from MyMainWindow import *
from Form1 import *             # replace Form1 the name of your generated file
import sys

app = QApplication(sys.argv)

window = MyMainWindow(Ui_Form1())
window.show()

sys.exit(app.exec_())

rawDescription: How to run the program generated by pyuic4?

description: Run the program generated by pyuic4


code:
for i, n in enumerate(items):
    ...
    items[i] = n + step

rawDescription: Iterate over a list indexes

description: Iterate over a list indexes


code: y = [[d[k]['start qty'],d[k]['end qty']] for k in x]

rawDescription: transforming nested dictionaries into various lists

description: Transforming nested dictionaries into various lists