code: df.groupby(pd.TimeGrouper('5Min'))['val'].apply(lambda x: len(x) > 3)

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

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


code:
df1  # similar to your example
df1["Histogram"].str.startswith("Band").cumsum()

rawDescription: Splitting dataframe and saving to txt files


code: contentType |= 8

rawDescription: Cleaning a multiple checkbox field into a bitwise operation output in django?


rawDescription: python - modify a list of strings via regex

description: Python - modify a list of strings via regex


code:
class ModelBase(object):
    def __init__(self):
        self.Serialiser.origin = self.origin

# ... then

cm  = ComponentModel()
ser = cm.Serialiser()

rawDescription: Accessing a parent variable from a nested child class in Python


rawDescription: Pythonic way to split math calculations

description: Pythonic way to split math calculations


code:
from operator import attrgetter
from itertools import groupby

color = attrgetter('color')
cats_by_color = {k: list(g) for k, g in groupby(sorted(cats, key=color), color)}

rawDescription: Create dictionary of lists by object feature


code:
import chardet
import codecs

falsely_decoded_str = "Ä×èÈÄÄî¦è¤ô_üiâAâjâüâpâXüj_10òb"

try:
    encoded_str = falsely_decoded_str.encode("cp850")
except UnicodeEncodeError:
    print("could not encode falsely decoded string")
    encoded_str = None

if encoded_str:
    detected_encoding = chardet.detect(encoded_str)["encoding"]

    try:
        correct_str = encoded_str.decode(detected_encoding)
    except UnicodeEncodeError:
        print("could not decode encoded_str as %s" % detected_encoding)

    with codecs.open("output.txt", "w", "utf-8-sig") as out:
        out.write(correct_str)

rawDescription: Unmunging munged unicode

description: Unmunging munged unicode


code:
import random

EASY = 'E'
HARD = 'H'
PRIORITY_CONSONANTS = 'tnrslhdcmpfgybwvkqxjz'
EASY_CONSONANTS = '' # what should be here?

def guess_letters(unguessed_consonants, difficulty_level):
    if difficulty_level == EASY:
        search_set = EASY_CONSONANTS
    elif difficulty_level == HARD:
        search_set = PRIORITY_CONSONANTS

    for con in unguessed_consonants:
        if con in search_set:
             return con

rawDescription: Hangman in Python - Consonant Guessing Coding


code:
#from file
r <- raster(system.file("external/test.grd", package="raster"))
logo <- raster(system.file("external/rlogo.grd", package="raster"), values=TRUE)
plot(logo)

rawDescription: Image analysis in R

description: Image analysis in R


rawDescription: SICP "streams as signals" in Python

description: SICP "streams as signals" in Python


rawDescription: Regexing an email from HTML

description: Regexing an email from HTML


rawDescription: Python - Extract folder path from file path


code:
def a(s):
    d = {}
    for i, c in enumerate(s):
        if not i % 4:
            a = []
            d['key%s' % ((i/4) + 1)] = a
        if not i % 2:
            b = []
            a.append(b)
        b.append(c)
    return d

rawDescription: Efficiently add values to bidimensional array


code:
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen

class MenuScreen(Screen):
    def switching_function(*args):
        global sm
        sm.current = 'Server'

    def __init__(self, **kwargs):

        super(MenuScreen, self).__init__(**kwargs)

#         def Server(instance):
#             self.clear_widgets()
#             self.add_widget(Label ( text = 'Inside server function'))
#             server = ServerScreen()
#             #return server
#             #server.function()

        self.add_widget(Label ( text = 'What Type Of Service You Want...???'))

        button1 = Button(text = 'Server',size_hint = (None,None),pos = (0,0))
        self.add_widget(button1)
#         button1.bind(on_press = Server)
        button1.bind(on_press = self.switching_function)

        button2 = Button(text = 'Client',size_hint = (None,None),pos = (100,0))
        self.add_widget(button2)
        #button2.bind(on_press = Client)

class ServerScreen(Screen):

    def __init__(self, **kwargs):
        super(ServerScreen, self).__init__(**kwargs)
        print('Inside server screen')

        self.clear_widgets()
        self.add_widget(Label (text = 'Working As A Server'))
        print("Hellooooooooooo")

sm = ScreenManager()
sm.add_widget(MenuScreen(name='Menu'))
sm.add_widget(ServerScreen(name='Server'))
#sm.add_widget(ClientScreen(name='Client'))

class FileApp(App):

    def build(self):

        #return Menu()

        return sm

rawDescription: How to move from one class to another in kivy

description: Move from one class to another in kivy


rawDescription: Python Regular Expressions Findall

description: Python Regular Expressions Findall


code:
import math
import numpy as np
x = [1.,2.,3.,4.,5.]
math.exp(x)
np.exp(x)

rawDescription: Python: What is the difference between math.exp and numpy.exp and why do numpy creators choose to introduce exp again


code:
'1|2'.split('|', 5)[-1]
# returns 2 - which isn't *after* the 5th

rawDescription: Find the sub-string after nth '|'

description: Find the sub-string after nth '|'


rawDescription: Can I generate a private key with pyOpenSSL with a passphrase

description: Generate a private key with pyOpenSSL with a passphrase


rawDescription: How to cross check a python list of dictionaries against a csr matrix

description: Cross check a python list of dictionaries against a csr matrix


code:
def thisView(request):
    response = render_to_response('webpage.mako', {}, request=request)
    someLogicOn(request.session['selectedClientId'])
    return response

rawDescription: Can you set session variables in MAKO files in Pyramid?

description: Set session variables in MAKO files in Pyramid


code:
a = object()
a.whoops = 1

rawDescription: Creating an empty object in Python

description: Creating an empty object in Python


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


code:
import Tkinter
w = Tkinter.Tk()
w.wm_state('iconic')

rawDescription: Minimizing a Tk Window

description: Minimizing a Tk Window


code:
np.random.seed(123456)
rng = pd.date_range('1/1/2011', periods=25, freq='1min')
ts = pd.Series(np.random.rand(len(rng)) > 0.85, index=rng)
ts

rawDescription: Downsize series containing boolean data with resample


code: sum(a * b for a, b in zip(list1, list2)) / sum(list1)

rawDescription: Pythonic way for calculating

description: Pythonic way for calculating


code:
s = u'\xea\xb1\xb8\xec\x8a\xa4\xeb\x8d\xb0\xec\x9d\xb4\xeb\xaf\xb8\xeb\x8b\x88\xec\x95\xa8\xeb\xb2\x94 3\xec\xa7\x91'
print(s.encode('latin1').decode('utf-8'))

rawDescription: what if a python unicode object has been decoded incorrectly

description: What if a python unicode object has been decoded incorrectly


rawDescription: Change embedded image type in APIC ID3 tag via Mutagen


code:
for ul in soup.findAll('p') :
    print(ul)

rawDescription: Parsing web page in python using Beautiful Soup


code:
def scale_dimensions(width, height, max_width):
    if width > max_width:
        ratio = max_width*1./width
        return (int(width*ratio), int(height*ratio))
    return (width, height)

rawDescription: Resizing uploaded images based on a maximum width in django (PIL)


code:
def bed_prepare(inp_bed):
    ''' Takes pandas dataframe bed file and identifies which regions overlap '''
    inp_bed['next_start'] = inp_bed['start'].shift(periods=-1)
    inp_bed['distance_to_next'] = inp_bed['next_start'] - inp_bed['stop']
    inp_bed['next_region_overlap'] = inp_bed['next_start'] <= inp_bed['stop']
    inp_bed['previous_stop'] = inp_bed['stop'].shift(periods=1)
    inp_bed['distance_from_previous'] = inp_bed['start'] - inp_bed['previous_stop']
    inp_bed['previous_region_overlap'] = inp_bed['previous_stop'] >= inp_bed['start']
    intermediate_bed = inp_bed
    return intermediate_bed

rawDescription: Comparing row values in pandas dataframe


rawDescription: How to sum elements of a list corresponding to elements of another list in python

description: Sum elements of a list corresponding to elements of another list in python


code:
def returnShape(*args):
    return np.broadcast(*args).shape

rawDescription: Numpy function to get shape of added arrays


code:
try:
    textPath = re.search('src="(.+?)"/>', i.text).group(1)
except AttributeError:
    textPath = '' # apply your error handling
print(textPath)

rawDescription: Parsing XML node and substring from value


code:
output = (lst[:3] # take the list before element 3
          + # and add
          lst[3:] # the list from element 3 on
          [::-1] # reversed
         )

rawDescription: Python reversing slice of a list

description: Python reversing slice of a list


code:
import re
sample = '''\
mapOptions = {
    zoom: 16,
    scrollwheel: false,
    center: new google.maps.LatLng(19.12345, -19.67890)
};
'''
map_lat_long = re.compile(r'google\.maps\.LatLng\(([\d.-]+),\s*([\d.-]+)\)')
map_lat_long.search(sample).groups()

rawDescription: Python extract text after keywords and brackets


code:
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")

rawDescription: Input html form data from python script

description: Input html form data from python script


code:
idx1.is_integer()
idx2.is_integer()

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

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


code:
import collections
Data = collections.namedtuple('Data','name location times')
data = Data('John','Los Angeles',[1,2,3,4])
data.name
data.location
data.times
data.times[0]

rawDescription: vectors in python structs

description: Vectors in python structs


code:
import pandas as pd
import glob

# if you don't use ['cand_id'] column - remove it from `usecols` parameter
dfy = pd.concat([pd.read_csv(f, sep='|', low_memory=False, header=None,
                             names=['cmte_id', '2', '3', '4','5', 'trans_typ', 'entity_typ', '8', '9', 'state', '11', 'employer', 'occupation', 'date', 'amount', 'fec_id', 'cand_id', '18', '19', '20', '21', '22'],
                             usecols= ['date', 'cmte_id', 'trans_typ', 'entity_typ', 'state', 'amount', 'fec_id', 'cand_id'],
                             dtype={'date': str})
                 for f in glob.glob('/home/jayaramdas/anaconda3/Thesis/FEC_data/itpas2_data/itpas2**.txt')
                ],
                ignore_index=True)

dfy['date'] = pd.to_datetime(dfy['date'], format='%m%d%Y')

# remove not needed column ASAP in order to save memory
del dfy['cand_id']

dfy = dfy[(dfy['date'].notnull()) & (dfy['date'] > '2007-01-01') & (dfy['date'] < '2014-12-31') ]

#df = dfy.set_index(['date'])

pvt = pd.pivot_table(dfy, index=['date','trans_typ','entity_typ','state','fec_id'],
                     columns='cmte_id', values='amount', aggfunc='sum', fill_value=0) \
        .reset_index()

print(pvt.info())

pvt.to_excel('out.xlsx', index=False)

rawDescription: Pandas: transposing one column in a multiple column df


code:
import numpy as np
rows = ['1','2','3']
cols = ['X','Y']

df = pd.DataFrame(np.char.add(*np.meshgrid(cols, rows, sparse=True, indexing='xy')),
                  index=rows, columns=cols)

rawDescription: create a Data frame as a function of row index value and column name?

description: Create a Data frame as a function of row index value and column name


code:
A
Aout

rawDescription: Shift matrix rows to have maxima in the middle


code:
for ind in range(len(t)):
  i = t[ind]
  ...

rawDescription: How to specify each index number - Python

description: Specify each index number - Python


code:
def f(): return 10000
f.__code__.co_consts

rawDescription: Understanding reference count of class variable


code:
def updatedValue(self, newValue):
    self.labelValue.setText(newValue)

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


code: last_name = soup.find('last_name') and soup.find('last_name').string

rawDescription: Parsing XML with BeautifulSoup and handling missing element


code:
filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            outfile.write(infile.read())

