code:
import yaml
from collections import OrderedDict

class quoted(str): pass

def quoted_presenter(dumper, data):
    return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='"')
yaml.add_representer(quoted, quoted_presenter)

class literal(str): pass

def literal_presenter(dumper, data):
    return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
yaml.add_representer(literal, literal_presenter)

def ordered_dict_presenter(dumper, data):
    return dumper.represent_dict(data.items())
yaml.add_representer(OrderedDict, ordered_dict_presenter)

d = OrderedDict(short=quoted("Hello"), long=literal("Line1\nLine2\nLine3\n"))

print(yaml.dump(d))

rawDescription: How can I control what scalar form PyYAML uses for my data?

description: Control what scalar form PyYAML uses for my data


code:
def correct_labels(ax):
    labels = [item.get_text() for item in ax.get_xticklabels()]
    days=[label.split(" ")[0] for label in labels]
    months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
    final_labels=[]
    for i in range(len(days)):
        a=days[i].split("-")
        final_labels.append(a[2]+"\n"+months[int(a[1])-1])
    ax.set_xticklabels(final_labels)

rawDescription: Pandas Plots: Separate color for weekends, pretty printing times on x axis


code:
p = 3
range(p)

rawDescription: Python; Updating several positions in a list with "for x in range"


code:
import datetime
import calendar

calendar.timegm(datetime.date(2012, 5, 25).timetuple()) * 1000

rawDescription: jquery flot prints dates on the x-axis

description: Jquery flot prints dates on the x-axis


rawDescription: Python equivalent for do.call(rbind, lapply()) from R


code:
import os
from stat import S_IREAD, S_IRGRP, S_IROTH

filename = "path/to/file"
os.chmod(filename, S_IREAD|S_IRGRP|S_IROTH)

rawDescription: Change file to read-only mode in Python

description: Change file to read-only mode in Python


code:
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 200, 25
x = mu + sigma*np.random.randn(10000)
n, bins, patches = plt.hist(x)
plt.show()

rawDescription: Distribution plot of an array

description: Distribution plot of an array


rawDescription: Escaping Characters Regex

description: Escaping Characters Regex


code:
import os
appname = os.environ['APPLICATION_ID']

rawDescription: Name of Current App in Google App Engine (Python)


rawDescription: Why is the subprocess.Popen argument length limit smaller than what the OS reports?


code:
[u'np-c:function',
 u'std:label',
 u'c:member',
 u'np:classmethod',
 u'np:data',
 u'py:class',
 u'np-c:member',
 u'c:var',
 u'np:class',
 u'np:function',
 u'py:module',
 u'np-c:macro',
 u'np:exception',
 u'py:method',
 u'np:method',
 u'np-c:var',
 u'py:exception',
 u'np:staticmethod',
 u'py:staticmethod',
 u'c:type',
 u'np-c:type',
 u'c:macro',
 u'c:function',
 u'np:module',
 u'py:data',
 u'np:attribute',
 u'std:term',
 u'py:function',
 u'py:classmethod',
 u'py:attribute']

rawDescription: How to properly write coss-references to external documentation with intersphinx?

description: Properly write coss-references to external documentation with intersphinx


rawDescription: Matplotlib 3D Bar chart: axis issue

description: Matplotlib 3D Bar chart: axis issue


code:
from collections import namedtuple, OrderedDict
_property = property
from operator import itemgetter as _itemgetter
Arc = namedtuple('Arc', ['head', 'tail'], verbose=True)

rawDescription: How do I create a tuple with an attribute using Python?

description: Create a tuple with an attribute using Python


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import urllib, urllib2

from operator import itemgetter

def detect_language_v2(chunks, api_key):
    """
    chunks: either string or sequence of strings

    Return list of corresponding language codes
    """
    if isinstance(chunks, basestring):
        chunks = [chunks]

    url = 'https://www.googleapis.com/language/translate/v2'

    data = urllib.urlencode(dict(
        q=[t.encode('utf-8') if isinstance(t, unicode) else t
           for t in chunks],
        key=api_key,
        target="en"), doseq=1)

    # the request length MUST be < 5000
    if len(data) > 5000:
        raise ValueError("request is too long, see "
            "http://code.google.com/apis/language/translate/terms.html")

    #NOTE: use POST to allow more than 2K characters
    request = urllib2.Request(url, data,
        headers={'X-HTTP-Method-Override': 'GET'})
    d = json.load(urllib2.urlopen(request))
    if u'error' in d:
        raise IOError(d)
    return map(itemgetter('detectedSourceLanguage'), d['data']['translations'])

rawDescription: Python - can I detect unicode string language code?


code: setattr(self, 'name', self.get_thing)

rawDescription: Using setattr() in python

description: Using setattr() in python


code:
from collections import Counter
weekdays = Counter()
date_from = datetime.date(2014,11,30) # Sunday
date_to   = datetime.date(2014,12,9)  # Tuesday
for i in range((date_to - date_from).days+1):
   weekdays[(date_from + datetime.timedelta(i))\
                                 .strftime('%a')] += 1
weekdays

rawDescription: Number of times each weekday occurs between two dates


code:
class SetEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, set):
            return dict.fromkeys(obj)
        return json.JSONEncoder.default(self, obj)

rawDescription: Fastest method in merging of the two: dicts vs lists


rawDescription: Python Regular Expression to Edit First Comment


code:
def merge(things):
    return {'id': things[0]['id'],
            'ua': list(itertools.chain.from_iterable(t['ua'] for t in things))}
sorted_things = sorted(things, key=operator.itemgetter('id'))
grouped_things = itertools.groupby(sorted_things, key=operator.itemgetter('id'))
new_things = [merge(list(group)) for key, group in grouped_things]

rawDescription: Combining JSON values based on key

description: Combining JSON values based on key


code:
def recursive_remap(d, keymap):
    if isinstance(d, dict):
        return {keymap[k]: recursive_remap(v, keymap) for k, v in d.items()}
    return d

dict3 = recursive_remap(dict1, dict2_inverse)

rawDescription: Remap keys of a recursive dictionary, using another dictionary


code: v = (tfidf * tfidf[idx, :]).transpose()

rawDescription: Reverse sort and argsort in python

description: Reverse sort and argsort in python


code:
plt.xticks(range(25),[str(i) for i in range(25)])
plt.yticks(range(0,180,10),[str(i) for i in range(0,180,10)])

rawDescription: can't change matplotlib.pyplot tick marks

description: Can't change matplotlib.pyplot tick marks


code:
br.select_form(nr=0)
br.form.set_all_readonly(False)
message += ' ' * (140 - len(message))
br.form['mobile'] = mobile
br.form['message'] = message
br.form['msgLen'] = str(140)
br.form.method = 'POST'
sendurl = 'http://site23.way2sms.com/smstoss.action'
br.form.action = sendurl
br.form.fixup()
res = br.submit()

rawDescription: Python Mechanize - Way2Sms Sending Message


code:
###############################################################################
#
# Example 9.
#
caption = ('Rows with odd numbers are in light red. '
           'Rows with even numbers are in light green.')

# Write the data.
worksheet9.write('A1', caption)

for row, row_data in enumerate(data):
    if row%2 == 0:
        worksheet9.write_row(row + 2, 1, row_data, format1)
    else:
        worksheet9.write_row(row + 2, 1, row_data, format2)

rawDescription: Applying formatting row by row in addition to column formatting with xlsxwriter


code:
from itertools import product
list1 = ['cake', 'pie', 'bread']
list2 = ['blue', 'red', 'yellow']
list(product(list1, list2))

rawDescription: Python - Combining two lists of strings to create a matrix/table of their combinations


code: N = mutable_object['key']

rawDescription: how to return a value from button_press_event matplotlib?

description: Return a value from button_press_event matplotlib


code: os.chown("path/to/file", uid, gid)

rawDescription: Creating a file with python using sudo makes its owner root


code:
from scipy.ndimage import generic_filter
generic_filter(data, np.all, size=(5,5), mode='constant', cval=0).astype(np.bool)

rawDescription: Extract indices of a 2D binary array

description: Extract indices of a 2D binary array


code:
expr = """
    CASE
        WHEN user_agent LIKE \'%Android%\' THEN \'mobile\'
        WHEN user_agent LIKE \'%Linux%\' THEN \'desktop\'
        ELSE \'other_unknown\'
    END AS user_agent_type"""

df = sc.parallelize([
    (1, "Android"), (2, "Linux"), (3, "Foo")
]).toDF(["id", "user_agent"])

df.selectExpr("*", expr).show()
## +---+----------+---------------+
## | id|user_agent|user_agent_type|
## +---+----------+---------------+
## |  1|   Android|         mobile|
## |  2|     Linux|        desktop|
## |  3|       Foo|  other_unknown|
## +---+----------+---------------+

rawDescription: How to perform a Switch statement with Apache Spark Dataframes (Python)

description: Perform a Switch statement with Apache Spark Dataframes (Python)


code:
import A, C
class B(object):
    def __init__(self, classC):
        vars(self).update(vars(A()))
        if classC:
            vars(self).update(vars(C()))
    def methodb(self):
        return 2

rawDescription: Python: Inheriting methods of a parent class without being a child of the class


code:
def get_client_address(environ):
    try:
        return environ['HTTP_X_FORWARDED_FOR'].split(',')[-1].strip()
    except KeyError:
        return environ['REMOTE_ADDR']

rawDescription: Obtaining Client IP address from a WSGI app using Eventlet


code:
import bencode
torrent = open('ubuntu-12.04.1-desktop-i386.iso.torrent', 'r').read()
metadata = bencode.bdecode(torrent)

rawDescription: Given a .torrent file how do I generate a magnet link in python?


code:
import main
import topic

handlers=[]
handlers.extend(main.handlers)
handlers.extend(topic.handlers)

ui_modules={}

rawDescription: How do I access my database level functions inside other classes/files in Tornado?

description: Access my database level functions inside other classes/files in Tornado


code: RawConfigParser.set('Section', 'option1', '%s,%s' % (i, t_delta.total_seconds()))

rawDescription: Correct way of getting time delta value from config file


code:
def __repr__(self, *args, **kwargs):
    self._check_expire()
    return dict.__repr__(self, *args, **kwargs)

rawDescription: What method is used when accessing a dict as a whole?


code: yield line.strip('\r\n')

rawDescription: Remove new line character from lines in Python


code:
def main():
    file = ("F:/media/KINGSTON/Networking/network.txt")
    Alist = create_matrix(file)
    node = start_node(Alist)
    check_neighbours(node, Alist)
main()

rawDescription: python passing variables between functions

description: Python passing variables between functions


rawDescription: Why is this python if statement not equal to true?


code:
input_string = ("""The cat in the hat
Red fish blue fish """)

words = [i.split(" ") for i in  input_string.split('\n')]

rawDescription: Creating a list from another list - Python


code:
class XmlDocument(object):
    def __init__(self, file, nodename=None, has_S=False, has_LEX=False, pos_attr=False):
        if isinstance(file, xml.dom.minidom.Document):
            self._xml_doc = file
        else:
            self._xml_doc = xml.dom.minidom.parseString(file)

rawDescription: Ternip can't format a string

description: Ternip can't format a string


code:
import numpy as np
t = [[a/b, b/a],[a*a,b*b]]
tl=np.reshape(map(lambda tc: '$'+latex(tc)+'$',np.ravel(t)),np.shape(t))
df = DataFrame(tl, index=['Situation 1', 'Situation 2'], columns=['Answer 1','Answer 2'])
df

rawDescription: How to Render Math Table Properly in IPython Notebook


code:
import re
text1 = '\bhttp://oaei.ontologymatching.org/2011/benchmarks/101/onto.rdf#Reference http://oaei.ontologymatching.org/2011/benchmarks/101/onto.rdf#Informal ACADEMIC type http://oaei.ontologymatching.org/2011/benchmarks/101/onto.rdf#school ACADEMIC type'
re.sub(r'https?://[^# ]+#?', '', text1)

rawDescription: Extracting strings starting with symbols and combining with others from a text using python


rawDescription: Summarizing dataframe into a dictionary

description: Summarizing dataframe into a dictionary


code:
vals0 = [0, 0, 0, 0, 0]
vals1 = [1, 1, 1, 1, 1]
vals2 = [0, 1, 0, 1, 0]
def category(vals):
    if all(vals):
        return 1
    elif any(vals):
        return 2
    else:
        return 0

category(vals0)
category(vals1)
category(vals2)

rawDescription: Efficient way of counting True and False


code:
from kivy.app import App
from kivy.uix.button import Button

class ScrollButton(Button):
    pass

class ScrollApp(App):
    def build(self):
        super(ScrollApp, self).build()
        container = self.root.ids.container
        for i in range(30):
            container.add_widget(ScrollButton(text=str(i)))
        return root

if __name__ == '__main__':
    ScrollApp().run()

rawDescription: Kivy: ScrollViewApp example in Kivy Language


rawDescription: matlab find() for nonzero element in python

description: Matlab find() for nonzero element in python


code:
class Person(models.Model):
    name = models.CharField(primary_key=True, max_length=...)

class JobInfo(models.Model):
    person = models.ForeignKey(Person, primary_key=True, db_column='name', to_field='name')
    startdate = models.DateField(db_column='startdate')
    ...

rawDescription: How to query multiple Django models describing denormalized tables

description: Query multiple Django models describing denormalized tables


code:
password_layout = QtGui.QGridLayout()
# Set the stretch
password_layout.setColumnStretch(0, 1)
password_layout.setColumnStretch(3, 1)
password_layout.setRowStretch(0, 1)
password_layout.setRowStretch(3, 1)
# Add widgets
password_layout.addWidget(username_label, 1, 1)
password_layout.addWidget(password_label, 2, 1)
password_layout.addWidget(_username, 1, 2)
password_layout.addWidget(_password, 2, 2)

rawDescription: PyQt - Centering Widget in resizable GridLayout


code: cache.set('userid', 234, 30)

rawDescription: Python sharing data across all modules in django app


code:
import numpy as np #Imports Python mathematical functions library
import matplotlib.pyplot as plt #Imports plot library
cos = np.cos
pi = np.pi

a = 5
e = 0.3
theta = np.linspace(0,2*pi, 360)
r = (a*(1-e**2))/(1+e*cos(theta))
plt.polar(theta, r)

print(np.c_[r,theta])

plt.show()

rawDescription: Plotting elliptical orbits

description: Plotting elliptical orbits


code:
import tornado.ioloop
import tornado.web

import ui_methods

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("main.html")

urls = [(r"/", MainHandler)]
application = tornado.web.Application(urls, ui_methods=ui_methods)

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Passing a custom python function into a tornado template


rawDescription: How do I to translate this json format into correct format that can be used pandas read_json()

description: To translate this json format into correct format that can be used pandas read_json()


rawDescription: How can I modify my wxPython code live to avoid closing/reopening them?

description: Modify my wxPython code live to avoid closing/reopening them


code: value_list = list(map(operator.methodcaller(method_name), object_list))

rawDescription: Choosing which instance method to use

description: Choosing which instance method to use


code: a = int(raw_input("please enter number: "))

rawDescription: python accessing the value of the raw_input as parameter

description: Python accessing the value of the raw_input as parameter


code:
def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            break
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            period = 0
            break

    return period

rawDescription: How can I stop a While loop?

description: Stop a While loop


code:
def sleepjob(*a, **k):
    if a:
        return Worker.SLEEP, a[0]
    else:
        return Worker.SLEEP, timedelta(**k)

rawDescription: Python generator's 'yield' in separate function


code:
import logging, traceback
logging.basicConfig(filename=r'C:\Temp\log.txt', level=logging.DEBUG)

try:
    #do some stuff
    logging.debug('I did some stuff!')
except SomeException:
    logging.error(traceback.format_exc())

rawDescription: How do you make Python wait so that you can read the output?

description: Make Python wait so that you can read the output


code:
@property
def full_name(self):
    return self.first_name + " " + self.last_name

rawDescription: More Pythonic way of adding attributes to class?


code: [max(group, key=itemgetter(2)) for fruit, group in groupby(fruits, itemgetter(0))]

rawDescription: Python Filter List Items Relative to Each Other


code: results = [ item['value'] for item in test_data ]

rawDescription: How do I extract all the values of a specific key from a list of dictionaries?

description: Extract all the values of a specific key from a list of dictionaries


rawDescription: Most efficient way to recode these multiple if statements


code:
def spliter(s):
   return [i.strip() for i in re.split(r'[+-]',s)]

spliter(s1)
s3="4x + 12z - 18k"
spliter(s3)

rawDescription: re.split('[+ -]',f) or better stepping to partial derivatives

description: Re.split('[+ -]',f) or better stepping to partial derivatives


code:
from operator import itemgetter
from itertools import imap, izip

last_element = imap(itemgetter(-1), a)
in_threes = izip(*[iter(last_element)] * 3)
res = map(list, in_threes)
# [[0, 3, 1], [2, 5, 2], [1, 2, 0], [0, 4, 2]]

rawDescription: Using the last element from each list in Python


rawDescription: What's the best style, class method or global function?


code:
import re
[ re.sub(r'[{}]+'.format(punctuation),'',x ) for x in lis]
re.sub(r'[{}]+'.format(punctuation),'', strs)

rawDescription: How to remove the punctuation in the middle of a word or numbers?

description: Remove the punctuation in the middle of a word or numbers


code:
def create_pyramid(rows):
    for i in range(rows):
        print('Y' * ( i + 1))

create_pyramid(6)

rawDescription: Using python, How can I make a pyramid using for loops?


code:
def my_slice(word, step):
    '''slice word with only step'''
    start = len(word)-1 if step < 0 else 0
    stop = -len(word)-1 if step < 0 else len(word)
    return word[start:stop:step]

word = "hello"
step = -1
my_slice(word, step)

rawDescription: Reverse a Python string without omitting start and end slice


code:
def list2dict(list_):
    return_dict = dict()
    for idx,word in enumerate(list_):
        return_dict.setdefault(word,idx)
    return return_dict

rawDescription: Speed issues when converting list to dictionary


code:
path = 'C:/Python27/aisources/'
os.chdir(path)
sfile=raw_input("What is your filename to check? ")
if os.path.exists(sfile):
     with open(sfile,'r') as f:
         print('its present')
else:
    print('not there')

rawDescription: access all files in a directory

description: Access all files in a directory


rawDescription: Probability list creation

description: Probability list creation


code: roots = [n for n in nodes.values() if d.value["PARENT"] is None]

rawDescription: Build tree out of list of parent/children in Python


code:
import os
path=os.path.dirname("C:/folder1/folder2/filename.xml")
path
os.path.basename(path)

rawDescription: Get folder name of the file in Python

description: Get folder name of the file in Python


code:
def newlist():
    with open('words.txt') as fin:
        listy = set()
        for word in fin:
            n1 = word.strip()
            n2 = sorted(n1)
            red = ''.join(n2)
            listy.add(red)
    return listy

newlist()

rawDescription: Think Python Ch12 Ex 4: Code seems correct but hangs when compiled


code:
for one_score in all_scores:
    score_file.write( str(one_score) + "\n")

rawDescription: Looping test scores in file input/output


rawDescription: Why the id of an object would change depending on the line in the python shell


code:
newtag = soup.new_tag("div")
newtag['class'] = "placeholder"
tag.wrap(newtag)

rawDescription: Beautiful Soup - inserting before extracted portion of parse tree


code:
everything = []
for row in data:
    everything.append[row]

rawDescription: Python sketch not working as intended (reading data from CSV)


rawDescription: View function is not being called in Django


code:
df
pd.melt(df,id_vars='Product', var_name='Location',value_name='Total Sold')

rawDescription: Merge columns and create new column with pandas


code: [(k, hash(k) % 32) for k in globals().keys() ]

rawDescription: Why is early return slower than else?

description: Why is early return slower than else


code:
ab = np.hstack((a, b))
s = np.argsort(ab)
t = np.hstack((np.zeros_like(a), np.ones_like(b)))[s]
ab[s][np.concatenate(([True], t[1:] != t[:-1]))]
array([ 1,  5,  7, 13, 17, 19])

rawDescription: Interleaving two numpy index arrays, one item from each array


code:
tasks_dict = dict((task['id'], task) for task in tasks)
folders_dict = dict((folder['id'], folder) for folder in folders)
forbidden_folders_set = set(forbiddenFolders)

rawDescription: Alternative to nested `for` loops in Python


code:
new_path = [self.path[0]] #keep the first element since it will always be needed
for node in range(1,len(self.path)-1):
    direction1 = (self.path[node-1][0] - self.path[node][0], self.path[node-1][1] - self.path[node][1])
    direction2 = (self.path[node][0] - self.path[node+1][0], self.path[node][1] - self.path[node+1][1])
    if direction1 != direction2:
        new_path.append(self.path[node])
new_path.append(self.path[-1]) #add in the last element
self.path = new_path

rawDescription: How to only output turning points of a path for maze

description: Only output turning points of a path for maze


code:
def opt_must_contain(context, request):
    opt = request.matchdict.get('opt')
    return opt in ('opt_a', 'opt_b', 'opt_c')

config.add_route('my_route', '/view_1/{opt}')

@view_config(route_name='my_route', custom_predicates=[opt_must_contain])
def my_view(request):
    opt = request.matchdict.get('opt')

rawDescription: Pyramid: Routing schemas and restraints

description: Pyramid: Routing schemas and restraints


code:
result = np.empty_like(X)
for i, x in enumerate(X):
    result[i] = func1d(x)

rawDescription: Python apply_along_axis of multiple arrays


rawDescription: All matrix row combination

description: All matrix row combination


code:
from string import ascii_lowercase
from random import choice

letters = [choice(ascii_lowercase) for _ in range(5)]

rawDescription: Sequence of letters in Python

description: Sequence of letters in Python


rawDescription: pymongo group by datetime

description: Pymongo group by datetime


code:
import json
import re
from django import template

register = template.Library()

@register.filter
def my_filter(value):
    string = json.dumps(value, indent=4)
    result = '
'
    for row in string.split('\n'):
        content = re.sub(r'\s{4}', ' ', row.rstrip())
        result += '
%s
' % content
    result += '
'
    return result

rawDescription: Create a table, line-by-line of a dictionary using json.dump or pprint in django template [python]


code:
from functools import update_wrapper

bar10_p = partial(foo, b=10)
update_wrapper(bar10_p, foo)

rawDescription: Partial function application with the original docstring in Python?


code:
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'searchbox')))

rawDescription: Selenium: Wait until text in WebElement changes


code:
df['datetime'] = pd.to_datetime(df.datetime)
df.set_index('datetime', inplace=True)

rawDescription: How can I use Pandas to round inconsistent timestamps to five minute intervals and fill gaps?

description: Use Pandas to round inconsistent timestamps to five minute intervals and fill gaps


rawDescription: How do I calculate the Euclidean distance between a point and a list of points in Python?

description: Calculate the Euclidean distance between a point and a list of points in Python


code:
l1 = (lambda angle=angle, belong=belong, THRES_THETA=THRES_THETA, lines_lengths_vstacked=lines_lengths_vstacked, max_line_length=max_line_length:
      np.sum(belong*(0.3 * (1-(angle/THRES_THETA)) + 0.7 * (lines_lengths_vstacked/max_line_length)), axis=1))