rawDescription: Python concatenate text files

description: Python concatenate text files


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


code: [doc for doc in pymongo.MongoClient().test.foo.find({'a': None}, {'_id': 0})]

rawDescription: What's the correct None or null entry for a datetime.datetime object in Python?


code:
from collections import Counter
count = Counter(x[3] for x in my_csv_reader)

rawDescription: Add new keys to a dictionary while incrementing existing values


code: [dict([('user', k)] + list(v.items())) for k, v in a['users'].items()]

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

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


code: modulename, _, classname = identifier.rpartition('.')

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


code: self.dataOlv = MyOvl(self, wx.ID_ANY, style=wx.LC_REPORT|wx.SUNKEN_BORDER)

rawDescription: Python create an event to an ObjectListView check box


code:
import urllib.request
data = urllib.request.urlopen(url) # url from previous section

rawDescription: Extracting data from a URL result with special formating


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


code:
@app.before_first_request
def load_global_data():
    global some_global_name
    some_global_name = load_data_from_pickle()

rawDescription: Flask: Creating objects that remain over multiple requests


code:
def profile(request):
    """Manage Account"""
    if request.user.is_anonymous() :
        # user isn't logged in
        messages.info(request, _(u'You are not logged in!'))
        return redirect('member-login')

    # get the currently logged in user's profile
    profile = request.user.profile

    # check to see if this request is a post
    if request.method == "POST":
        # Bind the post to the form w/ profile as initial
        form = ProfileForm(request.POST, instance=profile)
        if form.is_valid() :
            # if the form is valid
            form.save()
            messages.success(request, _(u'Success! You have updated your profile.'))
        else :
            # if the form is invalid
            messages.error(request, _(u'Error! Correct all errors in the form below and resubmit.'))
    else:
        # set the initial form values to the current user's profile's values
        form = ProfileForm(instance=profile)

    return render(
        request,
        'membership/manage/profile.html',
        {
            'form': form,
        }
    )

rawDescription: Populating Django Templates from retrieved records


code:
@decorator_that_makes_func_into_generator
def countdown(n):
    res = []
    while n > 0:
        res.append(n)
        n = n - 1
    return res

print(type(countdown(5)), list(countdown(5)))
# Output: <class 'generator'> [5, 4, 3, 2, 1]

rawDescription: Using decorator to turn function into generator in python


code:
import inspect
def serializable(func):
    def wrapper(self):
        pass
    wrapper.serialized = True
    return wrapper

class Book:
    @serializable
    def pretty_status(self):
        pass
    def foo(self):
        pass

for name, member in inspect.getmembers(Book, inspect.ismethod):
    if getattr(member, 'serialized', False):
        print(name, member)

rawDescription: Discover decorated class instance methods in python


code:
x1 = 5
x2 = 3
x3 = 6
x4 = 1
sorted([x1, x2, x3, x4], reverse=True)

rawDescription: Sorting Variables in Python?

description: Sorting Variables in Python


rawDescription: determine "type of value" from a string in python

description: Determine "type of value" from a string in python


rawDescription: python multiple inputs and multiple outputs

description: Python multiple inputs and multiple outputs


rawDescription: Adding calculated column(s) to a dataframe in pandas


code:
threshold = 24000
bars['Timestamp'] = bars[bars['Date']>threshold].loc[:, 'Date']
bars['Timestamp'] = bars['Timestamp'].fillna(method='ffill')
bars['Date'] = bars.apply(lambda x: x.Date + x.Timestamp if x.Date < threshold else x.Date, axis=1)
bars.drop('Timestamp', axis=1, inplace=True)

rawDescription: manipulating value of pandas dataframe cell based on value in previous row without iteration

description: Manipulating value of pandas dataframe cell based on value in previous row without iteration


code:
import zlib
l=[bin(i) for i in range(10)]
zlib.compress(str(l))

rawDescription: What char can be used to seperate binary data in a python 2.7 string?


code:
from itertools import combinations, starmap
all_intersections = starmap(set.intersection, combinations(all_sets, 2))

rawDescription: Intersection between all elements of same list where elements are set


rawDescription: Why increase a value in this way in python?


code:
from sys import argv

def operation(name, number, *args):
    print(name , number)

operation(*argv[1:])

rawDescription: passing arguments to functions in python using argv

description: Passing arguments to functions in python using argv


code: process(ClientScript, BP_ClientScript, conn, args)

rawDescription: Generic python module

description: Generic python module


code: self.getButton(0, 0).buttonMethod # note no parenthesis at end

rawDescription: Recognition source of event in PyQT

description: Recognition source of event in PyQT


code:
import numpy as np
from numpy.lib.stride_tricks import as_strided

def concatenated_ranges(ranges_list) :
    ranges_list = np.array(ranges_list, copy=False)
    base_range = np.arange(ranges_list.max())
    base_range =  as_strided(base_range,
                             shape=ranges_list.shape + base_range.shape,
                             strides=(0,) + base_range.strides)
    return base_range[base_range < ranges_list[:, None]]

rawDescription: repeat arange with numpy

description: Repeat arange with numpy


code:
if (var is 'stringone') or 'stringtwo':
    dosomething()

rawDescription: Python: How to check if a variable is equal to one string or another string


code:
def print_grades(file_name):
    # Call your create_grades_dict() function to create the dictionary
    grades_dict=create_grades_dict(file_name)
    print ("    ID     |       Name       | Test_1 | Test_2 | Test_3 | Test_4 |  Avg.  |")
    for key in sorted(grades_dict.keys()):
        print ("{0:<10} | {1:<16} | {2:>6} | {3:>6} | {4:>6} | {5:>6} | {6:>6.2f} |".format(key, grades_dict[key][0],  grades_dict[key][1],  grades_dict[key][2], grades_dict[key][3], grades_dict[key][4], grades_dict[key][5], ))

rawDescription: Getting a perfect output using .format()


code:
import itertools

def task(kw,text):
    i = itertools.cycle(kw)
    return tuple(next(i)+t if t.isalpha() else t for t in text)

print(task('lemon','hi there!'))

rawDescription: Create a list (of tuples?) from two lists of different sizes


code:
g = check.groupby('A')
bigList = []
for group in g:
    rowList = []
    for c in group[1].C.iteritems():
       rowList.append(c[1])
    bigList.append( rowList )

rawDescription: writing pandas dataframe columns to csv rows staggered

description: Writing pandas dataframe columns to csv rows staggered


code:
def like_cheese():
    var = input("Hi! I like cheese! Do you like cheese?").lower()  # Corrected the call to `.lower`.
    if var == "yes":
        print("That's awesome!")
while True:
    like_cheese()

rawDescription: How To Make a Python Program Automatically Restart Itself


rawDescription: Django how to update more than a row field at once


code:
import urllib2
import BeautifulSoup
import string

badwords = set([
    'cup','cups',
    'clove','cloves',
    'tsp','teaspoon','teaspoons',
    'tbsp','tablespoon','tablespoons',
    'minced'
])

def cleanIngred(s):
    # remove leading and trailing whitespace
    s = s.strip()
    # remove numbers and punctuation in the string
    s = s.strip(string.digits + string.punctuation)
    # remove unwanted words
    return ' '.join(word for word in s.split() if not word in badwords)

def main():
    url = "http://allrecipes.com/Recipe/Slow-Cooker-Pork-Chops-II/Detail.aspx"
    data = urllib2.urlopen(url).read()
    bs = BeautifulSoup.BeautifulSoup(data)

    ingreds = bs.find('div', {'class': 'ingredients'})
    ingreds = [cleanIngred(s.getText()) for s in ingreds.findAll('li')]

    fname = 'PorkRecipe.txt'
    with open(fname, 'w') as outf:
        outf.write('\n'.join(ingreds))

if __name__=="__main__":
    main()

rawDescription: Python HTML parsing with beautiful soup and filtering stop words


code:
import time

def myfast():
   code

n = 10000
t0 = time.time()
for i in range(n): myfast()
t1 = time.time()

total_n = t1-t0

rawDescription: How can I time a code segment for testing performance with Pythons timeit?

description: Time a code segment for testing performance with Pythons timeit


code:
def simplify_eq_with_assumptions(eq):
    assert eq.rhs == 0  # assert that right-hand side is zero
    assert type(eq.lhs) == Mul  # assert that left-hand side is a multipl.
    newargs = []  # define a list of new multiplication factors.
    for arg in eq.lhs.args:
        if arg.is_positive:
            continue  # arg is positive, let's skip it.
        newargs.append(arg)
    # rebuild the equality with the new arguments:
    return Eq(eq.lhs.func(*newargs), 0)

rawDescription: Python sympy - simplify nonzero factors from an equation


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

description: Generate random number with the specific length in python


code:
class MyLabel(Label):
    indice = StringProperty('0')
    _prefix = StringProperty('')
    _my_prefix = StringProperty(None)

    def get_prefix(self):
        if self._my_prefix is None:
            return self._prefix
        else:
            return self._my_prefix
    def set_prefix(self, value):
        self._my_prefix = value

    prefix = AliasProperty(get_prefix, set_prefix, bind=('_prefix', '_my_prefix'))

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


code:
import requests
from bs4 import BeautifulSoup
from urlparse import urljoin

url = 'http://bbs.skykiwi.com/forum.php?mod=forumdisplay&fid=55&typeid=470&sortid=231&filter=typeid&pageNum=1&page=1'

def getsourse(url):
    header = {'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows  NT 10.0; WOW64; Trident/8.0; Touch)'}
    html = requests.get(url, headers=header)
    return html.content

#To get all the links in current page
def getallLinksinPage(sourceCode):
    soup = BeautifulSoup(sourceCode)
    return [a["href"] for a in soup.select("#threadlist a.xst")]

sourceCode = getsourse(url) # source code of the url page
allLinksinPage = getallLinksinPage(sourceCode) #a List of the urls in current page
for eachLink in allLinksinPage:
    url = 'http://bbs.skykiwi.com/'
    html = getsourse(urljoin(url, eachLink))
    print(html)

rawDescription: How to get the right source code with Python from the URLs using my web crawler?

description: Get the right source code with Python from the URLs using my web crawler


code:
action = forms.ChoiceField(choices=choices,
                           widget=forms.Select(attrs={'onchange': 'actionform.submit();'}))

rawDescription: django submit form on change

description: Django submit form on change


code: list_ids = [line.strip() for line in open('list.txt').xreadlines()]

rawDescription: I'd'd like to take a list of strings, find them in another csv file and print a field from the matching line


code: a

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


rawDescription: How to precize that a pattern should start with a letter

description: Precize that a pattern should start with a letter


code:
from collections import defaultdict

d = defaultdict(list)
for child in root:
    d[child.tag].append(child.attrib)

rawDescription: How to keep adding values at end of dictionary

description: Keep adding values at end of dictionary


rawDescription: Loading Flask Models from Postgres

description: Loading Flask Models from Postgres


code:
struct.pack('>h', 257)
struct.unpack('>h', '\x01\x01')

rawDescription: int to binary python

description: Int to binary python


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

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


rawDescription: How to rapidly create array of N 3x3 matrices from 9 arrays of size N?

description: Rapidly create array of N 3x3 matrices from 9 arrays of size N


code:
# show every Nth label
locs, labels = plt.xticks()
N = 10
plt.xticks(locs[::N], test_df.index[::N].strftime('%Y-%m-%d'))

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


code:
a = np.array([100, 200, 250], dtype=np.uint8)
b = np.array([50, 50, 50], dtype=np.uint8)
c = 255 - b  # a temp uint8 array here
np.putmask(a, c < a, c)  # a temp bool array here
a += b

rawDescription: Avoid overflow when adding numpy arrays

description: Avoid overflow when adding numpy arrays


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