t1 = timeit.Timer(l1)
print(t1.repeat(3, 100))

l2 = (lambda angle=angle, belong=belong, THRES_THETA=THRES_THETA, lines_lengths_vstacked=lines_lengths_vstacked, max_line_length=max_line_length:
    np.einsum('ij,ij->i', belong, 0.3 * (1-(angle/THRES_THETA)) + 0.7 * (lines_lengths_vstacked/max_line_length)))
t2 = timeit.Timer(l2)
print(t2.repeat(3, 100))

l3 = (lambda angle=angle, belong=belong, THRES_THETA=THRES_THETA, lines_lengths_vstacked=lines_lengths_vstacked, max_line_length=max_line_length:
      vote_op(angle, belong, THRES_THETA, lines_lengths_vstacked, max_line_length))
t3 = timeit.Timer(l3)
print(t3.repeat(3, 100))

rawDescription: numpy 2d boolean array indexing with reduce along one axis

description: Numpy 2d boolean array indexing with reduce along one axis


code:
def __init__(self):
    self.user = None
    self.email = None

rawDescription: Clear all class variables between instances


code:
class MySpider(BaseSpider):
    stock = ["SCMP", "APPL", "GOOG"]
    name =  "dozen"
    allowed_domains = ["yahoo.com"]
    def stock_list(stock):
        start_urls = []
        for i in stock:
            start_urls.append("http://finance.yahoo.com/q/is?s={}".format(i))
        return start_urls
    start_urls = stock_list(stock)

rawDescription: Python: Scrapy start_urls list able to handle .format()?


rawDescription: How to find if consensus on answer

description: Find if consensus on answer


rawDescription: Replacing things like \t\r using Python

description: Replacing things like \t\r using Python


rawDescription: Finding intersection of points on a python graph generated by a list of points


code:
def makeNewClass(x):
    def init(self,attribute1,attribute2):
        # make sure you call the base class constructor here
        self.attribute2 = attribute2

    # make a new type and return it
    return type(x, (MySuperClass,), {'__init__': init})

x = "MySubClass"
MySubClass = makeNewClass(x)

rawDescription: how to dynamically generate a subclass in a function?

description: Dynamically generate a subclass in a function


rawDescription: Pandas: how to concisely detrend subset of columns


rawDescription: Removing each element at the value in each key


code:
transposed = [tuple(map(lambda x: w if w in x else '', allSets))
              for t in sortedTokens]
result = zip(*transposed)

rawDescription: Compare N lists and insert/append blank entries where discrepancies exist


code:
xdata = np.array([ 62.,  145.,  227.])
sine_func(xdata, lam, phi, A)

rawDescription: Python matplotlib sine function with some fixed points


code:
class Foo(object):
    #define foolist at the class level
    #(not at the instance level as self.foolist would be defined in a method)
    foolist=[]

A=Foo()
B=Foo()

A.foolist.append("bar")
print (B.foolist)  # ["bar"]
print (A.foolist is B.foolist) #True -- A and B are sharing the same foolist variable.

rawDescription: using variables in class functions in another class (python)

description: Using variables in class functions in another class (python)


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx

DATA = np.random.rand(5,5)

cmap = plt.cm.jet

cNorm  = colors.Normalize(vmin=np.min(DATA[:,4]), vmax=np.max(DATA[:,4]))

scalarMap = cmx.ScalarMappable(norm=cNorm,cmap=cmap)

for idx in range(0,len(DATA[:,1])):
    colorVal = scalarMap.to_rgba(DATA[idx,4])
    plt.arrow(DATA[idx,0],  #x1
              DATA[idx,1],  # y1
              DATA[idx,2]-DATA[idx,0], # x2 - x1
              DATA[idx,3]-DATA[idx,1], # y2 - y1
              color=colorVal)

plt.show()

rawDescription: Plotting arrows with different color in matplotlib


code:
import matplotlib.pyplot as plt
from mpldatacursor import datacursor
import random

fig, ax = plt.subplots()
ax.set_title('Click on a dot to display its label')

# Plot a number of random dots
for i in range(1, 1000):
    ax.scatter([random.random()], [random.random()], label='$ID: {}$'.format(i))

# Use a DataCursor to interactively display the label for a selected line...
datacursor(formatter='{label}'.format)

plt.show()

rawDescription: Python: get corresponding information of data points interactively with mouse


code: return "Create new user sucesso!"

rawDescription: Flask show return data on request

description: Flask show return data on request


code: find(("string1", "string2"), source1, source2)

rawDescription: Python: "Multiple" multiple arguments in function


code:
result = []
for t in types:
    result.extend(glob.glob("{}/{}*{}.fits".format(target, name, t)))
return result

rawDescription: looping through specific files in python

description: Looping through specific files in python


rawDescription: Unescaping filenames generated by ls -R

description: Unescaping filenames generated by ls -R


code:
@patch("Derived.Parent.__init__")
def test_init_001(self, mock_parent_init):
    mock_parent_init.return_value = None  # <---
    a = Derived("I am Derived")
    mock_parent_init.assert_called_with("I am Derived")
    self.assertEquals(a.parent_list, ["PARENT", "DERIVED"])

rawDescription: Mock parent class __init__ method

description: Mock parent class __init__ method


code:
import scipy.sparse
import numpy
import time

def csr_row_set_nz_to_val(csr, row, value=0):
    """Set all nonzero elements (elements currently in the sparsity pattern)
    to the given value. Useful to set to 0 mostly.
    """
    if not isinstance(csr, scipy.sparse.csr_matrix):
        raise ValueError('Matrix given must be of CSR format.')
    csr.data[csr.indptr[row]:csr.indptr[row+1]] = value

def csr_rows_set_nz_to_val(csr, rows, value=0):
    for row in rows:
        csr_row_set_nz_to_val(csr, row)
    if value == 0:
        csr.eliminate_zeros()

rawDescription: What is most efficient way of setting row to zeros for a sparse scipy matrix?


code: (word.count(c) for c in consonants)

rawDescription: How would I go about counting the number of consonants in a word? python


rawDescription: Efficient algorithm for expanding grouped tabular data


code:
a = np.random.normal(0.0,0.5,size=(5000,10))**2
a = a/np.sum(a,axis=1)[:,None]  # Normalize

pcolor(a)

rawDescription: plotting a 2D matrix in python, code and most useful visualization

description: Plotting a 2D matrix in python, code and most useful visualization


code:
for filename in os.listdir():
  file_contents = open(filename, 'r').read()
  globals()[filename] = file_contents

rawDescription: How to loop the files in a directory, and set variables named after the files?

description: Loop the files in a directory, and set variables named after the files


code:
class SingletonA:
    def __init__(self):

        # some state
        print("Creating dummy state in SingletonA")

    def _init(self):

        # some state
        print("Creating state in A")
        self.X = 1.
        self.Y = 2.
    def __new__(cls, *args, **kwargs):
        return cls._instance

SingletonA._instance = super(SingletonA, SingletonA).__new__(SingletonA)
SingletonA._instance._init()

rawDescription: singleton design pattern in Python with state

description: Singleton design pattern in Python with state


rawDescription: Select and sort integers/strings from a text file in Python


code:
data = {"dogs":[{"tail": True, "properties":{"test":1}}]}

path = ["dogs", 0, "properties"]
mydata = data
for i in path:
    mydata = mydata[i]

mydata["test"] = 2
print(data)

rawDescription: Modify an element in a nested dict given a "path" to it


code:
def helper_to_subtract_pairs(acc, x):
    return acc[:-1] + [x[0] - acc[-1]] + [x[1]]

rawDescription: Calculating the gap between pairs of twin primes in python


code:
import io
help(io.FileIO.seek)

rawDescription: How to view file handling functions documentation using help function in Python 3?

description: View file handling functions documentation using help function in Python 3


code: zip(*myList)

rawDescription: How to change the major order of lists in python?

description: Change the major order of lists in python


code:
f = open('path/to/file', 'w')
for pixels in nums:
    f.write(', '.join(str(255 - rgb) for rgb in pixels) +'\n')
f.close()

rawDescription: How to limit the list comprehension from repeating when inside a loop?

description: Limit the list comprehension from repeating when inside a loop


code: return len(alist) == len(anotherList) and sorted(alist) == sorted(anotherList)

rawDescription: Efficiently test if two lists have the same elements and length


rawDescription: Python: How to remove quotes around numbers from string


code: pd.concat([df1, df2], axis=1)

rawDescription: Turn dataframe into frequency list with two column variables in Python


code: from mpl_toolkits.basemap import Basemap, addcyclic

rawDescription: Plotting netCDF data with Python: How to change grid?


code:
channel_routing = {
    "websocket.connect": "news_providers.consumers.ws_foo",
    "websocket.keepalive": "news_providers.consumers.ws_foo",
    "websocket.receive": "news_providers.consumers.ws_message",
    "websocket.disconnect": "news_providers.consumers.ws_foo",
}

rawDescription: How to use Channel instead of Group when using django channels?

description: Use Channel instead of Group when using django channels


code:
test_array.min()
test_array.max()
test_array.take(0)
test_array.flat[0]

rawDescription: get a dict out of an ndarray

description: Get a dict out of an ndarray


code:
import json
obj= json.loads( aString )
obj['session_key']

rawDescription: which is the best way to get the value of 'session_key','uid','expires'

description: Which is the best way to get the value of 'session_key','uid','expires'


code:
l = [datetime.date(1976, 8, 4), datetime.date(2005, 8, 8), ...] # values_list(flat=True)
today = datetime.date.today()
average_age = sum(map(lambda x: today-x, l), datetime.timedelta(0))/len(l)

rawDescription: Calculating average age in Python

description: Calculating average age in Python


code:
def _get_modules_from_db(dictionary):
    leaves = []
    for k, v in dictionary.iteritems():
        if (isinstance(v, dict) and
            not sorted(v.keys()) == ['path_to_file', 'sha512sum']):
            leaves.extend(_get_modules_from_db(v))
        else:
            leaves.append(v)
    return leaves

rawDescription: Recursive function in Python: Best way to get a list of specific nested items


code:
foo_max_time_q = select([func.max(Foo.time).label('foo_max_time'),
                         Foo.id.label('foo_id')
                        ]).group_by(Foo.id
                         ).alias("foo_max_time_q")

foo_q = session.query(
          Foo.id.label('foo_id'),
          Foo.version.label('foo_version'),
          Foo.revision.label('foo_revision'),
          foo_max_time_q.c.foo_max_time.label('foo_max_time')
                ).join(foo_max_time_q,
                       foo_max_time_q.c.foo_id == Foo.id)

print(foo_q.__str__())

rawDescription: Sqlalchemy: subquery in FROM must have an alias


code:
import re

print(re.findall("Name\s+=\s+\"(.*?)\",",s)[0])
version

rawDescription: How to split string into dictionary and return a specific dictionary value?

description: Split string into dictionary and return a specific dictionary value


rawDescription: pythonic way to explode a list of tuples

description: Pythonic way to explode a list of tuples


code:
from itertools import chain
from glob import glob

lines = list(chain.from_iterable(open(f, 'r') for f in glob('./files/*.??')))
lines.sort()

with open('listTogether.txt', 'w') as out:
    out.writelines(lines)

rawDescription: Merge all .txt files into one text file and alphabetise that text file


code:
def my_view(request):
    if request.user.is_authenticated():
        return render(request, 'template1.html')
    else:
        return render(request, 'template2.html')

rawDescription: Django: Detect unused templates

description: Django: Detect unused templates


code: -s

rawDescription: Pycharm and sys.argv arguments

description: Pycharm and sys.argv arguments


code: data.reshape(3, -1, 3).swapaxes(1, 2)