rawDescription: Execute coroutine from `call_soon` callback function


rawDescription: numpy element transformation with lambda?

description: Numpy element transformation with lambda


code:
import numpy as np

def runningMean(ar, m):

    return np.convolve(ar, np.ones((m,))/m)[(m-1):]

a = np.array([1, 3, 4, 5, 15, 14, 16, 13])
m = 2
av = runningMean(a, m)

d = a[m:] - av[:-m]

rawDescription: Function which is similar to numpy's diff


rawDescription: Assigning subvectors to multidimensional arrays in Numpy


rawDescription: django create object without affecting database

description: Django create object without affecting database


code:
identifier = Word(alphas, alphanums+'_') # not Regex(r'[a-zA-Z0-9_]+')
real = Regex(r'\d+(\.\d*)?([Ee][+-]?\d+)?')
oper = oneOf("* + - /")

rawDescription: Parser failing - pyparsing

description: Parser failing - pyparsing


code:
import sys
from PyQt4.QtGui import QApplication, QWidget, QTableWidget, QTableWidgetItem, QVBoxLayout
from PyQt4.QtCore import Qt

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.widget_layout = QVBoxLayout()
        self.table_widget = QTableWidget(101, 1)
        self.table_widget.setSortingEnabled(True)

        self.widget_layout.addWidget(self.table_widget)
        self.setLayout(self.widget_layout)

        for num in xrange(101):
            item = QTableWidgetItem()
            item.setData(Qt.EditRole, num)
            self.table_widget.setItem(num, 0, item)

if __name__ == '__main__':
  app = QApplication(sys.argv)
  widget = Widget()
  widget.show()
  sys.exit(app.exec_())

rawDescription: QTableWidget Integer

description: QTableWidget Integer


code:
def reverse(regex, dict):
    replacer_regex = re.compile('''
        \(\?P\<         # Match the opening
            (.+?)       # Match the group name into group 1
        \>\(.*?\)\)     # Match the rest
        '''
        , re.VERBOSE)

    return replacer_regex.sub(lambda m : dict[m.group(1)], regex)

rawDescription: How fill a regex string with parameters

description: How fill a regex string with parameters


code:
def visit_once_clerk(start_point=None):
    visited = set()
    to_visit = set(start_point or [])

    while to_visit:
        value = (yield to_visit.pop())
        if value and value not in visited:
            to_visit.add(value)

rawDescription: Python coroutine that consumes and produces


code:
title_contents = {}
for note in result_list.notes:
    content = note_store.getNoteContent(auth_token,
                                        note_store.getNote(note.guid,
                                        True,False, False, False).guid)
    title_contents[note.title] = content

return render_to_response('oauth/callback.html', {'notebooks': notebooks,
                                                  'result_list': result_list,
                                                  'title_contents': title_contents})

rawDescription: How to show the content of each Evernote note in Django

description: Show the content of each Evernote note in Django


code:
import cProfile
pr = profile.Profile()
pr.enable()
import mwe
pr.disable()
pr.print_stats(sort='time')

rawDescription: Python getting meaningful results from cProfile


code:
import unittest
import sys

class Test(unittest.TestCase):
    def tearDown(self):
        try:
            del sys.modules['logging']
        except KeyError:
            pass
    def test_logging(self):
        import logging
        logging.foo=1
    def test_logging2(self):
        import logging
        print(logging.foo)

if __name__ == '__main__':
    unittest.sys.argv.insert(1,'--verbose')
    unittest.main(argv = unittest.sys.argv)

rawDescription: re-import module-under-test to lose context

description: Re-import module-under-test to lose context


code:
from collections import Counter
from itertools import chain
infile = open('data')

lines = infile.readlines()
cnt_lines = len(lines)

words = list(chain.from_iterable([x.split() for x in lines]))
cnt_words = len(words)

cnt_chars = len([ c for word in words  for c in word])

# show words frequency
print(Counter(words))

rawDescription: Print out the character, word, and line amounts using Python


code: id, device_id, valuetype1, valuetype2, valuetype3, ... ,valuetypen, timestamp

rawDescription: Struggling to take the next step in how to store my data


code:
array3 = array1.astype(float)
array3[array1 != 0] = array2[np.where(array2[:, 0][None, :] == array1[array1 != 0][:, None])[1], 2]
array3

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


code:
"vanilla" and ""
"" and "vanilla"

rawDescription: Need help understanding Booleans?

description: Need help understanding Booleans


code:
from datetime import datetime
start = datetime.strptime("2015-02-23 02:56:00","%Y-%m-%d %H:%M:%S")
end = datetime.strptime("2015-02-23 03:56:00","%Y-%m-%d %H:%M:%S")

if start <= d <= end:
    print(d)

rawDescription: How can i get the time interval in python

description: Get the time interval in python


rawDescription: Handling string with delimiters in argparse


code:
class Swoosh():
    spam = ''
    eggs = ''
    swallow = ''
    coconut = ''

rawDescription: Initializing object variables - a Java approach, a Python approach?


code:
for video in ['http://www.youtube.com/watch?v=i62Zjga8JOM']:
    dump_mp3_for(video)

rawDescription: Make a request to download a video in Python


code: data.query("state != 'New York'")

rawDescription: Most efficient way to exclude indexed rows in pandas dataframe


rawDescription: Make a dictionary on matching values

description: Make a dictionary on matching values


code: answer

rawDescription: Removing everything except letters and spaces from string in Python3.3


code:
class Foo(object):
    def __repr__(self): return '<Foo repr>'
    def __str__(self): return 'Foo as string'
    def __format__(self, spec): return 'Formatting Foo as {}'.format(spec)

'{:02x}'.format(Foo())
'{!s}'.format(Foo())
'{!r}'.format(Foo())

rawDescription: Python PEP3101: Why the field_spec is not passed to the __format__ function?


code:
import numpy as np
from tifffile import imsave
image = np.zeros((32, 256, 256), 'uint16')
imsave('multipage.tif', image)

rawDescription: Create a multiframe .tif file

description: Create a multiframe .tif file


code:
content = 'Please get me the Python book you talked about, @friend'
new_content = re.sub(r'(@\w+)', r"\g<0>>" % (reverse('profile', kwargs={'user_name': 'friend_username'})), content)

rawDescription: Using URL in Django Views? Possible?

description: Using URL in Django Views? Possible


code:
from functools import partial
heatmap_rgba = partial(cmap.to_rgba, alpha=0.5, bytes=True)
heatmap_per_list = partial(map, heatmap_rgba)
heatmap_color = map(heatmap_per_list, heatmap)

rawDescription: Python: Optimise For loops using list-comprehension


code:
app = Flask('wasp')
api = Api(app)

api.add_resource(
    DBAccessor,
    '/option/<ques_no>/<i>')

rawDescription: flask restful: how to give multiple arguments to get methhod of any Api using flask restful?

description: Flask restful: how to give multiple arguments to get methhod of any Api using flask restful


code:
from operator import itemgetter
data.sort(key=itemgetter(2))

rawDescription: python 2.4 sorting a text file by specific column

description: Python 2.4 sorting a text file by specific column


code:
for event in pygame.event.get():
    if event.type == pygame.MOUSEBUTTONDOWN:
        run_your_animation()

rawDescription: How use mouse control with pygame?

description: How use mouse control with pygame


code:
new_a = b
new_b = a + b
new_c = c + 1

a = new_a
b = new_b
c = new_c

rawDescription: What is the different between these two ways for declaring variables in python?


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

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


code: data

rawDescription: pandas error creating TimeDeltas from Datetime operation

description: Pandas error creating TimeDeltas from Datetime operation


code:
def save_form(self, request, form, change):
    f_save = form.save()
    f_save.groups = new_queryset
    return f_save

rawDescription: modifying admin groups M2M field

description: Modifying admin groups M2M field


code:
loss = ...
optimizer = tf.train.AdaGradOptimizer(0.01)
train_op = optimizer.minimize(loss, colocate_gradients_with_ops=True)

rawDescription: Is it possible to split a network across multiple GPUs in tensorflow?


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


rawDescription: Dict of dicts of dicts to DataFrame

description: Dict of dicts of dicts to DataFrame


code:
m = []
count = 0
for i in range(N):
    column = []
    for j in range(M):
        column.append(results[count].get())
    m.append(column)

rawDescription: How do I make processes able to write in an array of the main program?

description: Make processes able to write in an array of the main program


rawDescription: Difference between different hex types/representations in Python


code:
ords = [list(map(ord,x.split(","))) for x in keys] # get ord values from each char
ords

rawDescription: Sorting dictionary by value and key length


rawDescription: Tensorflow Race conditions when chaining multiple queues


code:
#! /usr/bin/env
from __future__ import print_function
import json

JSON_TEXT = '''
{"transacDet":[{"field1":6933434802,"field2":323499903,"field3":293483842},
{"field1":693433448,"field2":333400300,"field3":298334300}],"responseStatus"
:{"statusMessage":"success","statusCode":0}}'''

resp_json = json.loads(JSON_TEXT)
for d in resp_json['transacDet']:
    for k in sorted(d.keys()):
        print(k, d[k])

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


code:
bS = 'tgby'
prd = ["".join(it) for it in itertools.product(bS, repeat=len(bS)-1)]

rawDescription: python: chain elements of a tuple in a list of tuples

description: Python: chain elements of a tuple in a list of tuples


code:
import sys
from termcolor import colored, cprint

text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text)
cprint('Hello, World!', 'green', 'on_red')

rawDescription: How do I print colored output to the terminal in Python?

description: Print colored output to the terminal in Python


code:
upload_keys(target.get_ip(), user.get_name())
remote_action("Some command")

rawDescription: Options to do a "mini-dsl" with Python?

description: Options to do a "mini-dsl" with Python


code: zip(*sorted(zip(*l)))

rawDescription: Sorting a list of lists in python alphabetically by "column"


rawDescription: Selenium - get all children divs but not grandchildren


code:
[('stringOfAlphaNumeric2', 'stringOfAnyCharacter4'),
('stringOfAlphaNumeric2', 'stringOfAnyCharacter5'),
('stringOfAlphaNumeric2', 'stringOfAnyCharacter6'),
('stringOfAlphaNumeric1', 'stringOfAnyCharacter1'),
('stringOfAlphaNumeric1', 'stringOfAnyCharacter2'),
('stringOfAlphaNumeric1', 'stringOfAnyCharacter3')]

rawDescription: Again, regular expression matching in python


code:
from bz2 import BZ2File
import sys

f = BZ2File("/home/konrad/output.bin")
for line in f.readlines():
    sys.stdout.write(line)

rawDescription: Easiest way to compress in Python and decompress with decompress C# (and vice versa)


code:
from pyspark.sql.functions import col, sum as sum_, when
from pyspark.sql import Window
import sys

w = Window.partitionBy("colA").rowsBetween(-sys.maxsize, sys.maxsize)

this_non_zero = col("colB") != 0
any_non_zero = sum_(this_non_zero.cast("long")).over(w) != 0

(df
  .withColumn("this_non_zero", this_non_zero)
   .withColumn("any_non_zero", any_non_zero)
   .where(
       (col("this_non_zero") & col("any_non_zero")) |
       ~col("any_non_zero")
   ))

rawDescription: Selecting row based on column value in duplicated entries on different column in PySpark


code:
with open(inFile,'r') as i:
    lines = i.readlines()

processedLines = manipulateData(lines)

with open(outFile,'w') as o:
    for line in processedLines:
        o.write(line)

rawDescription: How to take input file from terminal for python script?

description: Take input file from terminal for python script


code:
a1 = doc.getElementsByTagName('a')
a2 = doc.getElementsByTagName('A')

#do stuff with a1 and a2

rawDescription: Python Minidom XML parsing interchangable upper and lower case node names


code:
import pandas as pd

df = pd.DataFrame({'col1':[1,2,3], 'col2':[4,5,6]},
                  index = ['row1','row2','row3'])

dfstacked = df.stack()

mask = dfstacked <= 3

colors = np.array(['b']*len(dfstacked))
colors[mask.values] = 'r'

dfstacked.plot(kind = 'bar', rot = 45, color = colors)
plt.show()

rawDescription: Color matplotlib bar chart based on value


code:
def order_function(price_x, price_y, array):
    price_x = price_x
    price_y = price_y
    array.append(price_x)
    # etc

rawDescription: How to design an algorithm that initializes once every 20 times it's called?

description: Design an algorithm that initializes once every 20 times it's called


rawDescription: Python shebang problems with importing modules (and choosing the correct interpreter)


rawDescription: Manipulate Pandas DataFrame containing dictionaries from Twitter API


code:
def run_it(o, partial):
    for name in dir(o):
        if partial in name:
            getattr(o, name)()

rawDescription: Calling unspecified function from another file and another class


code:
blues = reds = 0
for word in a.split():
    if word == 'blue':
        blues += 1
    if word == 'red':
        reds += 1
print("red:", reds)
print("blue:", blues)

rawDescription: How can i read these 2 words specifically?

description: Read these 2 words specifically


code:
from inspect import getargspec
defaults = getargspec(my_function).defaults
my_variable = defaults[0]
my_function(my_variable)
argspec = getargspec(my_function)
keyword_args = dict(zip(argspec.args[-len(argspec.defaults):], argspec.defaults))
positional_args = [None] * (len(argspec.args) - len(argspec.defaults))  # set all positionals to None
my_function(*positional_args, **keyword_args)
keyword_args

rawDescription: python variable value to trigger parameter default

description: Python variable value to trigger parameter default


rawDescription: Rearrange misplaced columns

description: Rearrange misplaced columns


code: d_out = {k:v for k,v in d.items() if not any('Remove_' in x for x in k)}

rawDescription: python 2.7 : remove a key from a dictionary by part of key

description: Python 2.7 : remove a key from a dictionary by part of key


code: try_match = lambda m, re_match=re.compile(r'sldkjlsdjf').match: re_match(m)

rawDescription: How to maintain state in Python without classes?

description: Maintain state in Python without classes


code:
import numpy as np
import pandas as pd

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

rawDescription: Select dataframe rows between two dates

description: Select dataframe rows between two dates


code:
import ConfigParser
import sys

config = ConfigParser.ConfigParser()
config.set(ConfigParser.DEFAULTSECT, 'name', 'value')

ORIG_DEFAULTSECT = ConfigParser.DEFAULTSECT # <---
ConfigParser.DEFAULTSECT = 'default'
try:
    config.write(sys.stdout)
finally:
    ConfigParser.DEFAULTSECT = ORIG_DEFAULTSECT # <---

rawDescription: Write to lowercase 'default' section ConfigParser


code:
def make_command(obj, *args, **kwargs):
    def f():
        obj.send_command(*args, **kwargs)
    return f

rawDescription: Using Deque.popleft as args for function


code:
#!/usr/bin/env python
import re
from trieMatch import PrefixMatch # https://gist.github.com/736416

pm = PrefixMatch(['YELLOW', 'GREEN', 'RED', ]) # huge list of 10 000 members
# if list is static, it might be worth picking "pm" to avoid rebuilding each time

f = open("huge_file.txt", "r") ## file with > 100 000 lines
lines = f.readlines()
f.close()

regexp = re.compile(r'^.*?fruit=([A-Z]+)')
filtered = (line for line in lines if pm.match(regexp.match(line).group(1)))

rawDescription: Smart filter with python

description: Smart filter with python


code:
a = DemoClass(3)
isinstance("abc", str)
isinstance(a, DemoClass)
isinstance(a, int)
issubclass(DemoClass, int)

rawDescription: Create/imitate mutable subclass of immutable built-in type


code:
class conform(serializers.ModelSerializer):
    class  Meta:
        fields = ( 'name','profile__age')
        model = a

rawDescription: Django REST combining Meta. models

description: Django REST combining Meta. models


code:
# initialize a variable to keep track of the total
total = 0

# Determine price per pound
# use if elif
if quantity >= 40:
    total = quantity * 7.50
elif quantity >= 20:
    total = quantity * 8.75
elif quantity >= 10:
    total = quantity * 10.00
else:
    total = quantity * 12.00

# do the tax calculations using total
total = total * 1.07

# print the result
print('Cost of coffee $', format(total,'.2f'), sep='')

rawDescription: Python assign variable names to if else function


rawDescription: Linear regression - reduce degrees of freedom


code:
#!/usr/bin/python
from twisted.scripts.twistd import run
from my.application import some_module
from os.path import join, dirname
from sys import argv
argv[1:] = [
    '-y', join(dirname(some_module.__file__), "myapp.py"),
    '--pidfile', '/var/run/myapp.pid',
    '--logfile', '/var/run/myapp.log'
]
run()

rawDescription: Twisted application without twistd

description: Twisted application without twistd


code:
import datetime

class EST5EDT(datetime.tzinfo):

    def utcoffset(self, dt):
        return datetime.timedelta(hours=-5) + self.dst(dt)

    def dst(self, dt):
        d = datetime.datetime(dt.year, 3, 8)        #2nd Sunday in March
        self.dston = d + datetime.timedelta(days=6-d.weekday())
        d = datetime.datetime(dt.year, 11, 1)       #1st Sunday in Nov
        self.dstoff = d + datetime.timedelta(days=6-d.weekday())
        if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
            return datetime.timedelta(hours=1)
        else:
            return datetime.timedelta(0)

    def tzname(self, dt):
        return 'EST5EDT'

dt = datetime.datetime.now(tz=EST5EDT())

rawDescription: How to get python to display current time (eastern)

description: Get python to display current time (eastern)


code:
object = try_memcached()
if not object:
    object = real_query()
    put_in_memcached(object)

rawDescription: Pylons and Memcached

description: Pylons and Memcached


rawDescription: Defining a logger for every thread

description: Defining a logger for every thread


code: hostname, _, addrlist = host

rawDescription: How to split the return of socket,gethostbyaddr and write to file?

description: Split the return of socket,gethostbyaddr and write to file


code:
readcookie = cookies.SimpleCookie(os.environ["HTTP_COOKIE"])
print(readcookie["varname"].value)

rawDescription: Python Setting and Recalling Cookies

description: Python Setting and Recalling Cookies


code:
from scipy.stats import norm
xs   = np.linspace(-3, 3, 100)
pdf  = norm.pdf(xs)
prob = pdf / pdf.sum() # these are probabilities
np.std(prob)           # note the very small value below

rawDescription: Calculate the standard deviation of a gaussian


code:
import foo as foo1
import foo as foo2
foo1 is foo2

rawDescription: Little confused with import python

description: Little confused with import python


code:
by_col = np.sum(M!=0, axis=0)
# use the counts of non-zero terms in each column, stored in an array
...

# if you need the grand total, use sum again
total = np.sum(by_col)

rawDescription: Walk through each column in a numpy matrix efficiently in Python


code:
import xml.etree.ElementTree  as et

xml = et.fromstring(x)

xml.find(".//attributes/transpose").append(et.fromstring('<octave-change>-1</octave-change>'))

print(et.tostring(xml))

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

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


code:
arr = [1, 2, 3, 4, 5, 6, 7, 8]
b2 = BitArray.from_array([i >= 3 for i in arr])
print(b2)
new_int = 9
b2.rotate_in(new_int >= 3)
print(b2)

rawDescription: Python dynamic bit manipulation example

description: Python dynamic bit manipulation example


code:
se = set(lis2)
all(x in se for x in lis1)

rawDescription: pattern match list a with list b

description: Pattern match list a with list b


code:
from collections.abc import Mapping

def layers(data):
    if isinstance(data, Mapping):
        yield data.keys()
        yield from layers(next(data.values()))

rawDescription: Parsing Python Dictionary Keys

description: Parsing Python Dictionary Keys


code:
import Tkinter as Tk
root = Tk.Tk()
b1 = Tk.Button(root,text="Button1")
b1.grid(row=0,column=0)
b2 = Tk.Button(root,text="Button2")
b2.grid(row=0,column=1)
big_widget = Tk.Canvas(root)
big_widget.grid(row=1,column=0,columnspan=2)

rawDescription: What is a better Tkinter geometry manager than .grid()


rawDescription: Cartesian product generic function in Python


code:
import csv

files = [open('part_{}'.format(n), 'wb') for n in xrange(100)]
csvouts = [csv.writer(f) for f in files]
with open('yourcsv') as fin:
    csvin = csv.reader(fin)
    next(csvin, None) # Skip header
    for rowno, row in enumerate(csvin):
        csvouts[rowno % 100].writerow(row)

for f in files:
    f.close()

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

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


code:
class People(object):
    def __init__(self, people=()):
        self._members = list(people)

    # add other methods/special methods like __len__ etc.

    def add(self, person):
        self._members.append(person)
    def remove(self, person):
        self._members.remove(person)

people = People()
people.add(john)
people.add(jack)

# Change list to set?

class People(object):
    def __init__(self, people=()):
        self._members = set(people)
    def add(self, person):
        self._members.add(person)
    def remove(self, person):
        self._members.remove(person)

rawDescription: Python add object to list inside same object method


code:
tagged_text = pos_tag(text.split())
tagged_text

rawDescription: chunk NP and VP using nltk

description: Chunk NP and VP using nltk


code:
import numpy as np
from mayavi import mlab

angle = np.linspace(0, 6*np.pi, 1000)
x = np.sin(angle)
y = np.cos(angle)
z = angle / 6.0

mlab.plot3d(x, y, z, color=(1,0,0), tube_radius=0.1)

angle += np.pi*2/3.0
x = np.sin(angle)
y = np.cos(angle)
z = angle / 6.0 - 0.5
mlab.plot3d(x, y, z, color=(0,0,1), tube_radius=0.1)

mlab.axes()
mlab.show()

rawDescription: Is there something like a depth buffer in matplotlib?


code:
firstHex = 7
secondHex = A

rawDescription: Python string splitting

description: Python string splitting


code:
from collections import defaultdict
from functools import partial

class IndexingList:
    def __init__(self, items):
        self.items = []
        self.indices = defaultdict(partial(defaultdict, list))
        self.extend(items)

    def append(self, item):
        try:
            for index, value in item.items():
                self.indices[index][value].append(item)
        except AttributeError as e:
            raise ValueError("All children of an IndexingList must be "
                             "dict-like. '{0}' is not.".format(item)) from e
        self.items.append(item)

    def extend(self, iterable):
        for item in iterable:
            self.append(item)

    def __iadd__(self, other):
        self.extend(other)
        return self

    def __getitem__(self, item):
        return self.items[item]

    def __setitem__(self, item, value):
        self.items[item] = value

    def __delitem__(self, item):
        del self.items[item]
        for index, value in item.items():
            self.indices[index][value].remove(item)

    def find_all(self, index, value):
        return self.indices[index][value]

    def __repr__(self):
        return repr(self.items)

rawDescription: Python list class that indexes its object-elements' properties


rawDescription: Pandas: How to convert a 10-min interval timeseries into a dataframe?


code: a + b

rawDescription: How to get the expected result using list comprehension

description: Get the expected result using list comprehension


code:
for y in x:
    if y >= 50:
        print("Good")
    else:
        print("Bad")

rawDescription: Conditional if statements based on items in a list with python 3.x


code:
action = {self.backupBtn: 'Backs up', self.connectBtn: 'Connects to',
    self.moveBtn: 'Copies', self.moveBtn: 'Moves'}