rawDescription: Python matplotlib animation randomly jumping to initial position


code:
for i in range(len(v.num_rows)):
    for j in range(len(v.num_cols)):
        v[i][j] = random.random()

rawDescription: How to randomize all the items in a matrix in python

description: Randomize all the items in a matrix in python


code:
x1 = profile1()
x2 = profile2()
np.allclose(x1, x2)

rawDescription: Alternative to numpy roll without copying array


code:
def Addzero(value):
    if(len(value) > 8) :
        return value
    else :
        return [0] * (8-len(value)) + value

rawDescription: Prepending zeros to a list

description: Prepending zeros to a list


rawDescription: PIL? Extract all pixels of a given RGB value


code:
import os
def fixpath(path):
    return os.path.abspath(os.path.expanduser(path))

rawDescription: Using absolute unix paths in windows with python


rawDescription: how to set .__name__ in python?

description: Set .__name__ in python


code: df['week'] = df.index.week

rawDescription: Plotting Weekly Tick Data From A Year Time Series


rawDescription: How to add classmethod to a python class?

description: Add classmethod to a python class


code:
def add_face(M, new_face, dim, front_side):
    #assume sizes match up correctly
    if front_side:
        return np.concatenate((new_face, M), dim)
    else:
        return np.concatenate((M, new_face), dim)

rawDescription: Selecting (n-1)D array from (n)D array in numpy


code: integers = [int(n) for n in range(2, limit + 1) if (n is 2) or (n % 2 != 0)]

rawDescription: Python code structure & convention - Creating a elements for a list with a loop


code:
def sliding_fitted_slope(x, y, win):
    x = np.concatenate(([0], x))
    y = np.concatenate(([0], y))
    Sx = np.cumsum(x)
    Sy = np.cumsum(y)
    Sx2 = np.cumsum(x*x)
    Sxy = np.cumsum(x*y)

    Sx = Sx[win:] - Sx[:-win]
    Sy = Sy[win:] - Sy[:-win]
    Sx2 = Sx2[win:] - Sx2[:-win]
    Sxy = Sxy[win:] - Sxy[:-win]

    return (win*Sxy - Sx*Sy) / (win*Sx2 - Sx*Sx)

rawDescription: Fully vectorise numpy polyfit

description: Fully vectorise numpy polyfit


rawDescription: How to design a python class which will behave like root classes

description: Design a python class which will behave like root classes


code:
import random
from tkinter import *