def mouseOver(self, event):
    self.status['text'] = "%s the selected database." % action[event.widget]

rawDescription: Multiple Buttons In One Method Python 3

description: Multiple Buttons In One Method Python 3


code:
def using_void(A, B):
    dtype = 'V{}'.format(A.dtype.itemsize * A.shape[-1])
    Ad = np.ascontiguousarray(A).view(dtype)
    Bd = np.ascontiguousarray(B).view(dtype)
    return ~np.in1d(Ad, Bd, assume_unique=True)

rawDescription: Matrix row difference, output a boolean vector


code:
li = ['0', ['1', '2'], ['3', ['4', '5'], '6', ['7'], '8'], '9']
def to_int(lst, path=[]):
    for i, j in enumerate(lst):
        if isinstance(j, list):
            yield from to_int(j, path+[i])
        else:
            yield int(j), path+[i]

for item in to_int(li):
    print (item)

rawDescription: Working on multilevel list (2)

description: Working on multilevel list (2)


rawDescription: Feeding a Python array into a Perl script


code:
script = argv
first = argv
second = argv
third = argv

rawDescription: Printing individual script arguments repeatedly prints all of them


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

    for url in a_bunch_of_urls:
        scrape_table(url, linewriter)

rawDescription: Scraping tables and writing rows to CSV

description: Scraping tables and writing rows to CSV


code:
[[1, 3], [1]]  # list1
[[1, 3], [1]]  # list2
[[1], [1]]     # list3 - unaffected by reference-madness

rawDescription: Passed argument/parameter in function is still being changed after removing the reference/alias


code: pd.concat(g for _, g in df.groupby("ID") if len(g) > 1)

rawDescription: How do I get a list of all the duplicate items using pandas in python?

description: Get a list of all the duplicate items using pandas in python


code:
char_generator = (pair for pair in enumerate(sequence) if pair[1] in subsequence)
for combo in itertools.combinations(char_generator, len(subsequence)):
    if all(pair[1]==char for pair,char in zip(combo,subsequence)):
        print([pair[0] for pair in combo])

rawDescription: Python: Sub sequence search

description: Python: Sub sequence search


code:
# get an array of the unique year values
year_vals = df.Year.unique()
# create our dict
data_dict={}
# iterate for each year make a key and set the value to the pivot table
for year in year_vals:
    data_dict[str(year)] = df[df.Year == year].pivot_table(columns='Incident', index='Vector',
                             aggfunc=len,)

rawDescription: Python Summarizing data efficiently using loops in pandas


code:
# old school lisper style.
sorted(list_of_games, key=lambda x: x.name)
filter(lambda x: x.name=='stuff', list_of_games)
# new style
[x for x in list_of_games if x.name=='stuff']

rawDescription: SQLAlchemy Query Possible?

description: SQLAlchemy Query Possible


code:
import numpy as np
import matplotlib.pyplot as plt
d = {'apples': 5, 'oranges': 2, 'bananas': 2, 'lemons': 1, 'coconuts': 1}

jet = plt.get_cmap('jet')
N = len(d)
plt.bar(range(N), d.values(), align='center', color=jet(np.linspace(0, 1.0, N)))
plt.xticks(range(N), d.keys(), rotation=25)

rawDescription: ipython pylab: print histogram from dictionary

description: Ipython pylab: print histogram from dictionary


code:
import networkx as nx
graph = nx.Graph(sim_matrix)
graph.nodes()
graph.edges(2)
graph.edges(4)

rawDescription: optimizing code for traversing a matrix in python

description: Optimizing code for traversing a matrix in python


rawDescription: Select text of textEdit object with QTextCursor, QTextEdit


rawDescription: Django cooking recipes site model structure


rawDescription: MongoDB Collection with Non-repeated field value


code:
cursor.execute("select database()")
db_name = cursor.fetchone()[0]

rawDescription: How to get database name from postgres/mysql cursor object

description: Get database name from postgres/mysql cursor object


code: _.translate(None, '.')

rawDescription: Rounding a number in python but keeping ending zeros


code:
import serial
s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)
s.write('2')
s.readline()

rawDescription: python to arduino serial read & write

description: Python to arduino serial read & write


code:
class MetaClass(type):
    @staticmethod
    def _create_getter(attr):
        def _getter(self):
            return getattr(self, attr)
        return _getter

    def __init__(self, name, bases, attrs):
        super(MetaClass, self).__init__(name, bases, attrs)

        for attr in attrs:
            if not attr.startswith('_'):
                setattr(self, 'get_%s' % attr, MetaClass._create_getter(attr))

class Base(object):
    __metaclass__ = MetaClass

rawDescription: how does django set up object method before it was defined

description: How does django set up object method before it was defined


code:
seq= something.get()
root.copy( seq[0] )
foo( seq[0] )
for member in seq[1:]:
    somewhereElse.copy(member)
    foo( member )

rawDescription: "For" loop first iteration

description: "For" loop first iteration


code: 'start t end'

rawDescription: Using a regular expression to replace upper case repeated letters in python with a single lowercase letter


rawDescription: Pandas: dataframes won't merge

description: Pandas: dataframes won't merge


code:
def addparams():
    param1 = ''
    param2 = ''
    typeans = ['parameter 1', 'param 1']
    typeansa = ['parameter 2', 'param 2']
    while True:
        [...] # same code as above
    return param1, param2

param1, param2 = addparams()
url = 'www.website.com/'+param1+param2 # not sure that's the url you want

rawDescription: Updating empty variables outside a function


code:
x = np.linspace(0,1,11)
y = np.linspace(1,0,11)
u = v = np.zeros((11,11))
u[5,5] = 0.2

plt.quiver(x, y, u, v, scale=1)

rawDescription: How does Python's matplotlib.pyplot.quiver exactly work?


code:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

x, y, z = [], [], []

for tim, pixels in dictionary.items():
    for pixel, intensities in pixels.items():
        for intensity in intensities:
            x.append(intensity)
            y.append(pixel)
            z.append(tim)

fig = plt.figure()
ax = Axes3D(fig)
ax.plot(x, y, z, zdir='z')
ax.show()

rawDescription: 3D-plotting nested dictionaries made up of different length arrays


code:
s = pd.Series([dt, dt])
s
s + pd.Timedelta(888)
s_nano = pd.Series([pd.Timedelta(888), pd.Timedelta(999)])
s + s_nano

rawDescription: How to create a pandas.Timestamp from datetime.datetime object and nanoseconds value

description: Create a pandas.Timestamp from datetime.datetime object and nanoseconds value


rawDescription: Defining a dictionary of dictionaries with vectors as inner and outer keys


code:
Message: 'Hello world'
Key: 'This_is_my_awsome_secret_key'
Encrypted: '\x1dNV`O\nkO`fD'
Decrypted: 'Hello world'

rawDescription: Custom Python Encryption algorithm

description: Custom Python Encryption algorithm


code:
import os
myhost = os.environ.get('MYSQL_PORT_3306_TCP_ADDR')
myport = int(os.environ.get('MYSQL_PORT_3306_TCP_PORT'))
import _mysql
db=_mysql.connect(host=myhost,port=myport,passwd="...",db="...")

rawDescription: connect to mysql server in docker

description: Connect to mysql server in docker


code:
stacks = [[1, 2, 3], [[4, 5, 6], [1, 2, 3]]]
wrapped = (s if isinstance(s[0], list) else [s] for s in stacks)
total = [sum(x[1] for x in w) for w in wrapped]
total

rawDescription: Sum concisely particular elements in a list of lists


rawDescription: combination of words based on a list of list of characters

description: Combination of words based on a list of list of characters


code:
def no_duplicates(x):
    seen = set()
    return not any(i in seen or seen.add(i) for i in x)

data = {((3, 2), (2, 1)),
        ((3, 2), (3, 1)),
        ((3, 1), (2, 1)),
        ((2, 1), (1,3), (2, 3))}

print({item for item in data if no_duplicates(first for first, _ in item)})

rawDescription: Throwing out elements in a python list of pairs


code:
items = ["stack", "over", "flow"]
map = { }

for item in items:
    def new_command():
        print(item)

    map[item] = new_command

map["stack"]()
map["over"]()
map["flow"]()

rawDescription: Dynamically creating a menu in Tkinter. (lambda expressions?)


code:
n = Symbol('n', integer=True)
sols = solve(sin(z + 2*pi*n) - 2, z)
sols
[i.rewrite(log) for i in sols]

rawDescription: How to solve sin(z)=2 in Sympy?

description: Solve sin(z)=2 in Sympy


code:
def showExits(self):
    return "This room has %d exits: %s" % (len(self.exits), ','.join(self.exits))

rawDescription: Relationships between variables

description: Relationships between variables


code: [character for character in sentence if character not in vowels] # returns list

rawDescription: Removing from vowels from a string

description: Removing from vowels from a string


code:
import operator
for s in map(operator.add, long_str[::2], long_str[1::2]):
   print (s)

rawDescription: Getting two characters from string in python


code:
ind=np.argsort(data[:,1],axis=0)
ind
data[ind.ravel(),:]  # ravel needed because of matrix

rawDescription: Sorting all rows in numpy matrix by target-column


rawDescription: Easiest way to remove unicode representations from a string in python 3?


code:
from urllib import urlretrieve
urlretrieve('http://upload.wikimedia.org/wikipedia/en/4/44/Zindagi1976.jpg',
            'Zindagi1976.jpg')

rawDescription: How to use urllib to download image from web

description: Use urllib to download image from web


rawDescription: Reversing bits of Python integer

description: Reversing bits of Python integer


code: res

rawDescription: Concatenation of a variant number of keys of a dictionary Python (recursion?)


code:
tpgrp = wls.groupby('Top')
tpgrpdict= dict(list(tpgrp))
tp0= tpgrp.get_group('BOT0')

rawDescription: Using print to access individual cells of pandas dataframe after groupby


code:
user = db.Key('aglwb3J0Zm9saW9yCwsSBFVzZXIY6gEM')
que = db.GqlQuery("SELECT * FROM Portfolio_Owners WHERE user_id = :1", user)

rawDescription: Gql Query on ReferenceProperty()

description: Gql Query on ReferenceProperty()


code: escape('<a>')

rawDescription: Python html alphabet

description: Python html alphabet


code:
def a(a, b, c):
    # make this your first statement
    print(len(locals()))

rawDescription: Check the number of parameters passed in Python function


code:
import csv

myparagraph = """
this is a long paragraph, with "quotes" and stuff.
"""

mycsv = csv.writer(open('foo.csv', 'wb'))
mycsv.writerow([myparagraph, 'word1'])
mycsv.writerow(['word2', 'word3'])

rawDescription: how to encode a paragraph for use in a CSV file in python

description: Encode a paragraph for use in a CSV file in python


code:
class Foo(object):
   def __init__(self):
     self.a = []
     self.b = 2

rawDescription: New instance of Python class with a non-None class attribute


code:
import nose

def xfrange(start, stop, step=1.):
    """ Floating point equivalent to xrange()."""
    while start < stop:
        yield start
        start += step

# Test simple inverted mapping for non-wrapped domain
pts = [(x,-x) for x in xfrange(1.,16., 1.)]
a = InterpolatedArray(pts)
for i in xfrange(1., 15., 0.1):
    nose.tools.assert_almost_equal(a[i], -i)
# Cause expected over/under range errors
result = False  # Assume failure
try: x = a[0.5]
except ValueError: result = True
assert result
result = False
try: x = a[15.5]
except ValueError: result = True
assert result

# Test simple wrapped domain
wrap = 360.
offset = 1.234
pts = [(x,((wrap/2.) - x)) for x in xfrange(offset, wrap+offset, 10.)]
a = InterpolatedArray(pts, wrap)
for i in xfrange(0.5, wrap, 0.1):
    nose.tools.assert_almost_equal(a[i], (((wrap/2.) - i)%wrap))

rawDescription: Circular interpolation in Python

description: Circular interpolation in Python


code: now.strftime('%Y-%m-%d %H:%M:%S %Z')

rawDescription: Time issues in Python

description: Time issues in Python


code:
def countryCommand():
    for button in keyboardButtons:
        button['state']=tk.NORMAL

keyboardButtons = []
for k in kybrd_list:
    ...
    keyboardButtons.append(tk.Button(root, text=k, width=5, relief=rel2, command=cmd2, state=tk.DISABLED))
    ...

rawDescription: tkinter enabling a list of buttons, but only one(the last one) responds

description: Tkinter enabling a list of buttons, but only one(the last one) responds


code:
your_byte_string = b'\x00'
# you can write also
# your_byte_string = u'\u0000'

print(json.dumps(convert_to_bool(your_byte_string)))

# >>> true

your_byte_string = b'\x01'
# you can write also
# your_byte_string = u'\u0001'

print(json.dumps(convert_to_bool(your_byte_string)))

# >>> false

rawDescription: Jsonifying bits from MySQLdb in Python

description: Jsonifying bits from MySQLdb in Python


code:
{'Apple bets new 4-inch iPhone to draw big-screen converts in China, India': 'https://in.finance.yahoo.com/news/apple-bets-4-inch-iphone-112024627.html',
 "Apple's new iPhone faces challenge measuring up in China, India": 'https://in.finance.yahoo.com/news/apples-iphone-faces-challenge-measuring-002248597.html',
 'Foxconn says in talks with Sharp over deal hitch; hopes for agreement': 'https://in.finance.yahoo.com/news/sharp-shares-plunge-foxconn-puts-031032213.html',
 'Samsung wins appeal in patent dispute with Apple': 'https://in.finance.yahoo.com/news/samsung-wins-appeal-patent-dispute-022120916.html',
 "Signs of life for Apple's stock as Wall St eyes new iPhone": 'https://in.finance.yahoo.com/news/signs-life-apples-stock-wall-165820189.html',
 'Solid support for Apple in iPhone encryption fight - Reuters/Ipsos': 'https://in.finance.yahoo.com/news/solid-support-apple-iphone-encryption-121255578.html'}

rawDescription: Python: searching through html file grabbing <a> tags with the href and text content


code:
from itertools import product, starmap, islice

def findNeighbors(grid, x, y):
    xi = (0, -1, 1) if 0 < x < len(grid) - 1 else ((0, -1) if x > 0 else (0, 1))
    yi = (0, -1, 1) if 0 < y < len(grid[0]) - 1 else ((0, -1) if y > 0 else (0, 1))
    return islice(starmap((lambda a, b: grid[x + a][y + b]), product(xi, yi)), 1, None)

rawDescription: Python, finding neighbors in a 2-d list

description: Python, finding neighbors in a 2-d list


code: a1[:, np.newaxis, np.newaxis] | a2[np.newaxis, :, np.newaxis] | a3[np.newaxis, np.newaxis, :]

rawDescription: Or'ing boolean arrays of different sizes


code:
with open(JSON_PATH, mode='w') as wf:
    json.dump(jf, wf)

rawDescription: Adding json object to unnamed set of json objections


code:
soup = BeautifulSoup(html)

all_tds = soup.findAll("td")

with open("out.txt","a+") as f:
    for td in all_tds:
        if "background-color:red" in soup.td.get("style"):
            f.write(soup.td.get("title")+"\n")

rawDescription: Extracting a word from text file using Python


code:
class cls_with_basic_method:

      def basic_method(arg):
         #...
         return arg

class cls_with_basic_method_and_decoratorA(class_with_basic_method):
      basic_method = decoratorA(cls_with_basic_method.basic_method)

class cls_with_basic_method_and_decoratorB(class_with_basic_method):
      basic_method = decoratorB(cls_with_basic_method.basic_method)

rawDescription: Dynamically assigning sub class dependent decorators


code: mapping = {item:set() for item in listOfItems if item != "SomethingIDoNotWant"}

rawDescription: Initialize dict with only some of a list


code:
xx = x / dx
yy = y / dy
zz = z / dz

rawDescription: Fast interpolation of regularly sampled 3D data with different intervals in x,y, and z


code:
dealerships = session.query(Dealership).filter_by(ownerID = userId).all()
names = [dealership.name for dealership in dealerships]
return jsonify(names = names)

rawDescription: Cant access value of JSON object

description: Cant access value of JSON object


code:
import datetime
adate = datetime.datetime.strptime("23.10.2012", "%d.%m.%Y").date()
adate + datetime.timedelta(days=30)

rawDescription: How can I "change" a python struct_time object?

description: "change" a python struct_time object


code:
from PySide import QtGui

app = QtGui.QApplication([])

button = QtGui.QPushButton()
button.setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')
button.setText('Press Me')
menu = QtGui.QMenu()
menuItem1 = menu.addAction('Menu Item1')
menuItem2 = menu.addAction('Menu Item2')

button.setMenu(menu)
button.show()

app.exec_()

rawDescription: How to change QPushButton text and background color

description: Change QPushButton text and background color


code:
def form_valid(self, form):
    ...
    self.request.session['submit_social_data'] = True
    return redirect(self.get_success_url())

rawDescription: Python social auth partial pipeline resume after form submit button


code:
import multiprocessing.pool

def thirty_second_function():
    return ["mango", "habanero", "salsa"]

def five_second_function():
    return {"beans": "8 oz", "tomato paste": "16 oz"}

if __name__ == '__main__':
    p = multiprocessing.pool.Pool()
    p1 = p.apply_async(thirty_second_function)
    p2 = p.apply_async(five_second_function)

    print(p1.get())
    print(p2.get())

rawDescription: Multiprocessing and variable return?

description: Multiprocessing and variable return


code:
import unittest
import utils_method as um

class Test(unittest.TestCase):
    def test_autoargs(self):
        class A(object):
            @um.autoargs()
            def __init__(self,foo,path,debug=False):
                pass
        a=A('rhubarb','pie',debug=True)
        self.assertTrue(a.foo=='rhubarb')
        self.assertTrue(a.path=='pie')
        self.assertTrue(a.debug==True)

        class B(object):
            @um.autoargs()
            def __init__(self,foo,path,debug=False,*args):
                pass
        a=B('rhubarb','pie',True, 100, 101)
        self.assertTrue(a.foo=='rhubarb')
        self.assertTrue(a.path=='pie')
        self.assertTrue(a.debug==True)
        self.assertTrue(a.args==(100,101))

        class C(object):
            @um.autoargs()
            def __init__(self,foo,path,debug=False,*args,**kw):
                pass
        a=C('rhubarb','pie',True, 100, 101,verbose=True)
        self.assertTrue(a.foo=='rhubarb')
        self.assertTrue(a.path=='pie')
        self.assertTrue(a.debug==True)
        self.assertTrue(a.verbose==True)
        self.assertTrue(a.args==(100,101))

    def test_autoargs_names(self):
        class C(object):
            @um.autoargs('bar','baz','verbose')
            def __init__(self,foo,bar,baz,verbose=False):
                pass
        a=C('rhubarb','pie',1)
        self.assertTrue(a.bar=='pie')
        self.assertTrue(a.baz==1)
        self.assertTrue(a.verbose==False)
        self.assertRaises(AttributeError,getattr,a,'foo')

    def test_autoargs_exclude(self):
        class C(object):
            @um.autoargs(exclude=('bar','baz','verbose'))
            def __init__(self,foo,bar,baz,verbose=False):
                pass
        a=C('rhubarb','pie',1)
        self.assertTrue(a.foo=='rhubarb')
        self.assertRaises(AttributeError,getattr,a,'bar')

if __name__ == '__main__':
    unittest.main(argv = unittest.sys.argv + ['--verbose'])

rawDescription: What is the best way to do automatic attribute assignment in Python, and is it a good idea?


rawDescription: making multi-index in pandas dataframes in Python?

description: Making multi-index in pandas dataframes in Python


code:
def function(l, n=0, test=0, calls=0):
    if not l:
        return n == test if calls > 0 else False
    else:
        n += l[0]
        calls += 1
        return function(l[1:], n, test,calls)

rawDescription: How to compare a return value of a recursive function with an integer (actual parameter of function)

description: Compare a return value of a recursive function with an integer (actual parameter of function)


code: idx = df.groupby(['candidate_id','enddate'], sort=False)['TitleLevel'].agg(lambda x: x.idxmax())

rawDescription: how to use groupby to avoid loop in python

description: Use groupby to avoid loop in python


code:
archive_id = vault.upload_archive("mybackup.tgz")
retrieve_job = vault.retrieve_archive(archive_id)

# if the job is in progress
job_id = retrieve_job.id
retrieve_job = vault.get_job(job_id)

if retrieve_job.completed:
    job.download_to_file("mybackup.tgz")

rawDescription: Using Boto to tell when a file has succesfully been uploaded to Glacier


code:
matches=re.findall(r'"whatiwant":"(.*?[^\\])??"', mstr)
for match in matches:
    html= match.group(1)

rawDescription: python - regex with quotes inside of the string

description: Python - regex with quotes inside of the string


code:
def getCommonLetters(a, b):
        return ''.join(sorted(set(a).intersection(set(b))))

getCommonLetters('google','apple')

rawDescription: To get the common letters in two words without repetition


code:
def PRHSX_message():
    prhsx_share_price = float(ystockquote.get_last_trade_price('PRHSX'))
    prhsx_daily_change = ystockquote.get_change('PRHSX')
    prhsx_total_shares = 47.527
    prhsx_starting_value = 2500
    prhsx_percent_change = (((prhsx_share_price * prhsx_total_shares) / prhsx_starting_value) - 1) * 100
    prhsx_current_value = prhsx_share_price * prhsx_total_shares
    prhsx_profit = prhsx_current_value - prhsx_starting_value

    prhsx_string = (
        "T. Rowe Price Roth IRA Account\n"
        "____________________________\n\n"
        "Percent Change: {}\n"
        "Share Price: {}\n"
        "Current Value: ${:.2f}\n"
        "Percent Growth: {:.2f}%\n"
        "Profit: ${:.2f}").format(
        prhsx_daily_change, prhsx_share_price, prhsx_current_value,
        prhsx_percent_change, prhsx_profit)

rawDescription: Why is Python printing braces here?

description: Why is Python printing braces here


code:
from django.template import Template, Context
t = Template("{{ foo.bar }}")
c = Context({'foo': {'hello': 'world'}, 'bar': 'hello'})
t.render(c)

rawDescription: "bar" in a Django template expression is a literal?


code:
numbins=10
H, xedges, yedges =np.histogram2d(x_axis, y_axis, bins=numbins, weights=z_axis)
count, x, y =np.histogram2d(x_axis, y_axis, bins=numbins)
H/=count

rawDescription: numpy histogram with 3 variables

description: Numpy histogram with 3 variables


code: select_query = select([table2.c.col1, table2.c.col2]).where(table1.c.key == table2.c.key)

rawDescription: Updating a table from another table with multiple columns in sqlalchemy


code:
def my__getattr__(self, key):
    # If attribute is in the self Series instance ...
    if key in self:
        # ... return is as an attribute
        return self[key]
    else:
        # ... raise the usual exception
        raise AttributeError("'Series' object has no attribute '%s'" % key)

# Overwrite current Series attributes 'else' case
pandas.Series.__getattr__ = my__getattr__

rawDescription: Access Pandas Series item with dot notation like DataFrame


code: b.data /= np.take(x, b.indices)

rawDescription: Substitute for numpy broadcasting using scipy.sparse.csc_matrix