class Sorting(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.function = {0:self.bubble, 1:self.quick, 2:self.shell}
        self.master.title("Sorting")
        self.master.rowconfigure(5, weight=1)
        self.master.columnconfigure(5, weight=1)
        self.grid(sticky=W+E+N+S )

        #label for sort intro
        self.label1 = Label(self, text="Select Sort", width=25, height=2)
        self.label1.grid(row=0, column=1, sticky=N)

        #Radio buttons for sorts
        self.v = IntVar()
        for indx, button in enumerate(('Bubble', 'Quick', 'Shell')):
            name = "%s Sort" % button
            button = Radiobutton(self, text=name, variable=self.v, value=indx)
            button.grid(row=1, column=indx, sticky=W+E+N+S)
        button.deselect()

        #button to generate number
        self.button4 = Button(self,text='Generate no.',command=self.gen)
        self.button4.grid(row=2, column=1, sticky=W+E+N+S)
        self.rowconfigure(5, weight=1)
        self.columnconfigure(5, weight=1)

    def create_but2sort(self):
        self.button5 = Button(self, text='start sorting', command=self.sortit)
        self.button5.grid(row=4, column=1, sticky=W+E+N+S)
        self.rowconfigure(5, weight=1 )
        self.columnconfigure(5, weight=1)

    def gen(self):
        self.nums = [random.randint(0, 100) for x in range(10)]
        num = ''.join('%4i' % num for num in self.nums)
        self.label2 = Label(self, text=num, width=2, height=2)
        self.label2.grid(row =3, columnspan=10, sticky = W+E+N+S)
        self.create_but2sort()

    def sortit(self):
        function = self.function[self.v.get()]
        result = function()
        num = ''.join('%4i' % num for num in result)
        self.label3 = Label(self, text=num, width=2, height=2)
        self.label3.grid(row=5, columnspan=10, sticky=W+E+N+S )

    def bubble(self):
        print('bubble to be implemented')
        return sorted(self.nums)

    def shell(self):
        print('shell to be implemented')
        return sorted(self.nums)

    def quick(self):
        print('quick to be implemented')
        return sorted(self.nums)

def main():
    Sorting().mainloop()

if __name__ == "__main__":
    main()

rawDescription: GUI for choosing different sorting in python by Tkinter


rawDescription: Merge dictionaries with key combinations


code:
import random

class Vigenere(object):

    #Initialize Vigenere object.
        #Sets the random seed based on integer passed to the object
        #Establishes all valid symbols
        #Generates empty matrix which will contain values for encryption/decryption
        #Generates a keyword based on the integer passed to the object
    def __init__(self, seed):
        random.seed(seed)
        self.seed = seed
        self.symbols= """ !"#$%&'()*+,-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
        self.Table = [[0 for i in range(len(self.symbols))] for i in range(len(self.symbols))]
        self.keyWord = ""
        self.message = ""
        self.ciphertext = ""
        self.keywordFromSeed(seed)

    #Sets the plaintext that will be encrypted/decrypted
    def setMessage(self,message):
        self.message = message

    #Generate psuedorandom keyword from seed
    def keywordFromSeed(self,seed):
        Letters = []

        while seed > 0:
            Letters.insert(0,chr((seed % 100) % 26 + 65))
            seed = seed // 100
        self.keyWord = "".join(Letters)
        self.buildVigenere()

    #Contructs a 95 x 95 matrix filled randomly with no repeats within same line
    def buildVigenere(self):
        random.seed(self.seed)
        temp = list(self.symbols)
        random.shuffle(temp)
        temp = ''.join(temp)

        for sym in temp:
            random.seed(self.seed)
            myList = []
            for i in range(len(temp)):
                r = random.randrange(len(temp))
                if r not in myList:
                    myList.append(r)
                else:
                    while(r in myList):
                        r = random.randrange(len(temp))
                    myList.append(r)
                while(self.Table[i][r] != 0):
                    r = (r + 1) % len(temp)
                self.Table[i][r] = sym

    #Encryption function that iterates through both the message and the keyword
        #and grabs values from Table based on the ordinal value of the current
        #character being pointed to be the iterator
    def encrypt(self):
        for i in range(len(self.message)):
            mi = i
            ki = i % len(self.keyWord)
            self.ciphertext = self.ciphertext + self.eRetrieve(ki,mi)

    def eRetrieve(self,ki,mi):
        row = ord(self.message[mi]) - 32
        col = ord(self.keyWord[ki]) - 32
        return self.Table[row][col]

    #Decryption function that iterates through both the message and the keyword
        #and grabs values from Table based on the ordinal value of the current
        #keyWord character being pointed to be the iterator, then traversing the
        #row that corresponds to that value. While traversing that row, once there
        #is a match of the message value being searched for, take the iterator value
        #and convert it to an ascii character. This is the decrypted character
    def decrypt(self):
        self.ciphertext = ""
        for i in range(len(self.message)):
            emi = i
            ki = i % len(self.keyWord)
            self.ciphertext = self.ciphertext + self.dRetrieve(ki,emi)

    def dRetrieve(self,ki,emi):
        n = len(self.symbols)
        whichRow = ord(self.keyWord[ki]) - 32
        for i in range(n):
            if self.Table[i][whichRow] == self.message[emi]:
                decryptChar = chr(i + 32)
                return(decryptChar)

rawDescription: Randomized Vigenere Cipher with Python

description: Randomized Vigenere Cipher with Python


code: data_tupled_list = [(x[0],x[1]+x[2]) for x in zip(*data_list)]

rawDescription: How to concatenate two items from different lists using python?

description: Concatenate two items from different lists using python


code: data = np.genfromtxt('file.csv', skip_header=True)

rawDescription: Using prepared data for Sci-kit classification


rawDescription: Accessing nested JSON elements in Python


rawDescription: Append to Python list all possible transformations for each list item


code:
listbox.bind("<Return>", insert_word(t_start,listbox.get(ACTIVE)))
#                        ^----this function call is evaluated---^

rawDescription: Function called by the control flow, not by tkinter bind


code:
x= 1
y=1
total = 0
while x <= 4000000:
    if x % 2 == 0:
        total += x
    x, y = y, x + y
print (total)

rawDescription: Using Fibonacci Program to Sum Even Elements


code: {k: v for v, k in enumerate(RANKS)}

rawDescription: Sort Python list by dict key,value

description: Sort Python list by dict key,value


rawDescription: How to check for words in a list and then return a count?

description: Check for words in a list and then return a count


code:
def foo():
    bar = 6

bar

rawDescription: python:Merging button yields "not defined"

description: Python:Merging button yields "not defined"


code: print(df)

rawDescription: Format pandas integers for display

description: Format pandas integers for display


code:
import csv

with open(inputfilename, 'r') as infile, open(outputcsv, 'wb') as outfile:
    writer = csv.writer(outfile)

    for line in infile:
        row = line.split()
        inverted_nums = [-float(val) for val in row[-3:]]
        writer.writerow(row[:-3] + inverted_nums)

rawDescription: Change values in CSV or text style file

description: Change values in CSV or text style file


code: x.loc[index1, 3] = x.loc[index2, 2].values + 2

rawDescription: Editing values in a pandas dataframe using data from another part of the dataframe


code: sum(a in b for a in ListA for b in ListB)

rawDescription: Given two lists of strings, find the total number of strings in the second list which contains any string in the first list as substring


code:
import matplotlib.pyplot as plt
plt.plot([1,2,3], [1,4,9], line='-')

rawDescription: matplotlib - Error passing line argument through **kwargs

description: Matplotlib - Error passing line argument through **kwargs


code:
def insert_data(self):
    """
    Insertion method.
    """
    self.treeview.insert('', 'end', text="Item_"+str(self.i), values=(self.dose_entry.get()+" mg", self.modified_entry.get()))
    # Increment counter
    self.i = self.i + 1

rawDescription: tkinter Treeview widget inserting data

description: Tkinter Treeview widget inserting data


rawDescription: Python Numpy Matrix - Return the value contained in the matrix?


code:
print(etree.tostring(root, encoding='utf8'))
print(etree.tostring(root, encoding='utf8').decode('utf8'))

rawDescription: What is right way to use cyrillic in python lxml library


code:
import json

json_data = json.dumps(data)

rawDescription: How to convert sqlite3 data to Json format and CSV format

description: Convert sqlite3 data to Json format and CSV format


rawDescription: Creating a 2-dimensional Numpy array with the euclidean distance from the center


rawDescription: Python: Format output string, right alignment


code:
class Photo(models.Model):
    ...
    watermarked_photo = ImageField()

rawDescription: Saving Image in a temporary file in django


rawDescription: How to extract an element's content in HTML?

description: Extract an element's content in HTML


rawDescription: Why does numpy indexing work differently in higher dimensions?


code:
class Thing(object):
    def __init__(self):
        self.legs = 4
    def length(self):
        return 6

rawDescription: use one function to getattr for either functions or regular attributes

description: Use one function to getattr for either functions or regular attributes


code:
dec = Number.objects.get(id=1).decimal
dec = float(dec)

rawDescription: Django modelfield, how do I get the actual value?


code:
from django.forms.models import ModelMultipleChoiceField

class ProductModelChoiceField(ModelMultipleChoiceField):

    def label_from_instance(self, obj):
        return u"%s | %s" % (obj.name, obj.cost)

rawDescription: How to create form which will show fields from two models?

description: Create form which will show fields from two models


rawDescription: Filtering a DataFrame based on multiple column criteria


code:
width = 8
("{0:<%d}"%width).format(s)

rawDescription: use variable to specify format in python

description: Use variable to specify format in python


rawDescription: Horizontal analysis by generating list using while-loop


code:
def sp_it(num):
    try:
        num = float(num)
    except ValueError:
        return ""
    if num not in range(0,11):
        return "Error!"
    else:
        return str(((num-5)*9)/5.0+21)

def it_sp(num):
    try:
        num = float(num)
    except ValueError:
        return ""
    if num not in range(0,31):
        return "Error!"
    else:
        return str(((num-21)*5)/9.0+5)

def set_callback(target, modifier, object, text):
    target.text = modifier(text)

def add_callback(inst, focus, target=None, modifier=None):
    if focus:
        inst.fbind('text', set_callback, target, modifier)
    else:
        inst.funbind('text', set_callback, target, modifier)

class GradeApp(App):
    def build(self):
        b = BoxLayout(orientation='vertical')
        f = FloatLayout()
        t1 = TextInput(input_filter='float')
        t2 = TextInput(input_filter='float')
        l1 = Label(text='Welcome to Grader!')
        l2 = Label(text='Spanish Grade')
        l3 = Label(text='Italian Grade')
        b.add_widget(l1)
        b.add_widget(l2)
        b.add_widget(t1)
        b.add_widget(l3)
        b.add_widget(t2)
        t1.fbind('focus', add_callback, target=t2, modifier=sp_it)
        t2.fbind('focus', add_callback, target=t1, modifier=it_sp)
        return b

rawDescription: Bind two TexInput in Kivy through a function


code:
def format_duration(seconds):
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)

rawDescription: Minutes and seconds as a variable in Python


code:
import numpy as np
def python_sphj(n, x):
    sphj = special.specfun.sphj
    res = np.array([sphj(n, v)[1][n] for v in x])
    return res

rawDescription: Vectorized spherical bessel functions in python?


rawDescription: Applying math.ceil to an array in python


code:
def cap_sentence(y):
    caps = "on"

    def func(x):
        nonlocal caps
        if caps == "on":
            caps = "off"
            return x.capitalize()
        elif "." in x:
            caps = "on"

    return tuple(map(func, y))

rawDescription: Changing the local variable of a function from within another function that is defined in said function.. Python


code: 'Hey there how are you'

rawDescription: removing duplicates in python and selenium

description: Removing duplicates in python and selenium


rawDescription: How to store lists over criteria in Python?

description: Store lists over criteria in Python


rawDescription: How to print a list of tuples

description: Print a list of tuples


code:
process = subprocess.call([
    "perl", "-i", "-pe",
    "s/(?<=password=)\w+/\\1mynewordtesting/", var])

rawDescription: Perl Regex issue via Python Script

description: Perl Regex issue via Python Script


code:
done, pending = await asyncio.wait(
    [self.process.protocol.queue.get(), self.process.killed],
    return_when=asyncio.FIRST_COMPLETED)

rawDescription: Cancel asynchronous iterator by timeout

description: Cancel asynchronous iterator by timeout


rawDescription: Optimisation of a simple vector operation (python)


rawDescription: Reshaping pandas dataframe, converting values of an existing column into new lower level columns with index ignored


code:
def is_palindrome(my_str):
    letters = [c.casefold() for c in my_str if c.isalpha()]
    return letters == letters[::-1]

is_palindrome("Rats live on no evil star")
is_palindrome("Hello World!")
is_palindrome("Madam, I'm Adam")

rawDescription: Can I make a code in python that ignores special characters such as commas, spaces, exclamation points, etc?

description: Make a code in python that ignores special characters such as commas, spaces, exclamation points, etc


code:
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
    if prefix is None:
        prefix = plat_specific and EXEC_PREFIX or PREFIX

    libpython = os.path.join(prefix,
                             "lib", "python" + get_python_version())
    if standard_lib:
        return libpython
    else:
        return os.path.join(libpython, "site-packages")

rawDescription: A way to get the path to the user installed packages on Linux and OS X operating systems? (Usable for Python versions between 2.5 - 2.7)


code:
edges = cv2.Canny(img2, 70, 50)
cv2.imwrite('edges.png', edges)

rawDescription: How to find the shape of an object in an image using python

description: Find the shape of an object in an image using python


code:
def _center(self, list_of_arrays, centering_factor, normalization_scheme):
    """
    Centering scheme for arrays
    """
    list_of_arrays -= centering_factor
    return normalization_scheme(normalize(list_of_arrays))

rawDescription: Numpy normalization code is strangely slow


code:
b = B('so')
b._A__name = 'something'
b._B__name = 'something else'

rawDescription: Subclass variables with the same name of superclass ones


code:
df['status'] = pd.cut(df['Days Late'], bins=[-1, 14, 35, 56, 365], labels=False)
labels = np.array('White Yellow Amber Red'.split())
df['status'] = labels[df['status']]
del df['Days Late']
print(df)
#        ID  quantity  status
# 0  STRSUB        56     Red
# 1  BOTDWG        20     Red
# 2  STRSUB        60   Amber
# 3  BOTDWG        67   Amber
# 4  STRSUB        74  Yellow
# 5  BOTDWG        87  Yellow
# 6  STRSUB        40   White
# 7  BOTDWG        34   White

rawDescription: Grouping data by value ranges

description: Grouping data by value ranges


code: P = solve_discrete_lyapunov(M.T, I)

rawDescription: Am I using scipy.linalg.solve_discrete_lyapunov correctly


code: ' '.join(['test', 'report'])

rawDescription: Format an array as string in Python

description: Format an array as string in Python


rawDescription: Writing multiple Python dictionaries to csv file


code:
class ReqMock:
    def __init__(self, ajax=False):
        self.ajax = ajax
    def is_ajax(self):
        return self.ajax

score_handler(ReqMock(True))
score_handler(ReqMock(False))

rawDescription: Python separating Ajax requests from normal page views


code: foo.multiply(1, 2)

rawDescription: Can a function in python behave like a class?


code: #!/usr/bin/python

rawDescription: How to execute python file in linux

description: Execute python file in linux


code:
functions = [x for x in globals().values()
             if hasattr(x, '__call__') and
                hasattr(x, "__code__") and
                x.__code__.co_argcount == 0]

for func in functions:
    try:
        var, msg = func()
    except (ValueError, TypeError):
        continue

    if not isinstance(var, bool) or not isinstance(msg, str):
        continue

    if not var:
        break

rawDescription: Exiting block of code when variable changes in python


code:
X = IndexedBase("X")
W = IndexedBase("W")
var("i,j,M,K", integer=True)

rawDescription: python symbolic summation and differentiation of a vector of parametric size

description: Python symbolic summation and differentiation of a vector of parametric size


code:
def main(x, **kwargs):
    f1(x, **kwargs_for_func(f1, kwargs, True))
    f2(x, **kwargs_for_func(f2, kwargs, True))

main(1, key1=None)

rawDescription: Pass keyword argument to another function where the keyword has a default value


code:
def iterate(func, d):
    for f in listDir(d):
        if f.isDir:
            yield from iterate(func, d + f.name)
        else:
            yield func(f)

rawDescription: Python: lazy iterating through directory-like structure


code:
import sqlite3
conn = sqlite3.connect('path/to/lookup.db')

c.execute("SELECT key FROM lookup WHERE id = '%s'" % from_id)
s1 = {x[0] for x in c.fetchall()}
c.execute("SELECT key FROM lookup WHERE id = '%s'" % to_id)
s2 = {x[0] for x in c.fetchall()}
common_items = s1.intersection(s2)

rawDescription: Using Large Lookup Table in Single MultiCore Machine with PySpark


code:
g = df.groupby("A").apply(lambda x: pd.concat((x["B"], x["C"])))
k = g.reset_index()
k["i"] = k1.index
k["rn"] = k1.groupby("A")["i"].rank()
k.pivot_table(rows="A", cols="rn", values=0)

# output
# rn   1   2   3   4   5   6
# A
# 1   10  12  11  22  20   8
# 2   10  11  10  13 NaN NaN
# 3   14  10 NaN NaN NaN NaN

rawDescription: Can pandas groupby aggregate into a list, rather than sum, mean, etc?


code:
wordorder = dict(zip(list2, range(len(list2))))
wordorder
sorted(list1, key=lambda x: wordorder.get(x.split('-')[1], len(wordorder)))

rawDescription: Python: How to order a list based on another list


code:
a = (not (letter.lower() in word) or not(letter.lower() in guessed_letters))
b = letter != ' '
result = a and b

rawDescription: if statement syntax - different than taught

description: If statement syntax - different than taught


code:
x = np.random.random(1000)
y = np.random.random(1000)
nx, ny = 7, 7
H, _, _ = np.histogram2d(x, y, bins=(nx,ny), normed=True)
pylab.imshow(H, interpolation='nearest')
pylab.colorbar()
pylab.show()

rawDescription: Python: XY density plot

description: Python: XY density plot


code:
def solve_grid(self, grid, row=0, col=0):
    row, col = self.find_next(grid, row, col)
    if row == -1:
        result = True
    else:
        result = False
        for num in range(1,10):
            if self.isValid(grid, row, col, num):
                grid[row][col] = num

                if self.solve_grid(grid, row, col):
                    result=True
                    break

                grid[row][col] = 0

    return result

rawDescription: splitting multiple return statements into different functions

description: Splitting multiple return statements into different functions


code:
for i, element in enumerate(lista):
    lista[i] = int(element)

rawDescription: Modifing element in array using for and in


rawDescription: How to generate ODIN-1 in Python

description: Generate ODIN-1 in Python


code:
transformed_dfs = [df.select(*[
  lit(None).cast(c.dataType).alias(c.name) if c.name not in df.columns
  else col(c.name)
  for c in output_schema.fields
]) for df in dfs]

rawDescription: What's the most efficient way to accumulate dataframes in pyspark?


code: pairs = {(x, x+2) for x in primes if x+2 in primes}

rawDescription: Python Set Comprehension

description: Python Set Comprehension


code:
def CompareDimensions(self):
    dims = [list(instance.GetDimensions()) for instance in self.house_list]
    dims = numpy.array(dims)
    # .... futher processing on matrix

rawDescription: Interaction of objects in object-oriented programming


rawDescription: Reshape for array multiplication/division in python


rawDescription: How can I make sure that numbers in 17 variables are different?

description: Make sure that numbers in 17 variables are different


code: (a1[:,numpy.newaxis] == a2).all(axis=2)

rawDescription: How to make this kind of equality array fast (in numpy)?

description: Make this kind of equality array fast (in numpy)


code:
if self.player.side == side:
    self.enemy.score += 1
else:
    self.player.score += 1

rawDescription: What are some interesting alternatives to line-by-line if/else statements?


rawDescription: why \* escapes even when it is a raw string?

description: Why \* escapes even when it is a raw string


code:
from scipy.misc import lena

bin_edges = 0, 55, 200, 255
quantiles = 0, 0.2, 0.5, 1.0
img = lena()
normed = hist_norm(img, bin_edges, quantiles)

rawDescription: How can I transform the histograms of grayscale images to enforce a particular ratio of highlights/midtones/shadows?

description: Transform the histograms of grayscale images to enforce a particular ratio of highlights/midtones/shadows


code:
while True:
    ...
    next_bad_apple -= 1
    if not next_bad_apple:
        pos = getRandomLocation()

        # if there's already a bad apple on this position
        # create a new position
        while pos in bad_apples:
            pos = getRandomLocation()

        bad_apples.append(pos)
        next_bad_apple = get_bad_apple_time()

rawDescription: PyGame wormy - threads with bad apples

description: PyGame wormy - threads with bad apples


code:
import numpy as np

# Mask of non-zeros elements in the output array
mask = ~np.sort(x==0,2)

# Setup output array and put non zero input elements into it
out = np.zeros_like(x)
out[mask] = x[x!=0]

rawDescription: Relocate zeros to the end of the last dimension in multidimensional numpy array


code:
urls.py
url(r'^portal/$', 'portal.views.portal', name='home'),
url(r'^portal/index.html$', 'portal.views.portal', name='home_index'),

rawDescription: Django HttpResponseRedirect vs render_to_response - how to get a login form to behave the way I need it to


code:
doc = self._testMethodDoc
return doc and doc.split("\n")[0].strip() or None

rawDescription: Python unittest, how to display TestCase's methods' docstring in report?


code:
self.line_count = 0
while True:
    line = self.process1.stderr.readline().decode('utf-8')
    wx.CallAfter(self.appendAndTrim, line)

rawDescription: wx.TextCtrl GetLineLength wx.CallAfter not working

description: Wx.TextCtrl GetLineLength wx.CallAfter not working


rawDescription: Running through a list of tuples

description: Running through a list of tuples


code: [[[0]*20 for i in range(10)] for j in range(5)]

rawDescription: Python using higher order functions

description: Python using higher order functions


code:
g = df.groupby(df.index)
g.apply(func)

rawDescription: Python pandas idxmax for multiple indexes in a dataframe


code:
from my.project import myapp_domain as _

# ....

message = _('temp-test', default='Temporary test')

rawDescription: Pyramid TranslationString not working on json renderer


code:
import operator
for i in range(len(L)):
    L[i] = sorted(L[i], key=operator.itemgetter(1, 2))

rawDescription: Sorting a complex structure of array of array


rawDescription: Slicing and if statements (Python)

description: Slicing and if statements (Python)


code:
import numpy as np
from PIL import Image

filePath = '/home/george/Desktop/img.jpg'

Img = Image.open(filePath)
img = np.asarray(Img, np.int)
shp = np.shape(img)
img = img.transpose(2,0,1).reshape(3,215,215)

leftPad = round(float((255 - shp[0])) / 2)
rightPad = round(float(255 - shp[0]) - leftPad)
topPad = round(float((255 - shp[1])) / 2)
bottomPad = round(float(255 - shp[1]) - topPad)
pads = ((leftPad,rightPad),(topPad,bottomPad))

img_arr = np.ndarray((3,255,255),np.int)
for i,x in enumerate(img):
    cons = np.int(np.median(x))
    x_p = np.pad(x,pads,
                'constant',
                 constant_values=cons)
    img_arr[i,:,:] = x_p

im_shp = np.shape(img_arr)
ii = np.uint8(img_arr).transpose(1,2,0)

im = Image.fromarray(np.array( (ii) ))
im.show()
im.save((filePath), "JPEG")

rawDescription: How can I efficently pad an RGB numpy array with the median of the image?

description: Efficently pad an RGB numpy array with the median of the image


code: transposed_grid = list(zip(*my_grid))

rawDescription: Appending a list to make a 4x4 matrix cipher


code:
#connections.py
class Connection:
    def __init__(self, server):
        self.server = server

def connect(server):
    connection = Connection(server) #create a new connection object with the server passed to the method

rawDescription: Pass command line variables between Python files. Totally stuck


code:
obj.__class__ = ClassA
obj.Test()
# hoho

rawDescription: How to update the the class type and methods in an existing object

description: Update the the class type and methods in an existing object


code: {'video': [{'title': title, 'id': id} for title, id in zip(titles, ids)]}

rawDescription: How do I make a JSON file out of a list in Python?

description: Make a JSON file out of a list in Python


code:
def expand_singles(item):
    if isinstance(item, list):
        if len(item) == 1:
            return expand_singles(item[0])
        return [expand_singles(i) for i in item]
    return item

l = [1, 2, 3, ['a', [[9, 10, 11]], 'c', 'd'], 5, ['e', 'f', [6, 7, [8]]]]
expand_singles(l)

rawDescription: Clean nested lists in Python

description: Clean nested lists in Python


code:
class A(object):
    foo = {}

rawDescription: Python - inbound outbound argument

description: Python - inbound outbound argument


rawDescription: determine mean zero crossing

description: Determine mean zero crossing


code:
import tkinter as tk

class MainApp(tk.Frame):

    def __init__(self, parent):

        tk.Frame.__init__(self, parent, bg="blue")
        self.parent = parent

        button = tk.Button(self, text="a button")
        button.pack()

root = tk.Tk()
root.geometry("200x200+300+300")
root.config(background="yellow")
app = MainApp(root)
app.pack(fill="both", expand=True)
root.mainloop()

rawDescription: Creating Frames in tkinter

description: Creating Frames in tkinter


code:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder

tiles = 5

Builder.load_string("""
#: import tiles __main__.tiles

<MyWidget>:
    cols: tiles
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
""")

class MyWidget(GridLayout):
    pass

class MyApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()

rawDescription: How to access a global var in Kivy file?

description: Access a global var in Kivy file


code: TaggedItem.object.get_by_model(MyModel, ['my tag with spaces'])

rawDescription: How to allow whitespaces in tag names using django-tagging-0.3.1?

description: Allow whitespaces in tag names using django-tagging-0.3.1


rawDescription: Polyval(p,x) to evaluate polynomials

description: Polyval(p,x) to evaluate polynomials


code:
import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
    print(file)

rawDescription: Find all files in directory with extension .txt in Python


code:
lst = [ 'foo-yes-bar', 'hello foo fine bar']
strings_to_match = ['foo', 'bar', 'hello']
[x for x in lst if all(s in x for s in strings_to_match)]

rawDescription: Find sublist of strings that match a regex that requires ordered inclusion from another list


rawDescription: Why does the order of dimensions change with boolean indexing?


code:
for i in range(5):  # range creates this: [0, 1, 2, 3, 4]
    print(i)

rawDescription: For Loop in Python 3.0

description: For Loop in Python 3.0


code:
M[:,1] = [[0], [0]]        # note the nested lists to reassign column
M
M[1,:] = [2, 2, 2]         # flat list to reassign row
M

rawDescription: How to multiply a given row `i` or column `j` with a scalar?

description: Multiply a given row `i` or column `j` with a scalar


code:
from sklearn.datasets import load_iris
from sklearn import tree
clf = tree.DecisionTreeClassifier()
iris = load_iris()
clf = clf.fit(iris.data, iris.target)
tree.export_graphviz(clf,
    out_file='tree.dot')

rawDescription: Is it possible to print the decision tree in scikit-learn?


code: a = np.frombuffer(Data) # no copy. Changes in `a` are reflected in `Data`

rawDescription: How to convert pointer to c array to python array

description: Convert pointer to c array to python array


code:
largest = max(nx.weakly_connected_component_subgraphs(G),key=len)
largest.nodes()
largest.edges()

rawDescription: Largest weakly connected component in networkX


code:
def func(arg, *args, kwonly, **kwargs):
    print('arg:', arg)
    print('args:', args)
    print('kwonly:', kwonly)
    print('kwargs:', kwargs)
func(1, 2, kwonly=3, kw=4)
func(1, 2, 3, kw=4)  # Should have written: 'kwonly=3'

rawDescription: Python inspect module: keyword only args


code:
profile_experience = soup.find(id="profile-experience")

for li in profile_experience.find_all("li", class_="position"):
    print(li.get_text())

rawDescription: Navigating DOM in BeautifulSoup

description: Navigating DOM in BeautifulSoup


code:
import re
re.compile('jpg|png|gif').search('testpng.txt')
re.compile('jpg|png|gif').search('testpg.txt')

rawDescription: Check to ensure a string does not contain multiple values


code:
from robot.libraries.BuiltIn import BuiltIn

class Selenium2LibraryExt(object):

    @property
    def _s2l(self):
        return BuiltIn().get_library_instance('Selenium2Library')

    @property
    def _driver(self):
        return self._s2l._current_browser()

    def perform_search(self, criteria):
        textbox = self._driver.find_element_by_name('q')
        textbox.send_keys(criteria)
        textbox.submit()

rawDescription: how to instantiate the webdriver object from the custom library when doing web automation using robot framework

description: Instantiate the webdriver object from the custom library when doing web automation using robot framework


rawDescription: lxml: Append 'None' or Null value when html tag text content is None

description: Lxml: Append 'None' or Null value when html tag text content is None


code:
def fibonacci(n):
    return n if n < 2 else fibonacci(n-1) + fibonacci(n-2)

rawDescription: python syntax: how to return 0 instead of False when evaluating 0

description: Python syntax: how to return 0 instead of False when evaluating 0


code:
from math import sin, cos, sqrt, atan2, radians

def distance(coord1, coord2): #Haversin
    lat1,lon1=coord1
    lat2,lon2=coord2
    dlat = radians(lat2-lat1)
    dlon = radians(lon2-lon1)
    a = sin(dlat/2) * sin(dlat/2)
    + cos(radians(lat1))*cos(radians(lat2))*sin(dlon/2)*sin(dlon/2)
    c = 2 *atan2(sqrt(a),sqrt(1-a))
    s = (6367*c)*1000 #meter
    return s

def get_coordinates(data):
    # Importing only coordinates from asko input file (Row 2 and 4)
    # Converting the coordinates from DDMM.MMMM to DD.DDDDDD

    LAT = (data[2])
    LAT_D = LAT[0:2]
    LATID = float(LAT_D)

    LAT_M = LAT[2:]
    LATM = float(LAT_M)
    LATIM = float(LATM) / 60.0

    latitude = (LATID + LATIM)

    LON = (data[4])
    LON_D = LON[1:3]
    LONGD = float(LON_D)

    LON_M = LON[3:]
    LONM = float(LON_M)
    LONGM = float(LONM) / 60.0

    longitude = (LONGD + LONGM)

    return (latitude, longitude)

coord1 = None

# with open as data will close itself after reading each line. so you don't need to close it yourself

with open('asko_nav_2013.nmea', 'r') as indata, open('asko_nav_out.txt', 'w') as outdata:
    for line in indata:
        if line.startswith('EOL'):  #if the line starts with EOL(end of line) it writes it in the output
            if dist < 100:
                outdata.write('%0.6f\t%0.6f\t%f\n' % (latitude, longitude, dist))
            outdata.write("\nEOL\n")
            coord1 = None   # Reset the first coordinate
        elif line.startswith('Line'):
            outdata.write('\n%s' % line)
        elif line.startswith('$GPGGA'):  #when the fist line starts with $GPGGA it splits the columns
            data=line.split(",")        #the for loop reads the file line by line
            latitude, longitude = get_coordinates(data)

            if coord1:
                coord2 = (latitude, longitude)
                dist = distance(coord1, coord2)

                if dist >= 100:
                    outdata.write('%0.6f\t%0.6f\t%f\n' % (latitude, longitude, dist))
                    coord1 = coord2
            else:
                # The first time through the loop "coord1" is None
                outdata.write('%0.6f\t%0.6f\t0.0 \n' % (latitude, longitude))
                coord1 = (latitude, longitude)

rawDescription: GPS downsampling

description: GPS downsampling


code:
from datetime import datetime, timedelta
from pony.orm import *

db = Database('sqlite', ':memory:')

class User(db.Entity):
    username = Required(str, unique=True)
    password = Required(str)
    friends = Set("User", reverse='friends')  # many-to-many symmetric relation
    online = Required(bool, default=False)    # if user is currently online
    last_visit = Optional(datetime)           # last visit time
    disabled = Required(bool, default=False)  # if user is disabled by administrator

sql_debug(True)
db.generate_mapping(create_tables=True)

rawDescription: Writing select functions for customized Pony


code:
from PyQt5 import QtCore, QtWebSockets, QtNetwork, QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QAction
from PyQt5.QtCore import QUrl

class MyServer(QtCore.QObject):
    def __init__(self, parent):
        super(QtCore.QObject, self).__init__(parent)
        self.clients = []
        print("server name: {}".format(parent.serverName()))
        self.server = QtWebSockets.QWebSocketServer(parent.serverName(), parent.secureMode(), parent)
        if self.server.listen(QtNetwork.QHostAddress.LocalHost, 1302):
            print('Listening: {}:{}:{}'.format(
                self.server.serverName(), self.server.serverAddress().toString(),
                str(self.server.serverPort())))
        else:
            print('error')
        self.server.acceptError.connect(self.onAcceptError)
        self.server.newConnection.connect(self.onNewConnection)
        self.clientConnection = None
        print(self.server.isListening())

    def onAcceptError(accept_error):
        print("Accept Error: {}".format(accept_error))

    def onNewConnection(self):
        print("onNewConnection")
        self.clientConnection = self.server.nextPendingConnection()
        self.clientConnection.textMessageReceived.connect(self.processTextMessage)

        self.clientConnection.textFrameReceived.connect(self.processTextFrame)

        self.clientConnection.binaryMessageReceived.connect(self.processBinaryMessage)
        self.clientConnection.disconnected.connect(self.socketDisconnected)

        print("newClient")
        self.clients.append(self.clientConnection)

    def processTextFrame(self, frame, is_last_frame):
        print("in processTextFrame")
        print("\tFrame: {} ; is_last_frame: {}".format(frame, is_last_frame))

    def processTextMessage(self, message):
        print("processTextMessage - message: {}".format(message))
        if self.clientConnection:
            for client in self.clients:
                # if client!= self.clientConnection:
                client.sendTextMessage(message)
            # self.clientConnection.sendTextMessage(message)

    def processBinaryMessage(self, message):
        print("b:",message)
        if self.clientConnection:
            self.clientConnection.sendBinaryMessage(message)

    def socketDisconnected(self):
        print("socketDisconnected")
        if self.clientConnection:
            self.clients.remove(self.clientConnection)
            self.clientConnection.deleteLater()

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    serverObject = QtWebSockets.QWebSocketServer('My Socket', QtWebSockets.QWebSocketServer.NonSecureMode)
    server = MyServer(serverObject)
    serverObject.closed.connect(app.quit)
    app.exec_()

rawDescription: How to create a websocket client by using QWebSocket in PyQt5

description: Create a websocket client by using QWebSocket in PyQt5


code:
perms = itertools.permutations(girls)
len([tuple(p) for p in (itertools.product(boys, g) for g in perms)])
perms = itertools.permutations(girls)
len(set(tuple(p) for p in (itertools.product(boys, g) for g in perms)))

rawDescription: Pairing people in a contest

description: Pairing people in a contest


code:
from mpmath import quad
quad(lambda x: exp(-x**2), [-inf, inf])

rawDescription: How to perform infinite sum numerically in python

description: Perform infinite sum numerically in python


code:
# shift each channel by 10 pixels
R = img[:,:,0]
G = img[:,:,1]
B = img[:,:,2]
RGBshifted = np.dstack( (
    np.roll(R, 10, axis=0),
    np.roll(G, 10, axis=1),
    np.roll(B, -10, axis=0)
    ))
imshow(RGBshifted)

rawDescription: Random flipping and RGB jittering/slight value change of image?


code:
a = ("Hello SO!")
a = "Hello SO!"

rawDescription: Using print() in Python2.x

description: Using print() in Python2.x


code:
from Tkinter import *

root = Tk()
root.title('Model Definition')
root.geometry('{}x{}'.format(460, 350))

# create all of the main containers
top_frame = Frame(root, bg='cyan', width = 450, height=50, pady=3)
center = Frame(root, bg='gray2', width=50, height=40, padx=3, pady=3)
btm_frame = Frame(root, bg='white', width = 450, height = 45, pady=3)
btm_frame2 = Frame(root, bg='lavender', width = 450, height = 60, pady=3)

# layout all of the main containers
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(0, weight=1)

top_frame.grid(row=0, sticky="ew")
center.grid(row=1, sticky="nsew")
btm_frame.grid(row = 3, sticky="ew")
btm_frame2.grid(row = 4, sticky="ew")

# create the widgets for the top frame
model_label = Label(top_frame, text = 'Model Dimensions')
width_label = Label(top_frame, text = 'Width:')
length_label = Label(top_frame, text = 'Length:')
entry_W = Entry(top_frame, background="pink")
entry_L = Entry(top_frame, background="orange")

# layout the widgets in the top frame
model_label.grid(row = 0, columnspan = 3)
width_label.grid(row = 1, column = 0)
length_label.grid(row = 1, column = 2)
entry_W.grid(row = 1, column = 1)
entry_L.grid(row = 1, column = 3)

# create the center widgets
center.grid_rowconfigure(0, weight=1)
center.grid_columnconfigure(1, weight=1)

ctr_left = Frame(center, bg='blue', width=100, height=190)
ctr_mid = Frame(center, bg='yellow', width=250, height=190, padx=3, pady=3)
ctr_right = Frame(center, bg='green', width=100, height=190, padx=3, pady=3)

ctr_left.grid(row=0, column = 0, sticky="ns")
ctr_mid.grid(row=0, column = 1, sticky="nsew")
ctr_right.grid(row=0, column = 2, sticky="ns")

root.mainloop()

rawDescription: tkinter gui layout using frames and grid

description: Tkinter gui layout using frames and grid


code:
_, num_days = calendar.monthrange(2016, 3)
first_day = datetime.date(2016, 3, 1)
last_day = datetime.date(2016, 3, num_days)
first_day
last_day

rawDescription: how to get the first day and last day of current month in python

description: Get the first day and last day of current month in python


code: df.query("a in @keys")

rawDescription: Slice pandas DataFrame where column's value exists in another array


code:
def b():
  for i in range(100): yield
dis.dis(b)

rawDescription: Python: lambda function behavior with and without keyword arguments?


rawDescription: Regex to match space and a string until a forward slash


code:
def needs_privilege(privilege, project=None):
    """Check whether the logged-in user is authorised based on the
    given privilege

    @type privilege: Privilege object, id, or str
    @param privilege: The requested privilege"""

    def validate(func, self, *args, **kwargs):
        """Validator of needs_privillige"""
        try: check(self.user, privilege, project)
        except AccessDenied:
            return abort(status_code=401)
        else:
            return func(self, *args, **kwargs)
    validate.privelege = privelege
    return decorator(validate)

rawDescription: Getting local variables of function

description: Getting local variables of function


code:
def method_friendly_decorator(method_to_decorate):
     def wrapper(self, lie, offset=-3):
         lie += offset # very friendly, adjust age even more!
         return method_to_decorate(self, lie)
     return wrapper

rawDescription: Decorator and closures

description: Decorator and closures


rawDescription: SqlAlchemy and Flask, how to query many-to-many relationship


code: exclude = ['bar']  # less ambiguous

rawDescription: How can I prevent a field from displaying on a ModelForm?

description: Prevent a field from displaying on a ModelForm


code:
for smiley, placeholder in d.iteritems():
    s = s.replace(smiley, placeholder)

rawDescription: Split a string into a list, leaving accented chars and emoticons but removing punctuation


code:
from functools import partial
def foo(a, b):
    return a + b

f1 = partial(foo, 2)
f2 = partial(foo, 2)
f1.func is f2.func
f1.args
f2.args
f1.keywords is None
f2.keywords is None

rawDescription: How to test that functools.partial produces the expected function object

description: Test that functools.partial produces the expected function object


code:
strs='[24, 72, 95, 100, 59, 80, 87]\n'
from ast import literal_eval
literal_eval(strs)

rawDescription: How to turn a 'string list' into a real list?

description: Turn a 'string list' into a real list


rawDescription: change a list of dictionaries to feature vector and target in scikit

description: Change a list of dictionaries to feature vector and target in scikit


code:
for row in BOARD:
    ...
    ...
    for i, column in enumerate(row):
        ...
        row[i] = userInput
        ...

rawDescription: How to edit the elements of a 2d array and display the edited 2d array?

description: Edit the elements of a 2d array and display the edited 2d array


rawDescription: replacing layout on a QWidget with another layout

description: Replacing layout on a QWidget with another layout


code:
class _LogWriter:
    def flush(self):
        pass

    def write(self, s):
        sublime_api.log_message(s)

sys.stdout = _LogWriter()
sys.stderr = _LogWriter()

rawDescription: Progress bar in Sublime Text with Python


code: crc32(b'the quick brown fox')

rawDescription: Why does python's zlib.crc32 need a bitwise AND to be considered "stable"?


code:
person = Person(firstName='Peter', lastName='Smith', age=21)
print(person)

rawDescription: Automatically setting getter, setter and deleter in python


code:
from matplotlib import pyplot as plt
plt.ioff()

rawDescription: Matplotlib can't suppress figure window

description: Matplotlib can't suppress figure window


code:
s = 0
for comb in combinations(range(1,50), 6):
   s += len(repr(comb))+2

s

rawDescription: Python - all lottery combinations - no duplicates, in order


code:
anchor = soup.findAll(text=re.compile("Assi"))[0]
' '.join(anchor.find_next('td').stripped_strings)

rawDescription: Python BeautifulSoup how to get the index or of the HTML table


code:
def checkio(data):
    return len(data) >= 10 and any(char.isdigit() for char in data) and any(char.islower() for char in data) and any(char.isupper() for char in data)

rawDescription: python password rules validation

description: Python password rules validation


code: image = cv2.imread (myFile, 1)

rawDescription: Create Numpy array of images

description: Create Numpy array of images


code:
s = 'term:foo term:"foo bar" term:bar foo term:"foo term:'
re.findall(r'(?<=term:)[^" ]+|(?<=term:")[^"]+(?=")', s)

rawDescription: Python regular expression to match either a quoted or unquoted string


code:
def readAnalogData(SCLKPin, MOSIPin, MISOPin, CSPin):
    GPIO.output(CSPin,   HIGH)
    GPIO.output(CSPin,   LOW)

    adcvalue = 0
    for i in range(12):
        GPIO.output(SCLKPin, LOW) # reverse order of hi/lo here
        GPIO.output(SCLKPin, HIGH)
        adcvalue <<= 1
        if(GPIO.input(MISOPin)):
            adcvalue |= 0x01
    adcvalue >>= 3
    # adcvalue &= 0x3ff <- commented out this line as should be no longer necessary

    return adcvalue

rawDescription: Reading data out of an ADC (MCP3001) with python (SPI)


rawDescription: Setting the fmt option in numpy.savetxt

description: Setting the fmt option in numpy.savetxt


code:
#1 Current RAM consumption: 0.070 GB
#2 Current RAM consumption: 0.118 GB
#2 Peak RAM consumption: 0.118 GB

rawDescription: Split of numpy array into unequal chunks


code:
from pylab import *
x = arange(0, 10, 0.2)
y = sin(x)
plot(x, y)
show()

rawDescription: how to change the shape of a contour in matplotlib

description: Change the shape of a contour in matplotlib


code:
def get_total(self):
    if twitter_count == None and facebook_count == None:
        return 0
    elif twitter_count != None and facebook_count != None:
        return twitter_count + facebook_count
    elif twitter_count != None:
        return twitter_count
    else:
        return facebook_count
total_count = property(get_total)

rawDescription: Query database in Django for sum of two fields, sorting wrong


rawDescription: Python division

description: Python division


code:
class SendFeedback(webapp2.RequestHandler):
    def post(self):
        ...

rawDescription: How to get text from modal and insert in email body?

description: Get text from modal and insert in email body


code:
def eliminate_duplicates(lst):
    return list(set(lst))

def main():
    a=input("Enter numbers: ")
    lst = a.split()               # split automatically cleans up the whitespace
    print(eliminate_duplicates(lst))

if __name__ == "__main__":
    main()

rawDescription: Inquiry about removing duplicates

description: Inquiry about removing duplicates


code:
import numpy as np
a = np.zeros((6,6), dtype=np.int)
a[1,2] = a[1,3] = 1
a[4,4] = a[5,4] = a[4,3] = 1

from scipy import ndimage
kernel = ndimage.generate_binary_structure(2, 1)
kernel[1, 1] = 0

b = convolve(a, kernel, mode="constant")
b[a != 0].sum()

rawDescription: Calculate number of equal neighbouring cells within a numpy array


rawDescription: How can I remove the duplicates in a column of a 2D list and return the result as another list?

description: Remove the duplicates in a column of a 2D list and return the result as another list


rawDescription: Save image with matplotlib.pyplot

description: Save image with matplotlib.pyplot


code:
rd, wr = os.pipe()
oldstdout = os.dup(1)
os.dup2(wr, 1)
os.close(wr)

rawDescription: Capture output from subprocess.call that I have no control over


code:
x_all = np.ravel(x + np.zeros_like(y))
y_all = np.ravel(y)

rawDescription: How to obtain only one parameter set for a polynomial fit when several data sets are taken into account?

description: Obtain only one parameter set for a polynomial fit when several data sets are taken into account


code:
long_value = long(string_value.decode('hex'), 16)
# maybe someone knows a better way?

rawDescription: Trying to generate RSA signature with Python from working C# code


code:
class ListModelMixin(object):
    """
    List a queryset.
    """
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

rawDescription: Django Rest Framework: turn on pagination on a ViewSet (like ModelViewSet pagination)


code:
shame = Node("shame")

conscience = Node("conscience", shame)
selfdisgust = Node("selfdisgust", shame)
embarrassment = Node("embarrassment", shame)

selfconsciousness = Node("selfconsciousness", embarrassment)
shamefacedness = Node("shamefacedness", embarrassment)
chagrin = Node("chagrin", embarrassment)
discomfiture = Node("discomfiture", embarrassment)
abashment = Node("abashment", embarrassment)
confusion = Node("confusion", embarrassment)

print_tree(shame)

rawDescription: How to print a tree in Python?

description: Print a tree in Python


code:
from lxml import html

page = requests.get('http://chem.sis.nlm.nih.gov/chemidplus/name/'+ substance)
tree = html.fromstring(page.text.replace('<wbr>',''))
if ("Smiles" in page.text):
        smiles = tree.xpath('normalize-space(//*[text()="Smiles"]/..//br[1]/preceding-sibling::text()[1])')
else:
        smiles = ""

rawDescription: Removing <wbr> tags and grabbing the info between


rawDescription: Python: is index() buggy at all?

description: Python: is index() buggy at all


code:
sched.add_job(func=your_function(),
              trigger=DateTrigger(run_date=datetime.datetime.now()))

rawDescription: Can we force run the jobs in APScheduler job store?


code:
from ast import literal_eval
l = [u'[190215]']
l = [item for value in l for item in value]
l

rawDescription: Remove 'u' from a python list

description: Remove 'u' from a python list


code:
from django.db.models import get_model
user_model = get_model('auth', 'user')

rawDescription: Django - Get ContentType model by model name (Generic Relations)


code:
df = pd.read_csv(StringIO(data), index_col=0)
df

rawDescription: Python3 Pandas column in seconds

description: Python3 Pandas column in seconds


code:
from bottle import route, template, run

@route('/hello')
@route('/hello/<name>')
def hello(name='World'):
    return template('hello_template', name=name)

run(host='localhost', port=8080, debug=True)

rawDescription: Basics - HTML and Python Connection with bottle


code:
b, = ns.values()  # this will only work if only one name was defined
b()

rawDescription: Read python function from a text file and assign it to variable


code:
def typechecked(target):
    import inspect
    import functools

    @functools.wraps(target)
    def wrapper(*args, **kwargs):
        signature = inspect.signature(target)
        params = target(*args, **kwargs)

        for p, a in zip(params, signature.return_annotation):
            if not isinstance(p, a):
                raise TypeError('Incorrect return type: {} ({} required)'.format(type(p), a))
        return params

    return wrapper

rawDescription: How do I return multiple values using annotations?

description: Return multiple values using annotations


code: merged_dict = {reg_dict[k]: v for k, v in ord_dict.items()}

rawDescription: How to merge one ordered dict and one dict together?

description: Merge one ordered dict and one dict together


rawDescription: Passing variable length parameters to a function in python


code:
with open('output.txt', 'w') as f_output:
    f_output.write(''.join([template.format(r) for r in replace]))

rawDescription: How do i replace a single number (from a set of lines) from a list of numbers?

description: Replace a single number (from a set of lines) from a list of numbers


rawDescription: Plot special character as ① in matplotlib


rawDescription: Pandas: Combine TimeGrouper with another Groupby argument


code:
def create_proxymodel(model_from, name=None, attrs=None, meta=None):
    attrs, meta = (attrs if attrs else {}, meta if meta else {})

    class  Meta:
        proxy = True
        app_label = model_from._meta.app_label

    for k, v in meta.items():
        setattr(Meta, k, v)

    attrs.update({'__module__': '', 'Meta': Meta})
    newmodel = type(name, (model_from,), attrs)

    return newmodel

rawDescription: Best practice for data-entry in Django admin site (different ModelAdmin on the same model)


rawDescription: search the biggest number of one column in a list of list python

description: Search the biggest number of one column in a list of list python


code: data = map(myData._make, reader) # or [myData._make(r) for r in reader]

rawDescription: Import Data Into Namedtuple in Python

description: Import Data Into Namedtuple in Python


code:
entry.delete(0, 'end')
# print new serial data

rawDescription: print the data on window screen and then clear the window screen before printing other data.in python

description: Print the data on window screen and then clear the window screen before printing other data.in python


code:
class Foo(object):
    a = None

rawDescription: Automatically setting class member variables in Python


rawDescription: Elaborate on the following line

description: Elaborate on the following line


code: plot(x[boolind], y[boolind])

rawDescription: How to interpolate lines over nans in pylab?

description: Interpolate lines over nans in pylab


code:
for k in keys:
    print(k, names.get(k, ""))

rawDescription: Sort not identical lists Python

description: Sort not identical lists Python


code:
with open("example.csv") as of:
    for row in data:
        for cell in row:
             of.write(cell + ";")
        of.write("\n")

rawDescription: Creating publication quality tables in python


code: y = x2.reshape(2, -2)

rawDescription: Re-order a numpy array python

description: Re-order a numpy array python


rawDescription: Make a hashable id for all subclasses of base class


code: index = range(0,81)

rawDescription: Possible to compress into a dictionary comprehension?


code:
num = []
size = int(size)
for h in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[:size]:
    for b in range(1, size + 1):
        num.append(h + str(b))

rawDescription: Bombs Away Battleships

description: Bombs Away Battleships


code:
re.findall('[A-Z][^A-Z]*', s)
# ['Some', 'String', 'Like', 'This']

rawDescription: python: SomeStingLikeThis to some_string_like_this

description: Python: SomeStingLikeThis to some_string_like_this


rawDescription: finding the number of elements in a defaultdict(list) python

description: Finding the number of elements in a defaultdict(list) python


rawDescription: Python - adding string elements from a list into an array


code:
f = open("Vector.txt", 'r')

l1 = [s.strip('\n') for s in f]
l2 = [s for s in l1]

f.close()

for a in l1:
    for b in l2:
        result = 0
        if (a == b):
            result = 1
        else:
            counter = 0
            for i in range(len(a)):
                if (int(a[i]) == int(b[i]) == 1):
                    counter += 1
            result = counter / len(a)
        print(a, b, result)

rawDescription: compare lists in python

description: Compare lists in python


code: df

rawDescription: Pandas: Exponentially decaying sum with variable weights


rawDescription: How to know if a number is in another number python

description: Know if a number is in another number python


rawDescription: how to print lists within a tuple in straight line

description: Print lists within a tuple in straight line


code:
self.m_panel29 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 10,10 ), wx.TAB_TRAVERSAL )
self.m_panel29.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_INFOBK ) )
gbSizer1.Add( self.m_panel29, wx.GBPosition( 0, 6 ), wx.GBSpan( 1, 3 ), wx.EXPAND |wx.ALL, 5 )

rawDescription: How to understand wxGridBagSizer?

description: Understand wxGridBagSizer


code:
columns = col.values()[0].keys()
zip(columns, zip(*(v.values() for v in col.values())))

rawDescription: Is there a way to zip json into rows and columns in web2py?


code:
import unittest
import difflib

class _BaseTestCase(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(MyTestCase, self).__init__(*args, **kwargs)
        self.addTypeEqualityFunc(str, self.assertEqualWithDiff)

    def assertEqualWithDiff(self, left, right, msg=None):
        try:
            self._baseAssertEqual(left, right)
        except self.failureException:
            diff = difflib.unified_diff(
                left.splitlines(True),
                right.splitlines(True),
                n=0
            )
            diff = ''.join(diff)
            raise self.failureException("\n" + diff)

class MyTestCase(_BaseTestCase):
    def test_a(self):
        a = """hi
there
ok"""
        b = """bye
there
ok
whatever"""
        self.assertEqual(a,b)  # This will actually call assertEqualWithDiff

if __name__ == "__main__":
    unittest.main()

rawDescription: assertEqual only shows differences

description: AssertEqual only shows differences


rawDescription: How to print notification to slack by calling a function via python

description: Print notification to slack by calling a function via python


code:
def index(request):
    if request.is_ajax():
        #do something
        request_data = request.POST
        return HttpResponse("OK")

rawDescription: Javascript to Django views.py?

description: Javascript to Django views.py


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


rawDescription: i did not comprehend sum(iterable[, start]) in python

description: I did not comprehend sum(iterable[, start]) in python


code:
...
def run(self):
    __builtins__.__NUMPY_SETUP__ = False
    import numpy
    ...

rawDescription: Why doesn't setup_requires work properly for numpy?


rawDescription: Making a histogram of string values in python


code:
for fp1, fp2, lst1, lst2 in zip(lonwgs84 , latwgs84, col1s, col2s):
    datawriter.writerow([fp1, fp2] + lst1 + lst2)

rawDescription: splitting lists and values

description: Splitting lists and values


code:
#fourth.py
import first
import second
import third

rawDescription: Automatically import to all Python files in the given folder?


code:
def tinyfunction():
    pass

def manytinyfunction():
    pass

rawDescription: Python profiling - What are the columns in runsnakerun output?


code:
class Example(object):
    """class docstring"""

    def hello(self):
        """hello doctring"""
        pass

rawDescription: Embedded python interpreter, generate stub source code for autocompletion


code:
def find_dupe_rows(*arrays):

    A = np.vstack(arrays)
    rtype = np.dtype((np.void, A.dtype.itemsize*A.shape[1]))
    _, first_idx = np.unique(A.view(rtype), return_index=True)
    out = np.zeros(A.shape[0], np.bool)
    out[first_idx] = True

    return out.reshape(len(arrays), -1)

rawDescription: Detect the first unique rows in multiple numpy 2-d arrays


code:
grouped = df.groupby([d.strftime('%Y%m%d') for d in df['date']])
newdf = grouped.agg('first')
print(newdf)

rawDescription: Indexing pandas dataframe to return first data point from each day


rawDescription: Extracting all full words between in a certain amount of characters