code:
df = sqlContext.createDataFrame([
    (1, "a"),
    (2, "b"),
    (3, "c"),
], ["ID", "Text"])

categories = df.select("Text").distinct().rdd.flatMap(lambda x: x).collect()

exprs = [F.when(F.col("Text") == category, 1).otherwise(0).alias(category)
         for category in categories]

df.select("ID", *exprs).show()

rawDescription: pyspark matrix with dummy variables

description: Pyspark matrix with dummy variables


rawDescription: Fast way to obtain a random index from an array of weights in python


code: L = [['x','y'] for i in range(20)]

rawDescription: Creating a list in Python with multiple copies of a given object in a single line


code:
wb = xl.Workbooks.Open(r'C:\Path\to\folder\Test.xlsx')
ws = wb.Worksheets(1)
cell = ws.Cells(2)
cell.Value = 'Some more text'
wb.Close(True)

rawDescription: python win32 COM closing excel workbook

description: Python win32 COM closing excel workbook


code:
mod_val=10**9+7

hi = 5000
for lo in range(0, hi-1):

    # Code 2
    test1 = 1
    test2 = 1
    for each in xrange(1,lo+1):
        test1 = (test1*each)
        test2 = (test2*(hi+each))

    test_output = (test2 / test1) % mod_val
    # print test_output

rawDescription: Placing of modulo operation in code

description: Placing of modulo operation in code


code:
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
import numpy as np

import matplotlib.colors as colors
from matplotlib.collections import PatchCollection

# Define our colormap here.
# Want red and green to be 1 at 0, and 0 at 1. Blue to be 0 at 0, and 1 at 1.
cdict = {'red':  ((0.0,1.0,1.0),
                  (1.0,0.0,0.0)),
        'green': ((0.0,1.0,1.0),
                  (1.0,0.0,0.0)),
        'blue':  ((0.0,0.0,0.0),
                  (1.0,1.0,1.0))
        }
# Use that dictionary to define the Linear SegmentedColormap
YlBu = colors.LinearSegmentedColormap('YlBu',cdict)

# Create figure
fig,ax = plt.subplots(1)

# Set the aspect ratio
ax.set_aspect('equal')

# We will populate these lists as we loop over our ellipses
ellipses = []
fluxes = []

for i in range(9):

    # Use i as a dummy value for our flux
    flux = float(i)

    # Store the fluxes. You have this already in your data array
    fluxes.append(flux)

    # Angle is in radians
    angle = float(i) * 45.

    # Create the ellipse patch. Don't add to the axes yet
    ell = Ellipse(xy=(i,2.), width=0.8, height=0.2, angle=angle)

    # Just add it to this list
    ellipses.append(ell)

# Now, create a patch collection from the ellipses.
# Turn off facecolor, and set the colormap to the one we created earlier
pc = PatchCollection(ellipses,False,lw=3,cmap=YlBu,facecolor='None')

# Set the color array here.
pc.set_array(np.array(fluxes))

# Now we add the collection to the axes
ax.add_collection(pc)

# And create a colorbar
fig.colorbar(pc,orientation='horizontal')

# Set the axes limits
ax.set_xlim(-1,9)
ax.set_ylim(0,4)

plt.show()

rawDescription: Edgecolor of Ellipse as a function of a third variable


code:
from operator import itemgetter
import time
import timeit
import matplotlib.pyplot as plt

def f1():
   return [x[0] for x in G]

def f1t():
   return tuple([x[0] for x in G])

def f2():
   return tuple([x for x in map(itemgetter(0), G)])

def f3():
    return tuple([x for x, y, z in G])

def f4():
    return tuple(list(zip(*G))[0])

def f6():
    t0,t1,t2=zip(*G)
    return t0

n=100
r=(5,35)
results={f1:[],f1t:[],f2:[],f3:[],f4:[],f6:[]}
for c in range(*r):
    G=[range(3) for i in range(c)]
    for f in results.keys():
        t=timeit.timeit(f,number=n)
        results[f].append(float(n)/t)

for f,res in sorted(results.items(),key=itemgetter(1),reverse=True):
    if f.__name__ in ['f6','f1','f1t']:
        plt.plot(res, label=f.__name__,linewidth=2.5)
    else:
        plt.plot(res, label=f.__name__,linewidth=.5)

plt.ylabel('rate/sec')
plt.xlabel('data size => {}'.format(r))
plt.legend(loc='upper right')
plt.show()

rawDescription: Best way to get the nth element of each tuple from a list of tuples in Python

description: Get the nth element of each tuple from a list of tuples in Python


code:
df = df.sort(['id','dates'])
df

rawDescription: Pandas temporal cumulative sum by group

description: Pandas temporal cumulative sum by group


code:
list = file_in.readlines()
list2 = []
string =""
i = 0

while i < len(list):
   ## remove any leading or trailing white space then split on ' '
   line_arr = list[i].lstrip().rstrip().split(' ')

rawDescription: Reading records spread across multiple input lines in Python


code:
import sys
import pydoc

def output_help_to_file(filepath, request):
    f = file(filepath, 'w')
    sys.stdout = f
    pydoc.help(request)
    f.close()
    sys.stdout = sys.__stdout__
    return

rawDescription: How do I export the output of Python's built-in help() function

description: Export the output of Python's built-in help() function


code:
def logged_apply(g, func, *args, **kwargs):
    step_percentage = 100. / len(g)
    import sys
    sys.stdout.write('apply progress:   0%')
    sys.stdout.flush()

    def logging_decorator(func):
        def wrapper(*args, **kwargs):
            progress = wrapper.count * step_percentage
            sys.stdout.write('\033[D \033[D' * 4 + format(progress, '3.0f') + '%')
            sys.stdout.flush()
            wrapper.count += 1
            return func(*args, **kwargs)
        wrapper.count = 0
        return wrapper

    logged_func = logging_decorator(func)
    res = g.apply(logged_func, *args, **kwargs)
    sys.stdout.write('\033[D \033[D' * 4 + format(100., '3.0f') + '%' + '\n')
    sys.stdout.flush()
    return res

rawDescription: Progress indicator during pandas operations (python)


code:
class NodeClass(Base):
    __tablename__ = 'nodes_table'
    node_id = Column(Integer, primary_key=True)

    left_id = Column(Integer, ForeignKey('nodes_table.node_id'))
    right_id = Column(Integer, ForeignKey('nodes_table.node_id'))

    left = relationship('NodeClass', primaryjoin = ('NodeClass.left_id == NodeClass.node_id'), use_list=False)
    right = relationship('NodeClass', primaryjoin = ('NodeClass.right_id == NodeClass.node_id'), use_list=False)

rawDescription: Using SQLAlchemy with multiple self-referential foreign keys


code:
elems = soup.find_all(True, class_='template_title',
                      height='50', valign='bottom', width='535')

rawDescription: Python 3 - Get text from tag in beautifulSoup


code: itertools.takewhile(lambda x: x < 10, primes())

rawDescription: Terminating generator expression

description: Terminating generator expression


rawDescription: Detect duplicates and create summarised rows


code:
def addedge(self, fro, to):
    self.verts[fro-1].addneighbor(to)
    self.verts[to-1].addneighbor(fro)

rawDescription: Object details don't get passed into another object pointer [Python 3]


code:
s = "It's not safe to go alone. Take this."
if 'safe' in s:
    print('The message is safe.')

rawDescription: How to programmatically detect and respond to a key word(s) in chat messages

description: Programmatically detect and respond to a key word(s) in chat messages


code:
import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("ip address", username="user_name", password="password", port=1234)

ssh.exec_command('your command')

rawDescription: Run linux commands from windows in python script


code: np.tensordot(X,tensor, axes=([1],[0]))

rawDescription: Numpy tensor: Tensordot over frontal slices of tensor


code: [getattr(RULES, attr) for attr in dir(fules) if all_caps.match(attr)]

rawDescription: How to get all the attributes of a class as a list in python

description: Get all the attributes of a class as a list in python


code:
def add_matrices(a,b):
    return listmatrixMap(add, a, b)

rawDescription: Add two matrices in python

description: Add two matrices in python


code: df['Datetime'] = pd.to_datetime(df.Date + ' ' + df.Time)

rawDescription: Select CONSECUTIVE rows from a DataFrame based on values in a column in Pandas with Groupby


code:
dic={gene:{iso:exon.split(',')} for gene, iso, exon in zip(Genes, Isoforms, ExonPos)}
dic

rawDescription: Nested dictionary - python

description: Nested dictionary - python


code:
a,b,c
d,e,f

rawDescription: PyQt4 table for inserting a table from the clipboard - tableWidget?


code: g.plot(one, two, three)

rawDescription: gnuplot.py - plotting time vs distance graph - multiple lines

description: Gnuplot.py - plotting time vs distance graph - multiple lines


rawDescription: Embedding python in multithreaded C application


rawDescription: Filter Pyspark dataframe column with None value


code:
def add(n):
    yield n
    for m in add(n+1):
        yield m

rawDescription: Python: is it possible to mix generator and a recursive function?


code:
import inspect

def numargs(func):
    args, varargs, keywords, defaults = inspect.getargspec(func)
    return len(args)

rawDescription: Python: DEAP: programatically handle number of func parameters


code:
from collections import Counter
numstring = "1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2"
numcount = Counter(numstring.split(','))

rawDescription: python - Count number of occurences of each number

description: Python - Count number of occurences of each number


code:
for _ in range(122):
    spamreader.next()
for row in spamreader:
    ...

rawDescription: Is it possible to read from a specific csv line?


code:
from sqlalchemy import create_engine, ForeignKey, Column, String, Integer, Sequence, Table
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

association_table = Table('associations', Base.metadata,
    Column('parent_id', Integer, ForeignKey('parents.id')),
    Column('tag_id', Integer, ForeignKey('tags.id')),
)

class Tag(Base):
    __tablename__ = 'tags'
    id = Column(Integer, Sequence('tag_id_seq'), primary_key=True)
    name = Column(String)

class Parent(Base):
    __tablename__ = 'parents'
    id = Column(Integer, Sequence('parent_id_seq'), primary_key=True)
    tags = relationship('Tag', secondary=association_table, backref='parents')

class Alice(Parent):
    __tablename__ = 'alices'
    __mapper_args__ = {'polymorphic_identity': 'alice'}
    alice_id = Column(Integer, ForeignKey('parents.id'), primary_key=True)

class Bob(Parent):
    __tablename__ = 'bobs'
    __mapper_args__ = {'polymorphic_identity': 'bob'}
    bob_id = Column(Integer, ForeignKey('parents.id'), primary_key=True)

engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

tag_a = Tag(name='a')
tag_b = Tag(name='b')
tag_c = Tag(name='c')
session.add(tag_a)
session.add(tag_b)
session.add(tag_c)
session.commit()
session.add(Alice(tags=[tag_a]))
session.add(Bob(tags=[tag_b]))
session.commit()

for tag in session.query(Tag).\
        filter(Tag.parents.any(Parent.id == Alice.alice_id)).\
        all():
    print(tag.name)

rawDescription: Sqlalchemy: Querying on m2m relations for polymorphic classes


code:
class ScreenButton(Button):
    screenmanager = ObjectProperty()
    def on_press(self, *args):
        super(ScreenButton, self).on_press(*args)
        self.screenmanager.current = 'whatever'

rawDescription: Kivy: Changing screens in screen manager with an on_press event


code:
indices_per_word = {}
for index, word in enumerate(listWords):
    indices_per_word.setdefault(word, []).append(index)

rawDescription: Find positon of words in list

description: Find positon of words in list


code:
def attack(self, prey_list):
    d_list = []

    for prey in prey_list:
        distX = self.rect.x - prey.rect.x
        distY = self.rect.y - prey.rect.y
        d = distX*distX+distY*distY
        d_list.append(d)

    shortest_distance = min(d_list)

rawDescription: Boids predator and obstacle behavior

description: Boids predator and obstacle behavior


code: element

rawDescription: Iterate over nested lists and dictionaries


code:
def gen_diff(A, B):
    if len(A) != len(B):
        raise IndexError('lists not of same length')
    for i in range(len(A)):
        if A[i] == B[i]:
            yield (True, i)
        else:
            yield (False, i)

rawDescription: Checking whether list in a dictionary is the same as another list?


code:
def max_temp(data):
    maximum = max(data, key=lambda e: e[1])[1]
    return maximum, [e[0] for e in data if e[1] == maximum]

rawDescription: All instances of maximum

description: All instances of maximum


rawDescription: Create a new array from numpy array based on the conditions from a list


code:
# Python 2 and 3
s = b'This must be a byte-string'

rawDescription: Py2/3 compatibility for string input to dll used with ctypes


code:
orders_df['Value'] = orders_df.Prices * orders_df.Amount * orders_df.C
orders_df   # The resulting dataframe

rawDescription: I want to multiply two columns in a pandas DataFrame and add the result into a new column


code:
blacklisted = ('foo.com', 'bar.com', 'sub.baz.net')
email_bad = 'x@sub.baz.net'
email_bad.endswith(blacklisted)
email_good = 'x@good.baz.net'
email_good.endswith(blacklisted)

rawDescription: Best way to filter out emails and domains in python

description: Filter out emails and domains in python


code:
loops = [[2,5,3], [5,3,2], [7,8,6,9]]
set(tuple(canonicalize(loop)) for loop in loops)

rawDescription: Removing similar, but not identical, lists from a list of lists in python


code:
from kivy.uix.widget import Widget
from kivy.app import App

class MyWidget(Widget):
    def dostuff(self, *args):
        print(args)

class MyApp(App):

    def build(self):
        return MyWidget()

MyApp().run()

rawDescription: Can someone tell me where I'm going wrong with this structure?


code: totalResults = globFolder(path1) + globFolder(path2)

rawDescription: Python - Can glob be used multiple times?


code:
with open(filename) as f_in:
    lines = (line.rstrip() for line in f_in)
    lines = list(line for line in lines if line) # Non-blank lines in a list

rawDescription: Python: Easiest way to ignore blank lines when reading a file


code:
import json
d = json.JSONDecoder()
my_string = 'key="{"foo":"bar"}"more_gibberish'
d.scan_once(my_string, 5)
my_string[18:]

rawDescription: In python, is there a way to extract a embedded json string?


code:
class Parent(object):
    def __init__(self):
        pass

    def parent_method(self):
        print('parent')

    @classmethod
    def parent_class_method(self):
        print('parent class method')

class Child(Parent):
    def __init__(self):
        pass

    def child_method(self):
        print('child')

    @classmethod
    def child_class_method(self):
        print('child class method')

def is_inherited_instance_method(test_object, method_name):
    """
    Gets the super object and looks up for it's method.
    If the child has `method_name` atribute and parent doesn't,
    then method is new.
    """

    super_object = super(test_object.__class__, test_object)
    if hasattr(test_object, method_name) and not hasattr(super_object, method_name):
        # You can add extra checks, such as: callable() ...
        print('it is a new method: %s' % method_name)
    else:
        print('method is not new: %s' % method_name)

def is_inherited_class_method(test_cls, method_name):
    """ Does the same but only with Classes. """

    super_cls = super(test_cls, test_cls)
    if hasattr(test_cls, method_name) and not hasattr(super_cls, method_name):
        # You can add extra checks, such as: callable() ...
        print('it is a new class method: %s' % method_name)
    else:
        print('class method is not new: %s' % method_name)

parent = Parent()
child = Child()

is_inherited_instance_method(parent, 'parent_method')
is_inherited_instance_method(child, 'parent_method')
is_inherited_instance_method(child, 'child_method')

is_inherited_class_method(Parent, 'parent_class_method')
is_inherited_class_method(Child, 'parent_class_method')
is_inherited_class_method(Child, 'child_class_method')

rawDescription: Python: Detect if a class method is redefined/overloaded from the C API


code:
# String to hex split by space
def str2hex(string):
    return ' '.join('%02x' % ord(b) for b in string)

class XStrLenField(scapy.fields.StrLenField):

    def i2repr(self, pkt, x):
        return str2hex(scapy.fields.StrLenField.i2m(self, pkt, x))

rawDescription: Working with LenFields in ScaPy

description: Working with LenFields in ScaPy


code: app = SharedDataSSIMiddleware(app, exports={'/foo': 'path'})

rawDescription: How to change response and content-length in uwsgi middleware?

description: Change response and content-length in uwsgi middleware


code:
r = requests.head(url, headers=headers, timeout=3, allow_redirects=True)
r.url
r.history

rawDescription: Detect URLs changes in python

description: Detect URLs changes in python


rawDescription: scipy and preserving mat file (.mat matlab data file) structure

description: Scipy and preserving mat file (.mat matlab data file) structure


code:
a_list = processed.items()
a_dict = dict(a_list)

rawDescription: Consolidating row data from DB into a list of dicts


rawDescription: Jenkins-cli - help required to get list of builds in the job


code:
def setDatabase(self, nameDatabase):
    self.database = QSqlDatabase.addDatabase("QSQLITE")
    self.database.setDatabaseName(nameDatabase)

    return self.database.open()

def setTable(self, nameTable):
    self.model = sqlTableModel(self)
    self.model.setEditStrategy(QSqlTableModel.OnManualSubmit)
    self.model.setTable(nameTable)
    self.model.select()

    self.view.setModel(self.model)

def saveTable(self):
    if self.model.submitAll():
        return True

    self.model.database().rollback()
    return False

rawDescription: PyQt - QTableView doesn't respond dataChanged signal?


code: someWidget.valueChanged.connect(lambda v: setattr(player, 'health', v))

rawDescription: How do I obtain the reference of a getter/setter method created through @property in Python?

description: Obtain the reference of a getter/setter method created through @property in Python


rawDescription: Adding certain numbers together in a string/list then turning then into letters


code:
chars[2:] + chars[:2]

chars[-2:] + chars[:-2]

rawDescription: Python: How to move forward or backward together in String printable


rawDescription: Python: compare an array element-wise with a float


code:
import StringIO
logfile = StringIO.StringIO(log)

rawDescription: Python/MySQLdb import from CSV with data encapsulation


code:
cursor = connection.cursor()
cursor.execute(
     "SELECT COUNT(0) FROM `mymodel_table` "
     "GROUP BY `mydatetimefield`;"
)
counts = cursor.fetchall()

rawDescription: How to populate a list with items.count() from a queryset sorted by a datetime field

description: Populate a list with items.count() from a queryset sorted by a datetime field


rawDescription: How to know if a member of a class is a method?

description: Know if a member of a class is a method


code:
import webapp2
import views

maintenance_mode = False

# These routes need to be always available
routes = [
    # Static pages
    (r'/(|about|contact|help|faq|terms|privacy|users|methods)',
     views.Static),
    # Other routes that should always be available here
]

if maintenance_mode:
    routes += [(r'/.*', views.Maintenance)] # Displays a maintenance message
    application = webapp2.WSGIApplication(routes)

else:
    routes += [
        # Routes that are not available in maintenance mode
    ]
    application = webapp2.WSGIApplication(routes)

rawDescription: GAE/P - schedule downtime for maintenance


code:
def chunks(l, n):
    """ Yield successive n-sized chunks from l. """
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

rawDescription: converting 3d lists to 2d lists in python

description: Converting 3d lists to 2d lists in python


code:
from nanomsg import Socket, PUB

s = Socket(PUB)
s.connect('tcp://localhost:8080')
s.send('topicMessage')

rawDescription: Publish-Subscribe and a Message bus Python


code:
import example
game = example.GameObject()
component = game.add_component(example.CameraComponent)
assert(isinstance(component, example.CameraComponent))
try:
    game.add_component(component) # throws Boost.Python.ArgumentError
    assert(False)
except TypeError:
    assert(True)

rawDescription: Python C API - How to construct object from PyObject


rawDescription: nbconvert markdown not searching predefined images

description: Nbconvert markdown not searching predefined images


code:
a = [1, 2, 1, 1, 3, 4, 2]
b = [1, 3, 4]

# After the set operations c would be [2]
# rather than the possibly desired [2, 2]

rawDescription: Compare with each other, items inside two lists, in a for loop?


code:
def outputList(inputlist, datafile, outputfile):
    d = {}
    with open(datafile, 'r') as f:
        for line in f:
            line = line.lstrip()
            key = line.split(',')[0]
            d[key] = line
    with open(outputfile, 'w') as f:
        for key in inputlist:
            f.write(d[key])

rawDescription: Return lines from file in order of a list


code:
with open("test_m.rdb") as inf:
    results = [(i[2],i[4]) for i in (line.split() for line in inf)]

result_string = ",".join(str(res) for res in results)

rawDescription: Python String Formatting, need to continuously add to a string


code:
def strip_empty_lines(s):
    lines = s.splitlines()
    while lines and not lines[0].strip():
        lines.pop(0)
    while lines and not lines[-1].strip():
        lines.pop()
    return '\n'.join(lines)

rawDescription: python - remove empty lines from end and beginning of string

description: Python - remove empty lines from end and beginning of string


code:
@register.filter(needs_autoescape=False)
def add_color(value):
    if float(value) > 0:
        return '%s' % value
    elif float(value) < 0:
        return '%s' % value
    else:
        return str(value)

rawDescription: Calculate two values and calculate difference in percentage in Django


rawDescription: Python Selenium return HTML location

description: Python Selenium return HTML location


code:
inds = np.where(a)[0]
cutoff  = inds[inds.shape[0]//2]

rawDescription: What is best way to find first half of True's in boolean numpy array?


code:
class MyClass(BaseClass):

    def my_method():
        """People see what happen because of clear names"""
        self.process_my_collection()
        self.do_other_stuff()

    def process_my_collection():
        """People see what happen because of clear names.
        They probably don't even need to read your math from
        process_my_collection_item(item) at all.
        And you make the code more flat as well.
        """
        for item in self.my_collection:
            self.process_my_collection_item(item)

    def process_my_collection_item(item):
        """The most people don't need to read these calculations every time
        since they just know it's working and tested
        but they'd like to work with methods above frequently:
        """
        if not item.numeric_property % 2:
            return
        self.my_property = item.other_property + item.age * self.my_coefficient

rawDescription: Should I use camelCase to abide by pep-8 line length?


code:
tree = lxml.etree.fromstring('''<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <name>Location history from 03/03/2012 to 03/10/2012</name>
  </Document>
</kml>''')
tree.xpath('//kml:name', namespaces={'kml': "http://www.opengis.net/kml/2.2"})

rawDescription: Python ElementTree find() not matching within kml file


code:
from django.shortcuts import render
from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout

# Create your views here.
def user(request):
    context = {}
    return render(request, 'user.html', context)

def login(request):
    context = {}
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                auth_login(request, user)
            else:
                context['error'] = 'Non active user'
        else:
            context['error'] = 'Mauvais nom d\'utilisateur ou mot de passe'
    else:
        context['error'] = ''
    return render(request, 'user.html', context)

def logout(request):
    context = {}
    auth_logout(request)
    return render(request, 'user.html', context)

rawDescription: Django why can't I authenticate a user?

description: Django why can't I authenticate a user


code:
template_response = super(
    ExtendedUserAdmin, self).render_change_form(*args, **kwargs)

rawDescription: How to wrap long super() call to be compliant with PEP-8?

description: Wrap long super() call to be compliant with PEP-8