code:
string_list = []

for el1 in file_list:
    for el2 in inner_dict.items():
        string_list.append(", ".join([el1, str(el2[0]), el2[1]]))

print(string_list)

rawDescription: Use .join() to manipulate inner dictionary elements of a nested dictionary


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

NPOINTS = 1000

np.random.seed(101)
lat = np.random.random(NPOINTS)*8+44
lon = np.random.random(NPOINTS)*100-50
counts = np.random.randint(0,1000,NPOINTS)

plt.subplot(211)
plt.scatter(lat, lon, c=counts)
plt.colorbar()
plt.subplot(212)
plt.scatter(lat, lon, s=counts)

plt.savefig('scatter_example.png')
plt.show()

rawDescription: Python: How to plot a heatmap for coordinates with different color intensity or different radius of circles?


code:
def updatesomethings(s):
    s.a, s.b, s.c = s.a + s.c, s.b - s.a, s.c * s.b

rawDescription: Python importing class attributes into method local namespace


code:
totalMean = [98,91,89,82,79,67,58,52,51,49,33,12]
list12_33 = []
list49_52 = []
list58_67 = []
list79_98 = []

for tup in totalMean:
    if tup >= 12 and tup <=33:
        list12_33.append(tup)
    elif tup >= 49 and tup <=52:
        list49_52.append(tup)
    elif tup >= 58 and tup <=67:
        list58_67.append(tup)
    elif tup >= 79 and tup <=98:
        list79_98.append(tup)

print [list12_33, list49_52, list58_67, list79_98]

rawDescription: create list using if and else condition

description: Create list using if and else condition


code:
from scrapy.spider import BaseSpider
from scrapy.selector import Selector
from craig.items import CraigItem
from scrapy.http import Request

class CraigSpiderSpider(BaseSpider):
    name = "craig_spider"
    allowed_domains = ["randstad.nl"]
    start_urls = (
        "http://www.randstad.nl/mwp2/faces/baanZoeken?afstand=10&pagina=1&_adf.ctrl-state=sb0riset7_4&sc=0&filters=vakgebied!5626&_afrLoop=",
        )

    def parse(self, response):
        sel = Selector(response)

        for link in sel.xpath("//a[contains(@class, 'outer-read-more-link')]/@href").extract():
            yield Request(link, callback=self.parse)

        text_list = sel.xpath('//div[@id="basePage:page:twoColumn:r2:0:functieOmschrijvingPanel::content"]/text()').extract()
        if text_list:
            text = '\n'.join(text_list)
            item = CraigItem()
            item['link'] = response.url
            item['title'] = text
            yield item

rawDescription: Extract text from an extracted new page from main page


code:
import wx

class MyForm(wx.Frame):
   def __init__(self):
        wx.Frame.__init__(self, None, size=(400,400))
        self.Bind(wx.EVT_SIZE, lambda *args: 0) # <--------
        self.panel2=wx.Panel(parent=self,
                             size=(200,200),
                             pos=(200,0),
                             style=wx.BORDER)

app = wx.App(False)
frame = MyForm().Show()
app.MainLoop()

rawDescription: Can't put the panel at the specified position on wxpython


rawDescription: List a specific position in each list within a list (python)


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

data = np.arange(100).reshape(10, 10).astype(float)

cmap = plt.cm.gray
cmap.set_bad((1, 0, 0, 1))

# Set the diagonal to NaN
data[range(10), range(10)] = np.nan

plt.imshow(data, cmap=cmap, interpolation='nearest')
plt.colorbar()
plt.show()

rawDescription: Changing colours of pixels of plt.imshow() image


code: zipped_list = zip(first_list, second_list, third_list, fourth_list)

rawDescription: How can I fill the table? (Python, Django)

description: Fill the table? (Python, Django)


code:
#create graph
G = nx.MultiGraph()

#read in strings from csv
testfile = 'C:…file.txt'

with open(testfile, "r") as f:
    line = f.readline
    f = (i for i in f if '\t' in i.rstrip())
    for line in f:
        customerID, path = line.rstrip().split("\t")
        path2 =  path.rstrip("\\").rstrip("}").split(",")
        pathTuple = tuple(int(x) for x in path2 )
        G.add_path([pathTuple[:i+1] for i in range(0, len(pathTuple))])

        for level, node in enumerate(path):
            counts[level][node]+=1

rawDescription: Node frequency using networkx

description: Node frequency using networkx


code:
import matplotlib.pyplot as plt
import pandas as pd
x = [[1.2, 2.3, 3.0, 4.5],
     [1.1, 2.2, 2.9, 5.0]]
df = pd.DataFrame(x, index=['Age of pregnant women', 'Age of pregnant men'])

df.T.boxplot()
plt.subplots_adjust(bottom=0.25)
plt.xticks(rotation=25)
plt.show()

rawDescription: Horizontal box plots in matplotlib/Pandas


code:
# Python 3.0+
from abc import ABCMeta, abstractmethod
class Abstract(metaclass=ABCMeta):
    @abstractmethod
    def foo(self):
        pass

rawDescription: Is it possible to make abstract classes in python?


code:
class ConstrainedRandom(object):
    def __init__(self, ranges=None, target=None, seed=None):
        self._rand = random.Random(seed)
        if ranges != None: self.setrange(ranges)
        if target != None: self.settarget(target)

    def setrange(self, ranges):
        self._ranges = ranges
        self._nranges = len(self._ranges)
        self._nmin, self._nmax = zip(*self._ranges)
        self._minsum = sum(self._nmin)
        self._maxsum = sum(self._nmax)
        self._zmax = [y-x for x,y in self._ranges]
        self._rconv = self._nranges * [None]
        self._rconv[-1] = pulse(self._zmax[-1])
        for k in range(self._nranges-1, 0, -1):
            self._rconv[k-1] = stepconv(self._rconv[k], self._zmax[k-1])

    def settarget(self, target):
        self._target = target

    def next(self, target=None):
        k = target if target != None else self._target
        k = k - self._minsum;
        N = self._rconv[0][k]
        seq = self._rand.randint(0,N-1)
        result = self._nranges*[0]
        for i in range(len(result)-1):
            cv = self._rconv[i+1]
            r_i = 0
            while k >= len(cv):
                r_i += 1
                k -= 1
            while cv[k] <= seq:
                seq -= cv[k]
                r_i += 1
                k -= 1
            result[i] = r_i
        result[-1] = k # t
        return [x+y for x,y in zip(result, self._nmin)]

    # end clss ConstrainedRandom

rawDescription: Create constrained random numbers?

description: Create constrained random numbers


code: '\n'.join(iter(raw_input, sentinel))

rawDescription: Raw input across multiple lines in Python


code:
f.seek(0)
next(islice(f, 7, None))

rawDescription: What substitutes xreadlines() in Python 3?


code:
def possible_solution(remaining, sol=None):
    sol = sol or []
    if not remaining:
        yield sol
    else:
        for i, candidate in enumerate(remaining):
            if not sol or abs(sol[-1] - candidate) != 1:
                new_sol = sol + [candidate]
                new_remaining = remaining[:i] + remaining[i+1:]
                for x in possible_solution(new_remaining, new_sol):
                    yield x

rawDescription: arrangements backtracking python

description: Arrangements backtracking python


code: [''.join(map(str, i)) for i in itertools.product([0,1], repeat=4)]

rawDescription: How to generate combination of fix length strings using a set of characters?

description: Generate combination of fix length strings using a set of characters


code:
subprocess.check_call(["open", "-a", os.path.join(path, "blender.app"),
                       "Import_mhx.blend"])

rawDescription: Open a file from a specific program from python


code: match = Match()

rawDescription: python: is there anyway to initialize a variable only one time?

description: Python: is there anyway to initialize a variable only one time


code: my_var = session['somekey']

rawDescription: How to use beaker with GAE

description: Use beaker with GAE


code:
for x in reflist:
    for y in x:
        for z in range(0, 41):
            y.append([])

rawDescription: For loops in nested list with variable numbers of indices


code:
for ii in xrange(1, size):
    lst_f.append( (lambda ii_tmp: lambda x: np.dot(matA[ii_tmp], x))(ii) )

rawDescription: Why does a lambda function change its behavior from in the function that generates it to the main?


rawDescription: Find what is in a PYC file

description: Find what is in a PYC file


rawDescription: Comparing List and get indices in python


code:
def apply_function(particle, *args, **kwargs):
    for char, function in char_functions:
        if char in particle:
            function(*args, **kwargs)
            break

rawDescription: Expressions in a dictionary mapping

description: Expressions in a dictionary mapping


code:
foo = ["neg * , This is a sentence","pos * , This is another sentence"]
[p.split('*', 1) for p in foo]

rawDescription: Split line into category and text

description: Split line into category and text


code:
new_dict = {}
for k, v in original_dict.iteritems():
    k_excludes = excludes.get(k, {})
    new_dict[k] = {sub_k:sub_v for sub_k, sub_v in v.iteritems()
                   if sub_k not in k_excludes}

rawDescription: Python dictionary comprehension with nested for


code: codes = [elem.encode() for elem in ast.literal_eval(','.join(a))]

rawDescription: python list items & convert language codes to names

description: Python list items & convert language codes to names


rawDescription: Multiplying across in a numpy array

description: Multiplying across in a numpy array


rawDescription: django shared library/classes

description: Django shared library/classes


code:
from random import randrange

data_set = [randrange(100, 1000) for x in range(5)]
required_amount = 20
special_number = sum(data_set) // required_amount

print("Data set:")
print(data_set)
print("Special number:")
print(special_number)

# divmod() returns a pair of numbers, split them into quotients and remainders
pairs = [divmod(x, special_number) for x in data_set]
proportional_data_set = [x[0] for x in pairs]
remainder = [x[1] for x in pairs]

print
print("Proportional data set before adjusting:")
print(proportional_data_set), "=", sum(proportional_data_set)
print("Remainders:")
print(remainder)

while sum(proportional_data_set) < required_amount:
    i = remainder.index(max(remainder))    # index of the highest remainder
    proportional_data_set[i] += 1          # add another marble to this index
    remainder[i] = -1                      # don't use this remainder again

print
print("Proportional data set after adjusting:")
print(proportional_data_set), "=", sum(proportional_data_set)
print("Remainders:")
print(remainder)

rawDescription: Proportional rounding error

description: Proportional rounding error


code: Followers: 10623

rawDescription: Grabbing a specific value from a webpage using LXML


code: stats = [summ for summ in data['playerStatSummaries'] if summ['playerStatSummaryType'] == 'RankedSolo5x5']

rawDescription: Python 3: Iterating over a dictionary

description: Python 3: Iterating over a dictionary


code:
def form_valid(self, form):
    user_form = UserCreationForm(self.request.POST)
    if user_form.is_valid():
        user = user_form.save()
        teacher = form.save(commit=False)
        teacher.user_id = user.id
        teacher.save()
        return HttpResponseRedirect(self.get_success_url())

rawDescription: Django User Model one-to-one with other model and Forms


code:
# Declare which code you want to delete.
# This can be further improved by being a parameter
# or read from outside the script.
code = 5
removed_lines = 0
f = open("input.txt","r+")
lines = f.readlines()
f.seek(0)
for line in lines:
    # Writes to the file all the lines except for those that
    # begin with the code declared above.
    if not line.startswith(str(code)):
        f.write(line)
    else:
        print("removed line %s" % line)
        removed_lines += 1
f.truncate()
f.close()
print("%d lines were removed" % removed_lines)

rawDescription: Python - Remove entire Line in file using specific data


code:
import itertools
from math import fsum
from operator import itemgetter

mylist = [...]

summed = [(name, num, fsum(float(x.replace(',', '.')) for x in g))
          for (name, num), g in itertools.groupby(mylist, key=itemgetter(0, 1))]

rawDescription: Python list sum elements

description: Python list sum elements


code:
legal = []
illegal = []
for item in submission:
    if item in permissible:
        legal.append(item)
    else:
        illegal.append(item)

rawDescription: check that a list contains only elements from a given "permissible" list

description: Check that a list contains only elements from a given "permissible" list


code:
def sums(large_array):
    return large_array.reshape((-1, 1)) + large_array.reshape((1, -1))

rawDescription: Numpy with Combinatoric generators: How does one speed up Combinations?


code: _Element_Py = Element

rawDescription: Inherit or mock pythons etree.ElementTree.Element possible?


code:
class RootListSerializer(ListSerializer):
    def to_representation(self, instance):
        for i in instance:
            i.foo = 'foo'
        ...

class RootSerializer(Serializer):
    class Meta(object):
        list_serializer_class = RootListSerializer

rawDescription: Accessing serializer instances in nested serializer's field


code:
@somedec(30.0, 'foobarbaz')
def somefn(a, b, c):
    return a + b + c

@somedec(15.0, 'quxjinzop')
def otherfn(d, e, f):
    return d - e - f

rawDescription: python wrapper function taking arguments inside decorator

description: Python wrapper function taking arguments inside decorator


code:
result = df2.swaplevel(0, 1)
result.columns = ['CalciumConc_mgL', 'CalciumConc_mgL_lagged_12m']

rawDescription: Use Python/Pandas to Match Sample Pairs Yearly Data


code: href="/product/"

rawDescription: how to Pass variable in link to the django view


code:
classs = input("Class [1, 2 or 3] -  ")
l = []

if classs =='1':
    name = input("What is your name? -  ")

    datafile = '1.txt'
    found = False

    with open(datafile, 'r') as f:
        data = f.readlines()
        for line in data:
            if name in line:
                print(line)
                l.append(int(line.split()[2]))
                found = True
        if found == False:
            print("False")

rawDescription: Python HELP | Create averages from a list from .txt file?


code:
class myClass(object):
  def doAuth(self):
    self.token = callAuthProcedure()

rawDescription: Python: Store Token in Memory

description: Python: Store Token in Memory


code: pandas.tools.pivot.pivot_table(your_dataframe, values='value', index='name', columns=['type', 'date'], aggfunc='sum')

rawDescription: pandas pivot dataframe to 3d data

description: Pandas pivot dataframe to 3d data


code:
level_0[level_0.str.startswith('Unnamed: ')] = None
level_0 = level_0.fillna(method = 'ffill')

rawDescription: How can I read in a csv file as a MultiIndexed DataFrame when the spanning column header isn't repeated?

description: Read in a csv file as a MultiIndexed DataFrame when the spanning column header isn't repeated


code:
if os.path.isfile(file_path): # or some other condition
    delete = True             # Standard action: delete
    try:
        with open(file_path) as infile:
            if "dollar" in infile.read(): # don't delete if "dollar" is found
                delete = False
    except IOError:
        print("Could not access file {}".format(file_path))
    if delete:
        os.unlink(file_path)

rawDescription: Deleting specific text files

description: Deleting specific text files


code: bet = bet[1:-1] # "slice" from second to penultimate

rawDescription: How to change a list in a for loop? Labouchere in Python

description: Change a list in a for loop? Labouchere in Python


rawDescription: Issue with using the chr() method to add \x to characters in a list


code: count_all = lambda string, sub: sum(string[i:i+len(sub)] == sub for i in range(len(string) - len(sub) + 1))

rawDescription: Does Python have a string contains how many substring method, allowing for overlap?


code:
def decorate(f):
    def wrapped_function():
        print("Function is being called")
        f()
        print("Function call is finished")
    return wrapped_function

@decorate
def my_function():
    print("Hello world")

my_function()

rawDescription: Python Closures Example Code

description: Python Closures Example Code


code:
import random
rng = random.Random()
i = 0
result =[]

while i <4:
    bd =list(range(4))
    rng.shuffle(bd)
    if bd not in result:
        # Use [:] to create a slice of bd which actually contains the whole list
        result.append(bd[:])
    i +=1
print(result)

rawDescription: Python Creating a nested list with random module


code:
class BigIntegerField(IntegerField):
    empty_strings_allowed = False
    description = _("Big (8 byte) integer")
    MAX_BIGINT = 9223372036854775807

    def get_internal_type(self):
        return "BigIntegerField"

    def formfield(self, **kwargs):
        defaults = {'min_value': -BigIntegerField.MAX_BIGINT - 1,
                    'max_value': BigIntegerField.MAX_BIGINT}
        defaults.update(kwargs)
        return super(BigIntegerField, self).formfield(**defaults)

rawDescription: Can the Django ORM store an unsigned 64-bit integer (aka ulong64 or uint64) in a reliably backend-agnostic manner?


rawDescription: Python : what would be the ouput of range(x,y) if x>y


code:
pick(5)
pick(0)
pick(3)

rawDescription: Generate two random strings with dash in between


rawDescription: Store NumPy Row and Column Headers

description: Store NumPy Row and Column Headers


code: ('AAA') if (True) else (('BBB' + 'CCC') if (True) else ('DDD'))

rawDescription: A issue of concatenating two strings with if...else statement


code:
version = '1.3.3'
lowercase=True

rawDescription: how to make pandas.read_sql() not convert all headers to lower case

description: Make pandas.read_sql() not convert all headers to lower case


code:
1.0
One
1,Two
1,Two,Three,4.5
One,2,3.4,Five,6

rawDescription: Python save arbitrarily nested list to CSV


rawDescription: PyBBM in Django static content

description: PyBBM in Django static content


rawDescription: i am trying send email using web2py with gmail and using smtp setting i have attached all code

description: I am trying send email using web2py with gmail and using smtp setting i have attached all code


code:
from itertools import zip_longest # izip_longest python2

bits = [1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1,1,0]
it = iter(map(str, bits))

print( [int("".join(sli), 2) for sli in izip_longest(*iter([it] * 8),fillvalue="")])
[149, 107, 231, 2] # using just zip would be  [149, 107, 231]

rawDescription: Python bit list to byte list

description: Python bit list to byte list


code:
from traits.api import HasTraits, Range, Int

class Foo(HasTraits):
    high = Int(10)
    low = Int(1)
    bar = Range(high='high', low='low')

rawDescription: Access low and high settings of an ETS Range attribute?


code:
minimum = min(xs)
print(minimum)

rawDescription: python: How to compare elements within one list

description: Python: How to compare elements within one list


code: write(a)

rawDescription: Print tree with indentations

description: Print tree with indentations


code:
bar1(foo())  # Receives a single tuple-valued argument
bar1(*foo()) # Receives 3 integer arguments
bar2(foo())  # Receives a single tuple-valued argument
bar2(*foo()) # Receives 3 arguments, but only expected 1!

rawDescription: Replacing Positional arguments - calling a function with or without tuple arguments


code:
#! /usr/bin/python3
import re

def makeNice(s):
    return re.subn('(#U[0-9a-f]{4})', lambda cp: chr(int(cp.groups()[0][2:],16)), s) [0]

a = '-#U2605-#U79c1-'
print(a, makeNice(a))

rawDescription: Python: Converting Unicode code point filenames to strings


code:
def f(x, y=None):
    if y is None:
        return lambda y: f(x, y)
    return 'result'

rawDescription: How to create and return a function object in a c extension module?

description: Create and return a function object in a c extension module


code:
def multikeysort(items, columns):
    from operator import itemgetter
    comparers = [((itemgetter(col[1:].strip()), -1) if col.startswith('-') else
                  (itemgetter(col.strip()), 1)) for col in columns]
    def comparer(left, right):
        for fn, mult in comparers:
            result = cmp(fn(left), fn(right))
            if result:
                return mult * result
        else:
            return 0
    return sorted(items, cmp=comparer)

rawDescription: Python sorting list of dictionaries by multiple keys


code:
filetypecounter = {}
filetypecounter[filetype] = filetypecounter.get(filetype, 0) + 1

rawDescription: Set value in dictionary if value not there?


code:
def finishLaunching(self):
    # ...

    self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(NSDate.date(), 1.0, self, 'tick:', None, True)
    NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
    self.timer.fire()

def tick_(self, arg):
    self.menuItem.setTitle_("Tick %d!" % int(time.time()))

rawDescription: NSMenuItem + Python + Dynamic Variables

description: NSMenuItem + Python + Dynamic Variables


code:
import numpy as np

def adaptive_thresh(input_img):

    h, w = input_img.shape

    S = w/8
    s2 = S/2
    T = 15.0

    #integral img
    int_img = np.zeros_like(input_img, dtype=np.uint32)
    for col in range(w):
        for row in range(h):
            int_img[row,col] = input_img[0:row,0:col].sum()

    #output img
    out_img = np.zeros_like(input_img)

    for col in range(w):
        for row in range(h):
            #SxS region
            y0 = max(row-s2, 0)
            y1 = min(row+s2, h-1)
            x0 = max(col-s2, 0)
            x1 = min(col+s2, w-1)

            count = (y1-y0)*(x1-x0)

            sum_ = int_img[y1, x1]-int_img[y0, x1]-int_img[y1, x0]+int_img[y0, x0]

            if input_img[row, col]*count < sum_*(100.-T)/100.:
                out_img[row,col] = 0
            else:
                out_img[row,col] = 255

    return out_img

rawDescription: Bradley adaptive thresholding algorithm

description: Bradley adaptive thresholding algorithm


code:
import builtins   # __builtin__ in python2
str = builtins.str

rawDescription: Overloaded or rewritten str() function in Python


code:
if __name__ == '__main__':
    p1 = Process(target = writeFiles)
    p1.start()
    ask()

rawDescription: Raw_input inside a Python process

description: Raw_input inside a Python process


code:
data = []

for line in infoData:
    if '=' not in line:
        continue
    name, value = line.split('=')
    value, unit = re.search('([\d.]+)(\w+)', value).groups()

    data.append({'name': name.strip(), 'value': float(value), 'unit': unit})

rawDescription: Not correct regular-expression in python


code:
@Merge(foo='bar')
def test(*args, **kws):
    print *args
    print **kws

rawDescription: Merge decorator function as class

description: Merge decorator function as class


rawDescription: Python mac adress matching and processing


code:
s = pd.Series(uniq)
s.to_csv('rgdp_uniq_indstry_class.csv')

rawDescription: pandas: export ndarray to csv

description: Pandas: export ndarray to csv


code:
matrix = [[0 for i in range(400)] for k in range(400)]
with open("filename") as data:
    for row in data:
        (x, y, n) = map(int, row.split())
        matrix[x][y] = n

rawDescription: Python from matrix to simple text file

description: Python from matrix to simple text file


code:
class classmethod:
    def __init__(self, thefunc): self.f = thefunc
    def __call__(self, obj, *a, **k): return self.f(obj.__class__, *a, **k)

rawDescription: backport function modifiers to python2.1

description: Backport function modifiers to python2.1


code:
arr
unqa,ID,counts = np.unique(arr[:,0],return_inverse=True,return_counts=True)
out

rawDescription: Average entries with duplicate first element in 2D numpy array


code: [list(zip(a, p)) for p in permutations(b)]

rawDescription: Python merging two lists with all possible permutations


code: objects = manager.Manager()

rawDescription: Add django model manager code-completion to Komodo


code:
rantaplan = Person.objects.get(name='rantanplan')
tracking = Service.objects.get(name='tracking')
PersonServiceRel.objects.filter(provider=rantaplan, service=tracking)
# or
rantaplan.provided_services.filter(service=tracking)

rawDescription: What are the character limitations to Django model's related_name in a relationship?


rawDescription: Numpy - summing up a list of vectors

description: Numpy - summing up a list of vectors


code:
from kivy.storage.jsonstore import JsonStore

from os.path import join

class AppScreen(ScreenManager):
    data_dir = App().user_data_dir
    store = JsonStore(join(data_dir, 'storage.json'))
    ...
    def login(self):
        username = self.login_username.text
        password = self.login_password.text
        AppScreen.store.put('credentials', username=username, password=password)

rawDescription: Saving login screen username and password for Kivy app


code:
headers = [('content-length', '2501479'),
 ('accept-ranges', 'bytes'),
 ('vary', 'Accept-Encoding'),
 ('server', 'off'),
 ('last-modified', 'Thu, 20 Oct 2011 04:30:01 GMT'),
 ('etag', '"2c8171a-262b67-4afb368edfffc"'),
 ('date', 'Thu, 20 Oct 2011 16:01:11 GMT'),
 ('content-type', 'text/plain')]

headers = dict(headers)
int(headers['content-length'])

rawDescription: Extracting Information from a Tuple (Python)


code:
Found: 0
Found: 1
Found: 2

rawDescription: regex's multi-match?

description: Regex's multi-match


code: gsub("\\b " , text , replacement = "" , perl = T)

rawDescription: How to remove single space between text

description: Remove single space between text


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

col_labels=['G','A','T','C','C']
row_labels= ['G','T','G','C','C']
table_vals= [
    ['X','','','',''],
    ['','','X','',''],
    ['X','','','',''],
    ['','','','X','X'],
    ['','','','X','X']]
line = np.array([
    [0, 1, 2, 2, 3, 4],
    [0, 0, 1, 2, 3, 4]])
ncol = len(col_labels)
nrow = len(row_labels)

# draw grid lines
plt.plot(np.tile([0, ncol+1], (nrow+2,1)).T, np.tile(np.arange(nrow+2), (2,1)),
    'k', linewidth=3)
plt.plot(np.tile(np.arange(ncol+2), (2,1)), np.tile([0, nrow+1], (ncol+2,1)).T,
    'k', linewidth=3)

# plot labels
for icol, col in enumerate(col_labels):
    plt.text(icol + 1.5, nrow + 0.5, col, ha='center', va='center')
for irow, row in enumerate(row_labels):
    plt.text(0.5, nrow - irow - 0.5, row, ha='center', va='center')

# plot table content
for irow, row in enumerate(table_vals):
    for icol, cell in enumerate(row):
        plt.text(icol + 1.5, nrow - irow - 0.5, cell, ha='center', va='center')

# plot line
plt.plot(line[0] + 1.5, nrow - line[1] - 0.5, 'r', linewidth = 5, alpha = 0.5)

plt.axis([-0.5, ncol + 1.5, -0.5, nrow+1.5])
plt.show()

rawDescription: How to draw dynamic programming table in python

description: Draw dynamic programming table in python


code:
from itertools import chain, product, count
s = set((1, 2, 3))
test_seq = chain.from_iterable(product(s, repeat=n) for n in count(1))
zip(range(10), test_seq)

rawDescription: Calculating the Nth Sequence of Length M in Python


code: list(map(function, list_of_dicts))

rawDescription: What is more effective iterate a list and call a function or pass the list to the function


code:
# Splits the training data into training size and testing size
numtrain = int(len(documents) * 90 / 100)
# Process the documents for training data
train_set = [({i:(i in tokens) for i in word_features}, tag) for tokens,tag in documents[:numtrain]]
# Process the documents for testing data
test_set = [({i:(i in tokens) for i in word_features}, tag) for tokens,tag  in documents[numtrain:]]

rawDescription: Testing the NLTK classifier on specific file


code:
import pandas as pd
df = pd.read_csv('path/to/fixed.csv')

rawDescription: Parsing CSV file in pandas with commas in last column


code:
# Use our function to get a new version of foo with "bar" replaced by mybar
foo = monkey_patch_fn( foo, "bar", my_bar )

# Check it works
foo()

rawDescription: Does an equivalent of override exist for nested functions?


rawDescription: How to generate unique 64 bits integers from Python?

description: Generate unique 64 bits integers from Python


rawDescription: Python - Function "which" from R in Python


code:
class Foo(object):
    def __init__(self):
        self._bar = None  # Bar is an important "private" member
        self._baz = None  # As is baz
        self._fizzbuzz = 4  # Of course, you can also provide defaults here

rawDescription: Equivalent of struct members in Python (mainly for documentation and reading code)


code:
from traits.api import HasTraits, List
from traitsui.api import (
    View, ListEditor, Group, Item, CheckListEditor, Group
)

class Foo(HasTraits):
    my_list = List()
    full_list = List()

    def _full_list_default(self):
        return [str(n) for n in range(10)]

    traits_view = View(Group(Item('my_list',
                                style='custom',
                                editor=CheckListEditor(name='full_list')),
                            orientation='vertical'),
                    scrollable=True,
                    height=100)

if __name__ == '__main__':
    f = Foo()
    f.configure_traits()

rawDescription: Scrollable Group with a List using TraitsUI


code:
new_name = rename_code_object(gen, 'new_name')
new_name.__name__
new_name().__name__
new_name()

rawDescription: Changing the __name__ of a generator

description: Changing the __name__ of a generator


code: pix[(x, y)]

rawDescription: What does pix[x, y] mean in Python

description: What does pix[x, y] mean in Python


code:
target = s1 = []
s2 = []
s3 = []
for f in filenames:
    num = int(f[5:9])
    if num > 800:
        target = s2
    elif num > 1600:
        target = s3
    target.append(f)

rawDescription: globbing a range with padded 0's- python

description: Globbing a range with padded 0's- python


code:
def is_anonymous(self):
        """
        Check if the record is anonymous.
        """
        if self.kind == CursorKind.FIELD_DECL:
            return self.type.get_declaration().is_anonymous()
        return conf.lib.clang_Cursor_isAnonymous(self)

rawDescription: Finding anonymous enums with libclang

description: Finding anonymous enums with libclang


code:
from random import randint

while True:
    userChoice = raw_input("> Choose rock, paper, or scissors: ")
    computerChoice = randint(1, 101)
    if computerChoice <= 34:
        computerChoice = "rock"
    elif computerChoice <= 67:
        computerChoice = "paper"
    else:
        computerChoice = "scissors"
    print("> The computer chooses: " + str(computerChoice))
    if userChoice == computerChoice:
        print("> It's a tie! Thank you for playing!")
    askUserPlayAgain = raw_input("> Would you like to play again? Enter [yes or no]: ")
    if askUserPlayAgain.lower()[0] == "y":
        continue
    elif askUserPlayAgain.lower()[0] == "n":
        break

rawDescription: Trying to re-loop a game only if a user says to


code:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.2)
y = np.sin(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
plt.show()

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

description: Change the shape of a contour in matplotlib


code:
from collections import OrderedDict as o

things_to_evaluate = o(
    ('thing 1', lambda: Thing(property = 'a')),
    ('thing 2', lambda: Thing(property = 'b')),
    ...
    )

rawDescription: Globally Make Python Dictionaries Ordered


code:
df = pd.concat([df]*10000).reset_index(drop=True)
#print df
df1,df2,df3 = df.copy(), df.copy(), df.copy()

def a(df):
    df['new_col1'] = df['foo'].notnull()
    df['new_col2'] = np.in1d(df['bar'], 'P')
    df['new_col3'] = ~df['new_col2']
    Status =  np.in1d(df['Status'],'Approved, not yet paid')
    invertStatus = ~Status
    Current_Status = np.in1d(df['Current_Status'],'Approved, not yet paid')
    invertCurrent_Status = ~Current_Status
    df['new_col4'] = Status & invertCurrent_Status
    df['new_col5'] = Status & Current_Status
    df['new_col6'] = invertStatus & invertCurrent_Status
    #print df
    return df.groupby('id').sum()[['new_col1','new_col2','new_col3','new_col4','new_col5','new_col6']].astype(int)

def b(df):
    df['new_col1'] = df['foo'].notnull().astype(int)
    df['new_col2'] = df['bar'].factorize()[0]
    df['new_col3'] = (df['new_col2'] - 1).abs()
    df['Status'] =  df['Status'].factorize()[0]
    df['invertStatus'] = (df['Status'] - 1).abs()
    df['Current_Status'] = df['Current_Status'].factorize()[0]
    df['invertCurrent_Status'] = (df['Current_Status'] - 1).abs()

    df['new_col4'] = df['Status'] & df['invertCurrent_Status']
    df['new_col5'] = df['Status'] & df['Current_Status']
    df['new_col6'] = df['invertStatus'] & df['invertCurrent_Status']

    return df.groupby('id').sum()[['new_col1','new_col2','new_col3','new_col4','new_col5','new_col6']]

rawDescription: Pandas, long processing time of groupby and comparisons


code:
class Class(object):
    def __init__(self, num, name, input_file):
        self.name = name
        self.num = num
        self.input_file = input_file
        self.students = []
        #so far it's just an empty list

    #add methods that read in the students from a file
    #parse it for info you need
    def parse():
        #parse self.input_file for info you need
        pass

class Classes(object):
    def __init__(self, input_file):
        self.input_file = input_file
        self.all_classes = []
    #this parse function should read in from a file
    #of all classes, and instantiate a new Class
    #object and put them in self.all_classes
    #this is the class that enables you to select
    #which Class you want, and Class object should
    #have methods for calculating average, per student
    #grade etc....
    def parse():
        #parse the file to fill self.all_classes
        pass

classes = Classes(input_file="all_classes.txt")
#this should return a Classes object named classes
#that object should contain a list of all Class objects
#those objects should have methods to retrieve avg grade etc...

rawDescription: I'm creating a quiz which is for primary school students


code: real_fun = getattr(generator, 'nextCmd')

rawDescription: How to get data from SNMP with python?

description: Get data from SNMP with python


code:
#!/usr/bin/env python
#file: child.py
import os
import random
import sys
import time

for i in range(10):
    print("%2d %s %s" % (int(sys.argv[1]), os.getpid(), i))
    sys.stdout.flush()
    time.sleep(random.random())

rawDescription: Python subprocess in parallel

description: Python subprocess in parallel


rawDescription: Python - Homework - Converting Any Base to Any Base


code:
inventory = {
    'A': ['Toy', 3, 30],
    'B': ['Toy', 8, 80],
    'C': ['Cloth', 15, 150],
    'D': ['Cloth', 9, 90],
    'E': ['Toy', 11, 110]
}

items = sorted(inventory.items(), key=lambda item: item[1][1])

most_expensive_by_category = {item[0]: (key, item) for key, item in items}

most_expensive = dict(most_expensive_by_category.values())

rawDescription: grouping dictionary with list values

description: Grouping dictionary with list values


code: divergence = ((V * np.log(V_over_WH)) - V + WH).sum()

rawDescription: non-negative matrix factorization failing to converge

description: Non-negative matrix factorization failing to converge


code:
def my_spider(max_pages):
    # use range from 1 to max pages
    for i in range(1, max_pages+1):
        url = 'http://www.buya.com/Store/SAM-S-LOCKER/400?page={}'.format(i) # http:/?...
        source_code = requests.get(url)
        plain_text = source_code.content
        soup = BeautifulSoup(plain_text)
        # you want the h3 tags and to extract the href from the a tags
        for link in soup.findAll("h3", {'class': "two-lines-name"}):
            href = link.a["href"]
            print(href)

my_spider(5) # outside the function

rawDescription: New to Python, what am I doing wrong and not seeing <A> tag (links) returned with BS4


code:
print('Hello world!')
while True:
    print('It is nice to meet you, ' + input('What is your name? '))

rawDescription: How do I use "while" in this situation

description: Use "while" in this situation


code:
from django.conf.urls import include, url

urlpatterns = [
    url(r'^blog/', include('blog.urls')),
]

rawDescription: How to link html files together using Django 1.9?

description: Link html files together using Django 1.9


code: bounded_zipf = stats.rv_discrete(name='bounded_zipf', values=(x, weights))

rawDescription: Sampling from a bounded domain zipf distribution


code:
import numpy as np

def func(x, y):
    return np.sin(y * x)

xaxis = np.linspace(0, 4, 10)
yaxis = np.linspace(-1, 1, 20)
result = func(x[:,None], y[None,:])

rawDescription: numpy - evaluate function on a grid of points

description: Numpy - evaluate function on a grid of points


code:
grouped = enumerate(groupby(seq, key=lambda x: x[1]), 1)
extracted = ((i, [g[0] for g in gg]) for i, (k,gg) in grouped)
final = [(i, len(x), x) for i,x in extracted]
final

rawDescription: Grouping list of tuples in python

description: Grouping list of tuples in python


code:
for k in lst:
    d.pop(k)

rawDescription: Removing one or multiple keys from a dictionary


code:
def func1():
   def set1():
      x=5
      y=10
   ##lots of code
   x+=1
   y+=1

def func2():
   while True:
      func1()

set1() # This won't work because set1 is in the local scope of func1
       # and hidden from the global scope
func2()

rawDescription: python run code that is in a function once

description: Python run code that is in a function once


code:
jacket = Jacket(size=69, color="pink")
jacket.save()
prod = Product(price=0.99)
prod.details = jacket  # It's like magic!
prod.save()

rawDescription: How to write dynamic Django models?

description: Write dynamic Django models


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

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


code:
import ctypes
from random import randint

class STRUCT_2(ctypes.Structure):
    #_pack_=2
    _fields_ = [('field_1', ctypes.c_short),
                ('field_2', ctypes.c_short),
                ('field_3', ctypes.c_short),
                ('field_4', ctypes.c_short),
                ('field_5', ctypes.c_short),
                ('field_6', ctypes.c_short),
                ('field_7', ctypes.c_short),
                ('field_8', ctypes.c_short)]

class STRUCT_1(ctypes.Structure):
    #_pack_=2
    _fields_ = [('elements', ctypes.c_short),
                #an array of structs
                ('STRUCT_ARRAY', ctypes.POINTER(STRUCT_2))]

    def __init__(self,num_of_structs):
        elems = (STRUCT_2 * num_of_structs)()
        self.STRUCT_ARRAY = ctypes.cast(elems,ctypes.POINTER(STRUCT_2))
        self.elements = num_of_structs

        for num in range(0,num_of_structs):
            self.STRUCT_ARRAY[num].field_1 = 1
            self.STRUCT_ARRAY[num].field_2 = 2
            self.STRUCT_ARRAY[num].field_3 = 3
            self.STRUCT_ARRAY[num].field_4 = 4

for num in range(0,100):
    test = STRUCT_1(num)
    print("%i done" % num)

rawDescription: python ctypes array of structs

description: Python ctypes array of structs


rawDescription: N Queens: backtracking solution implimented by Python generator


code: f = open(filename[1:])

rawDescription: Take data from socket connection and split it


code:
#------------------------------------------------------------------------------
# Completer configuration
#------------------------------------------------------------------------------

# Activate greedy completion
#
# This will enable completion on elements of lists, results of function calls,
# etc., but can be unsafe because the code is actually evaluated on TAB.
c.Completer.greedy = True # <-- uncomment this line and set it to True

rawDescription: Ipython autocompletion for list or dict of objects


code:
from collections import Iterable
lis = [1,[2,2,2],4]
list(flatten(lis))
list(flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))

rawDescription: How to convert a nested list into a one-dimensional list in Python?

description: Convert a nested list into a one-dimensional list in Python


code: func_template = lambda **kwargs: eval(compiled, globals(), **kwargs)

rawDescription: Python dynamic functions from strings

description: Python dynamic functions from strings


code: 'Look at the rOBOt down the road.'.lower()

rawDescription: find mixed case word in python string

description: Find mixed case word in python string


code:
import csv
import json

scores = {}  # empty dictionary to store scores for each word

with open('sentimentfile.txt') as f:
    reader = csv.reader(f, delimiter='\t')
    for row in reader:
        scores[row[0].strip()] = int(row[1].strip())

with open('tweetsfile.txt') as f:
    for line in f:
        tweet = json.loads(line)
        text = tweet.get('text','').encode('utf-8')
        if text:
            total_sentiment = sum(scores.get(word,0) for word in text.split())
            print("{}: {}".format(text,score))

rawDescription: how to properly loop through two files comparing strings in both files against each other

description: Properly loop through two files comparing strings in both files against each other


code:
for item in soup.select("div.view-content table tr")[1:]:
    f.writerow([td.get_text(strip=True).encode("utf-8") for td in item.find_all("td")])

rawDescription: Access python for loop values

description: Access python for loop values


code:
thelist = [elem for line in open('file.txt', 'r')
                for elem in ast.literal_eval(line)]

rawDescription: Strip outside quotes from text when writing to list in Python


code:
li=[[1,2,3],[4,5],[6],[7,8,9,10]]

def xlate(li,wanted):
    idx=0
    for i,e in enumerate(li):
        for j,e_ in enumerate(e):
            if idx==wanted: return (i,j)
            idx+=1

    return (None,None)

t=xlate(li,5)
li[t[0]][t[1]]='X'

rawDescription: How to replace the nth element of multi dimension lists in Python?

description: Replace the nth element of multi dimension lists in Python


code:
#!/usr/bin/env python
from bottle import request, route, run, view

@route('/', method=['GET', 'POST'])
@view('form_template')
def index():
    return dict(parts=request.forms.sentence.split(), # split on whitespace
                show_form=request.method=='GET') # show form for get requests

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

rawDescription: how do i print outputs to html page using python?

description: Print outputs to html page using python


code:
from datetime import datetime,time

start = time(8, 0, 0)
end = time(20, 0, 0)
with open("input.txt") as f,open("output.txt","w") as f1:
    for line in f:
        spl = line.split()
        t1 = datetime.fromtimestamp(float(spl[2])).time()
        t2 = datetime.fromtimestamp(float(spl[3])).time()
        if t1 >= start and t2 <= end:
            f1.write(line)

rawDescription: Obtain data from one time to another

description: Obtain data from one time to another


code: ['title\n\ncontent here\n\ntext...\n', 'title \n\n\n']

rawDescription: Regex: match text between 2 items

description: Regex: match text between 2 items


code: letter_freq_all.apply(lambda x: x.str.replace('[%*]', '').astype(float)/100, axis=1)

rawDescription: How to use Python's Str.Replace() Method on all columns in a Pandas DataFrame?

description: Use Python's Str.Replace() Method on all columns in a Pandas DataFrame


code:
from socket_views import test_connectOne, test_connectTwo

socketio.on('connect', namespace='/namespaceOne')(test_connectOne)
socketio.on('connect', namespace='/namespaceTwo')(test_connectTwo)

rawDescription: How to handle dynamic decorators in python easily?

description: Handle dynamic decorators in python easily


code:
leeway = 1.10

XX = X.reshape((1, X.size))
dX = np.abs(XX - XX.T).reshape((1, X.size ** 2))
dxs = dX[np.where(np.logical_and(dX > expected_distance / leeway,
                                 dX < expected_distance * leeway))]
dx = dxs.mean()

YY = Y.reshape((1, Y.size))
dY = np.abs(YY - YY.T).reshape((1, Y.size ** 2))
dys = dY[np.where(np.logical_and(dY > expected_distance / leeway,
                                 dY < expected_distance * leeway))]
dy = dys.mean()

rawDescription: Constructing a 2D grid from potentially incomplete list of candidates


code:
def get_env_variable(var_name, default=False):
    """
    Get the environment variable or return exception
    :param var_name: Environment Variable to lookup
    """
    try:
        return os.environ[var_name]
    except KeyError:
        import StringIO
        import ConfigParser
        env_file = os.environ.get('PROJECT_ENV_FILE', SITE_ROOT + "/.env")
        try:
            config = StringIO.StringIO()
            config.write("[DATA]\n")
            config.write(open(env_file).read())
            config.seek(0, os.SEEK_SET)
            cp = ConfigParser.ConfigParser()
            cp.readfp(config)
            value = dict(cp.items('DATA'))[var_name.lower()]
            if value.startswith('"') and value.endswith('"'):
                value = value[1:-1]
            elif value.startswith("'") and value.endswith("'"):
                value = value[1:-1]
            os.environ.setdefault(var_name, value)
            return value
        except (KeyError, IOError):
            if default is not False:
                return default
            from django.core.exceptions import ImproperlyConfigured
            error_msg = "Either set the env variable '{var}' or place it in your " \
                        "{env_file} file as '{var} = VALUE'"
            raise ImproperlyConfigured(error_msg.format(var=var_name, env_file=env_file))

# Make this unique, and don't share it with anybody.
SECRET_KEY = get_env_variable('SECRET_KEY')

rawDescription: Pycharm: set environment variable for run manage.py Task


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-b', action="store_true")
parser.add_argument('-c', action="store_true")
parser.add_argument('-d', action="store_true")
parser.add_argument('-a', action="store_true")
args = parser.parse_args()
if args.a: args.b = args.c = args.d = True

rawDescription: python - argparse one argument instead of several others

description: Python - argparse one argument instead of several others


code:
ax = subplot(111)
ax.yaxis.set_ticks([16, 8, 4, 2, 1, 0])
axis([-0.5, 4.5, 31.5, 0.5])
imshow(b, interpolation="nearest")

rawDescription: How to plot an image with non-linear y-axis with Matplotlib using imshow?

description: Plot an image with non-linear y-axis with Matplotlib using imshow


code:
def coarsegrain(x,w=2):
    N = len(x)
    M = N//w
    y = zeros((M,M))
    for i in range(M):
        for j in range(M):
            y[i,j] = np.nanmean(x[w*i:w*i+w,w*j:w*j+w])
    return y

rawDescription: average of elements within a window of size NbyN of an array

description: Average of elements within a window of size NbyN of an array


code: lines = sys.stdin.readlines()

rawDescription: Python regex with devanAgarI

description: Python regex with devanAgarI


code:
class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        central_widget = QtGui.QWidget()
        self.setCentralWidget(central_widget) # new central widget
        self.ui = Ui_Form()
        self.ui.setupUi(central_widget)  # target central_widget for UI setup

rawDescription: PyQt Layout seems not to work - why all is overlayed?


code: [x[0]==x[1] and x[0] or 'dc' for x in zip(s.split(), s1.split())]

rawDescription: Python - replace a word multiple times

description: Python - replace a word multiple times


code:
def function1(n,d):
    if n/2 in d:
        d[n] = d[n/2] + 1
        return
    if n not in d:
        length = 0
        temp = n
        while temp > 1:
            if temp%2 == 0:
                temp //= 2
            else:
                temp = 3*temp + 1
            length += 1
            if temp in d:
                length += d[temp]
                break
        d[n] = length

d={1: 1}
for key in range(first,last):
    function1(key, d)

rawDescription: Improving speed of large dictionary in Python 3.4


code:
f.class_
raise f.class_('foo')

rawDescription: Multiple dot syntax in python and matplotlib


code:
from itertools import *

return chain.from_iterable((x,a) for a in y)

rawDescription: list comprehension question

description: List comprehension question


code:
type(object).__dict__['mro'].__get__(object, type(object)) == object.mro
type(object).__dict__['mro'].__get__(object, type(object))()

rawDescription: Python3 how is mro defined in object?

description: Python3 how is mro defined in object


code:
class Symbol(object):
    registry = {}
    def __new__(cls, *args, **kwargs):
        id_ = args[0]
        return Symbol.registry.setdefault(_id, object.__new__(cls, *args, **kwargs))

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

rawDescription: Pickling a "interned" object

description: Pickling a "interned" object


code:
lookup
lookup['P04217']

rawDescription: look up dictionary in python

description: Look up dictionary in python


rawDescription: Treat String as Hex Python

description: Treat String as Hex Python


code: sum(sub.count(item) for sub in lst)

rawDescription: How to find the number of instances of an item in a list of lists

description: Find the number of instances of an item in a list of lists


rawDescription: Iterate through triple nested tuple Python 3.4


code:
xmin,xmax = 3,5
ymin,ymax = 2, 6
my_slice = np.s_[ymin:ymax+1, xmin:xmax+1]
my_slice
my_slice[0]
dir(my_slice[0])

rawDescription: How to get coordinates from a numpy slice object

description: Get coordinates from a numpy slice object


code:
if index == len(l) or l[index] != e:
    return False, None
return True, index

rawDescription: Python bisect: pass value instead of returning insertion index


code:
import math
import wave
import struct
FILENAME = "/tmp/test.wav"
freq = 440.0
data_size = 40000
frate = 1000.0
amp = 64000.0
nchannels = 2
sampwidth = 2
framerate = int(frate)
nframes = data_size
comptype = "NONE"
compname = "not compressed"
data = [(math.sin(2 * math.pi * freq * (x / frate)),
        math.cos(2 * math.pi * freq * (x / frate))) for x in range(data_size)]
try:
    wav_file = wave.open(FILENAME, 'w')
    wav_file.setparams(
        (nchannels, sampwidth, framerate, nframes, comptype, compname))
    for values in data:
        for v in values:
            wav_file.writeframes(struct.pack('h', int(v * amp / 2)))
finally:
    wav_file.close()

rawDescription: Get .wav file length or duration

description: Get .wav file length or duration


code: second="\n".join(re.findall(r'\d+',line))#extract second position numbers

rawDescription: How to extract characters and numbers from every line of a file?

description: Extract characters and numbers from every line of a file


code:
def get_max_deflection(x_vals):
    ''' x_vals: iterable x-values
        returns (max_deflection, x_value) tuple '''
    return max((self.getTotalDeflection(x), x) for x in x_vals)

rawDescription: Finding the maximum return value of a function and the corresponding input for a given number of inputs


code:
def create_sample_set(mask, N=36, shape_color=[0,0,1.,1.]):
    rv = np.ones((N, mask.shape[0], mask.shape[1], 4),dtype=np.float)
    mask = mask.astype(bool)
    for i in range(N):
        for j in range(3):
            current_color_layer = rv[i,:,:,j]
            current_color_layer[:,:] *= np.random.random()
            current_color_layer[mask] = np.ones((mask.sum())) * shape_color[j]
    return rv

rawDescription: How to detect object on images?

description: Detect object on images


rawDescription: Reading data from specially formatted text file


rawDescription: passing arguments without commandline

description: Passing arguments without commandline


code:
from sqlalchemy.sql import and_

def get_contacts(*exps):
    return session.query(Contact).filter(and_(*exps)).all()

# All contacts with an id less than 5 and a name that starts with user.
contacts = get_contacts(Contact.id < 5, Contact.name.like('user%'))

rawDescription: how to deal with multiple arguments in a dictionary construct when query in sqlalchemy?

description: Deal with multiple arguments in a dictionary construct when query in sqlalchemy


code:
from decimal import Decimal
d = Decimal('1.23')
d
f = d
f
d._exp = 1
f

rawDescription: How is the Decimal Class Immutable?

description: How is the Decimal Class Immutable


code:
@classmethod
def main(cls):
    "Create an application containing a single TrimDirView widget."
    tkinter.NoDefaultRoot()
    root = cls.create_application_root()
    cls.attach_window_icon(root, ICON)
    view = cls.setup_class_instance(root)
    cls.main_loop(root)

rawDescription: Updating a TKinter GUI from a multiprocessing calculation


code:
a = ['1,2,3,4,5Text,6Text']
[','.join(x for x in a[0].split(',') if not x.endswith('Text'))]

rawDescription: How to remove specific strings from a list

description: Remove specific strings from a list


code:
fr = open('/home/name/db/str/dir/numbers/str.phy')
fw = open('/home/name/db/str/dir/numbers/str.phy.parsed', 'w') # Name this whatever makes sense

for line in fr:
    if line.startswith('ENS'):
        linepars = re.sub ('ENS([A-Z]+)0+([0-9]{6})','\\1\\2',line)
        fw.write(linepars)
    else:
        fw.write(line)

fw.close()
fr.close()

rawDescription: Python Overwriting files after parsing

description: Python Overwriting files after parsing


code:
def foo():
    string = ("this is an "
              "implicitly joined "
              "string")

rawDescription: Proper indentation for Python multiline strings


rawDescription: ast.literal_eval not working (python string of list to list)

description: Ast.literal_eval not working (python string of list to list)


rawDescription: Generating products of lists that sum to a parameter N


code:
d = {}
nested_set(d, ['person', 'address', 'city'], 'New York')
d

rawDescription: Setting a value in a nested python dictionary given a list of indices and value


code:
sample_dict = {
        'key1': [
                {'key1': 'value_of_interest'},
                {'key2': 'less_interesting_value'},
                ],
        }

rawDescription: In Python, why isn't there a built in function to find a key in a nested dictionary?


code:
@app.before_request
def before_request():
    g.db = connect_db()

@app.teardown_request
def teardown_request(exception):
    db = getattr(g, 'db', None)
    if db is not None:
        db.close()

rawDescription: Keeping an object over the lifetime of a request in Flask


code:
def logdotexp(A, B):
    max_A = np.max(A)
    max_B = np.max(B)
    C = np.dot(np.exp(A - max_A), np.exp(B - max_B))
    np.log(C, out=C)
    C += max_A + max_B
    return C

rawDescription: numerically stable way to multiply log probability matrices in numpy

description: Numerically stable way to multiply log probability matrices in numpy


code:
import helpers

@route('/')
def index():
    return Template("template_name").render(h=helpers)

rawDescription: Webhelpers with Python Bottle

description: Webhelpers with Python Bottle


code:
replacements = [("A", "eh"), ("B", "bee"), ("X", "ex")]
result = re.sub("([A-Z])(?=[A-Z])", r"\1 ", "ABC thIs iS XYZX. A Xylophone")
for source, dest in replacements:
    result = re.sub("("+source+r")(?=\W)" , dest, result)
print(result)

rawDescription: regexp for nvda to put spaces between all capital letters?

description: Regexp for nvda to put spaces between all capital letters


code: return xls_to_response(xls,'foo.xls')

rawDescription: django excel xlwt

description: Django excel xlwt


code:
datetime.datetime(2012, 1, 1, 0, 0)
                 #year, month, day, hour min if I recall correctly.

rawDescription: Setting the x axis as time (years, months) for a set of values


rawDescription: Python - Neaten this append/extend conditional


code:
df = pd.concat([s, s2], axis=1)
df.apply(lambda x: len(x[0] & x[1]), axis=1)

rawDescription: Count size of rolling intersection in pandas


code:
import numpy as np

# Some physical constants we'll need
h, kB, c = 6.626e-34, 1.381e-23, 2.998e8

def planck(lam, T):
    # The Planck function, using NumPy vectorization
    return 2*h*c**2/lam**5 / (np.exp(h*c/lam/kB/T) - 1)

# wavelength array, 3 - 300 um
lam = np.linspace(3, 75, 132)
# temperature array
T = np.array([280, 300, 320, 340, 360, 380])
# Remember to convert wavelength from um to m
pfuncs = planck(lam * 1.e-6, T[:,None])

import pylab
for pfunc in pfuncs:
    pylab.plot(lam, pfunc)
pylab.show()

rawDescription: python, plot planck curves looping through arrays

description: Python, plot planck curves looping through arrays


code:
timeout = 15
time.sleep(timeout)

rawDescription: How to stop a Python program after some arbitrary timeout

description: Stop a Python program after some arbitrary timeout


code:
Setup
df = pd.DataFrame(np.random.rand(10000, 5)*10, columns=list('ABCDE')).astype(int)

rawDescription: How to use pandas isin() to test values on a range of columns in a dataframe

description: Use pandas isin() to test values on a range of columns in a dataframe


code:
ID_GENERATOR = create_id_generator()  # Global variable
my_id = next(ID_GENERATOR)
my_id2 = next(ID_GENERATOR)
my_id3 = next(ID_GENERATOR)
print(my_id, my_id2, my_id3, next(ID_GENERATOR))

rawDescription: Python best practices for functions

description: Python best practices for functions


code:
txt = in_file.read()
count = {x:sum([1 for char in txt if char==x])for x in 'aeiouy'}

rawDescription: Vowel counter in a text file

description: Vowel counter in a text file


code:
class MyModel(Model):
    pk = PrimaryKeyField()
    other_field = TextField()

rawDescription: Peewee: change "Id" field with another name


code:
def create_app(logger_instance):
    app = Flask(__name__)
    app.config['LOGGER'] = logger_instance
    return app

rawDescription: Pass another object to the main flask application


code: data = [[1 if entry=='X' else 0 for entry in row[1:]] for row in reader]

rawDescription: How to parse of a simple csv file?

description: Parse of a simple csv file


code:
from package import foo
foo.fct(7)

rawDescription: Import a module from a package

description: Import a module from a package


code:
class LocationByCountryListAPIView(generics.ListAPIView):
    def get(self, request, country_pk):
        # get the country by its primary key from the url
        country = Country.objects.get(pk=country_pk)

        locations = Location.objects.filter(country=country)
        location_serializer = LocationSerializer(locations, many=True)

        return Response({
            'locations': location_serializer.data
        })

rawDescription: How to retrieve object by foreign key in the url using Django and rest_framework

description: Retrieve object by foreign key in the url using Django and rest_framework


code: tuple(x.split('-') + [int(y)])

rawDescription: How to combine two lists in a non standard way in Python

description: Combine two lists in a non standard way in Python


code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1977)

x = np.random.normal(0, 1, 1000).cumsum()

# Set every third value to NaN
x[::3] = np.nan

# Set a few bigger gaps...
x[20:100], x[200:300], x[400:450] = np.nan, np.nan, np.nan

# Use pandas with a limited forward fill
# You may want to adjust the `limit` here. This will fill 2 nan gaps.
filled = pd.Series(x).fillna(limit=2, method='ffill')

# Let's plot the results
fig, axes = plt.subplots(nrows=2, sharex=True)
axes[0].plot(x, color='lightblue')
axes[1].plot(filled, color='lightblue')

axes[0].set(ylabel='Original Data')
axes[1].set(ylabel='Filled Data')

plt.show()

rawDescription: Working with NaN values in matplotlib

description: Working with NaN values in matplotlib


rawDescription: Solve 2 sides of equation with SymPy

description: Solve 2 sides of equation with SymPy


code:
def foo(i, axis):
    for j in range(9):
        value = grid[i][j] if axis == 'x' else grid[j][i]
        doSomething(value)
        doSomethingElse(value)

rawDescription: Conditionally swap axes in for loop for multidimensional list Python


code: dfrs = df.resample('3min', how=sum)

rawDescription: Grouping pandas data frame by time intervals


code:
string = 'examine table'
splitString = string.split()

rawDescription: How to split a variable into two different variables?

description: Split a variable into two different variables


code:
content = ["['Chest', ['bench', 'incline'], [2, 1], [10, 10], [10, 20, 10]], 'Chest', ['decline'], [1], [1], [10]"]

import ast
a_tuple = ast.literal_eval(content[0])
print(a_tuple)

rawDescription: Python(3.x) - Opening File and Removing the Quotation Marks when reading file


code:
def differenceImageV6(img1, img2):
  a = img1-img2
  b = np.uint8(img1<img2) * 254 + 1
  return a * b

rawDescription: Fast absolute difference of two uint8 arrays


code:
import mock
import nose2.tools

def fix_case(f):
    def test(case):
        f(case=case)
    return test

with nose2.tools.such.A('system') as it:

    @it.should('do something')
    @fix_case
    @mock.patch('datetime.time')
    @mock.patch('datetime.date')
    def test_3(date, time, case=None):
        print(date, time, case)

it.createTests(globals())

rawDescription: Use mock.patch decorators with nose2 Such DSL


code:
for i in r(l):
    ...

rawDescription: Short for 'for i in range(1,len(a)):' in python


rawDescription: Python: elegant way to split a string in order to pick the last element when the len of string is unknown


code:
from collections import Counter
strs="assassin"
Counter(strs)

rawDescription: Counting consecutive characters in a string


code: df[day_names] = df.apply(lambda row: pd.Series(row.days), axis=1)

rawDescription: Pandas - How do I subset a column composed of list objects?


rawDescription: Python reset to 0 a Multidimensional Array


code:
import simplejson
simplejson.dumps({'node': {'list': '

Hello World

'}})

rawDescription: HTML tags within JSON (in Python)

description: HTML tags within JSON (in Python)


rawDescription: better way to find pattern in string?

description: Better way to find pattern in string


code:
def list_decreaser(xs):
    listresult = []
    for i in range(len(xs)-1, 0, -1): # <--- interate backward
        del xs[i]
        listresult.append(xs[:]) # <----
    return listresult

print(list_decreaser([0,3,4,5,6,7,8]))

rawDescription: function that given a list returns a list of list decreasing

description: Function that given a list returns a list of list decreasing


code: groups.rds | intersect(groups.development) | first

rawDescription: How to get a hostname that contains a certain string from a group in Ansible

description: Get a hostname that contains a certain string from a group in Ansible


code:
def anti_vowel(text):
    return ''.join(c for c in text if c.lower() not in vowels)

rawDescription: pop() function not functioning right in a for loop

description: Pop() function not functioning right in a for loop


code:
for line in open('log.txt'):
    sent_time, src, sport, dst, dport, payload = line.split(' | ', 6)
    payload = payload.replace('Payload ', '')

    # to get the unquoted payload, I'd guess (can't test SIP though)
    from ast import literal_eval
    payload = literal_eval(payload)

rawDescription: python SIP log file processing

description: Python SIP log file processing


code: s = 'This is my string, it contains a single quotation mark \', but that\'s fine because I\'ve escaped them!'

rawDescription: Having quotation marks as a character in a python list


code:
s = 'hello world'
s.split(' ', maxsplit=1)
s.split(' ', 1)

rawDescription: python inspect module positional_only param

description: Python inspect module positional_only param


code:
col = 1
a[a[:,col].argsort(axis=0)]

rawDescription: Sorting numpy matrix for a given column

description: Sorting numpy matrix for a given column


code: [lst for lst in [[itm for itm in sublst if itm != 'data'] for sublst in hashtags] if len(lst) > 0 ]

rawDescription: Python: Remove an item from list

description: Python: Remove an item from list


code:
for i in nums:
    print(i)

rawDescription: Extracting digits in line and storing them to list in Python


rawDescription: How can I apply a math operation on a list of tuples with `map()`?

description: Apply a math operation on a list of tuples with `map()`


rawDescription: Python: Count how many times a word occurs in a file


code:
grouped = df.groupby(['group'])
grouped['Bid'].sum()

rawDescription: pandas quick way to break dataframe by timeindex

description: Pandas quick way to break dataframe by timeindex


code: line_read_bytearray = bytearray(line_read, 'UTF-8')

rawDescription: How to convert the data extracted from a file to bytes in python?

description: Convert the data extracted from a file to bytes in python


rawDescription: Python extending decimals

description: Python extending decimals


code:
new_soup = BeautifulSoup('<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">')
new_soup
type(new_soup)

rawDescription: How can I create a stylesheet external link using BeautifulSoup?

description: Create a stylesheet external link using BeautifulSoup


code: my_var = addition(1, 2)

rawDescription: re-naming data frame output given input parameter to class in python

description: Re-naming data frame output given input parameter to class in python


rawDescription: How can data remain persistent across multiple calls of decorated function?


code:
def parms_of(f):
    return f.__code__.co_varnames[:f.__code__.co_argcount]

rawDescription: Initializing a class in another class, but passing only set attributes


code: data = [list(row) for row in zip(*data)]

rawDescription: How do I remove an empty column in a two dimensional list in python?

description: Remove an empty column in a two dimensional list in python


code:
fig = plt.figure(figsize=(6, 4))
ax1 = plt.subplot2grid((5,1), (0, 0), rowspan=2)
ax2 = plt.subplot2grid((5,1), (2, 0), rowspan=1)
ax3 = plt.subplot2grid((5,1), (3, 0), rowspan=2)

rawDescription: matplotlib subplot2grid doesn't display correctly

description: Matplotlib subplot2grid doesn't display correctly


code:
df = s.str.get_dummies(sep=" ")
df.columns = df.columns.map(int)
df.reindex(columns=np.arange(6), fill_value=0)

rawDescription: Pandas: Convert array column to numpy Matrix


code:
backslashpairs = (arr[:-1, :-1] == arr[1:, 1:])
slashpairs = (arr[1:, :-1] == arr[:-1, 1:])

equal_neighbors = np.zeros_like(arr, dtype=int)
equal_neighbors[:-1] += vpairs
equal_neighbors[1:] += vpairs
equal_neighbors[:, :-1] += hpairs
equal_neighbors[:, 1:] += hpairs
equal_neighbors[1:, :-1] += slashpairs
equal_neighbors[:-1, 1:] += slashpairs
equal_neighbors[:-1, :-1] += backslashpairs
equal_neighbors[1:, 1:] += backslashpairs
equal_neighbors

rawDescription: Comparing elements in a numpy array, finding pairs, how to deal with edges/corners


code:
def pyramid(n):
    word = "abc"
    counter = 0
    for i in range(1, n+1):
        print (" "*(n-i), end="")
        for j in range(i):
            print (word[counter%len(word)], end=" ")
            counter += 1
        print()

rawDescription: Triangle made out of 'abc' [python]

description: Triangle made out of 'abc' [python]


code:
def test():
    global thread1
    ...

rawDescription: How to use thread instance function inside a function?

description: Use thread instance function inside a function


rawDescription: How to quickly convert two column CSV to a table/excel spreadsheet?

description: Quickly convert two column CSV to a table/excel spreadsheet


code: text = re.sub("jnnorm", "jnnorm MYTAGHERE", text)

rawDescription: How to use regular expressions on a .html file in python?

description: Use regular expressions on a .html file in python


rawDescription: Handling spreadsheet data through the clipboard in GTK


code: print('Type > ', end='', flush=True)

rawDescription: Python3: Using "select.select" with print(str, end=' ')


code:
from __future__ import unicode_literals
s=['xx','yy','zz','aa']
s

rawDescription: How to achieve forward compatible string literals in python?

description: Achieve forward compatible string literals in python


code: b[:, columns_ids] = a[:, columns_ids][b_rows]

rawDescription: Manipulation with arrays in numpy

description: Manipulation with arrays in numpy


code: con.execute("select * from sqlite_master where type='table';").fetchone()[4]

rawDescription: csv import sqlite3 without specifying column types

description: Csv import sqlite3 without specifying column types


code: df.index = df.index.date

rawDescription: how avoid change index to timestamp in pandas dataframe when create a generator

description: How avoid change index to timestamp in pandas dataframe when create a generator


code:
class MyClass(object):
    thatDict={} # Only one copy

rawDescription: What is more efficient? A dict inside the class definition or dict inside a func definition?


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

data = np.arange(100).reshape(10, 10)

cmap = plt.cm.gray
norm = plt.Normalize(data.min(), data.max())
rgba = cmap(norm(data))

# Set the diagonal to red...
rgba[range(10), range(10), :3] = 1, 0, 0

plt.imshow(rgba, interpolation='nearest')
plt.show()

rawDescription: Changing colours of pixels of plt.imshow() image


code:
aa = doc[0]
aa
'<html><head><title>Page title</title></head>'
pt = re.compile('(?<=<title>).*?(?=</title>)')
re.findall(pt,aa)
['Page title']

rawDescription: Python Regex Help

description: Python Regex Help


code:
CHILD= None

def the_callback(child_hwnd, regex):
    '''Pass to win32gui.EnumWindows() to check all the opened windows'''
    if re.match(regex, win32gui.GetWindowText(child_hwnd)):
        CHILD= child_hwnd

win32gui.EnumChildWindows(hwnd, the_callback, regex)

if CHILD:
    (x_tl, y_tl, x_br, y_br) = win32gui.GetWindowRect(CHILD)

rawDescription: python win32 simulate click

description: Python win32 simulate click


code:
import tokenize
import token
import io
import collections

class Token(collections.namedtuple('Token', 'num val start end line')):
    @property
    def name(self):
        return token.tok_name[self.num]

def change_str_to_unicode(text):
    result = text.splitlines()
    # Insert a dummy line into result so indexing result
    # matches tokenize's 1-based indexing
    result.insert(0, '')
    changes = []
    for tok in tokenize.generate_tokens(io.BytesIO(text).readline):
        tok = Token(*tok)
        if tok.name == 'STRING' and not tok.val.startswith('u'):
            changes.append(tok.start)

    for linenum, s in reversed(changes):
        line = result[linenum]
        result[linenum] = line[:s] + 'u' + line[s:]
    return '\n'.join(result[1:])

text = '''print "result code %d" % result['code']
# doesn't touch 'strings' in comments
'handles multilines' + \
'okay'
u'Unicode is not touched'
'''

print(change_str_to_unicode(text))

rawDescription: How to ensure all string literals are unicode in python

description: Ensure all string literals are unicode in python


code:
import urllib2, lxml.etree as etree

url = 'http://www.xmlfiles.com/examples/note.xml'
headers = {}

req = urllib2.Request(url, headers=headers)
responseData = urllib2.urlopen(req).read()

element = etree.fromstring(responseData)
print(element)
print(etree.tostring(element, pretty_print=True))

rawDescription: XML in Python and lxml

description: XML in Python and lxml


code:
output = subprocess.check_output(
  """my_func() { echo The argument is "$1"; }
     my_func the_argument
  """,
  shell = True)

rawDescription: Using Subprocess or os.system to run shell commands in python


code:
class MyInline(admin.TabularInline):
    MyModel.m2m.through.__unicode__ = lambda x: 'My New Unicode'
    model = MyModel.m2m.through

rawDescription: Django: Friendlier header for StackedInline for auto generated through model?


code:
import heapq as _heapq

def most_common(counter, n=None):
    '''List the n most common elements and their counts from the most
    common to the least.  If n is None, then list all element counts.

    >>> Counter('abcdeabcdabcaba').most_common(3)
    [('a', 5), ('b', 4), ('c', 3)]

    '''
    # Emulate Bag.sortedByCount from Smalltalk
    sort_key = lambda pair: (-pair[1], pair[0])
    if n is None:
        return sorted(counter.iteritems(), key=sort_key)
    return _heapq.nsmallest(n, counter.iteritems(), key=sort_key)

rawDescription: How to sort the results of Counter.mostCommon(n) lexicographically (by counter, then by value)?

description: Sort the results of Counter.mostCommon(n) lexicographically (by counter, then by value)


rawDescription: How to change array layout?

description: Change array layout


code:
import re
import keyword
def replace_var(m):
    varname = m.group()
    if keyword.iskeyword(varname) or varname[0].isdigit():
        return varname
    return varname + '[n]'
re.sub(r'\w+',  replace_var, 'b<3 and d >4 or 4<=a <20')

rawDescription: replacing part of the string in python 2.7

description: Replacing part of the string in python 2.7


code:
url(r'^continue/(?P<workflowid>\d+)/$',
          view = 'continue',
          name = 'continue_view')

rawDescription: How do I make my post form handling more flexible

description: Make my post form handling more flexible


code:
df1['val'] = df2['val'].combine_first(df1['val'])
df1

rawDescription: how to update existing data frame in pandas?

description: Update existing data frame in pandas


code:
sys.argv
['uwsgi', 'foo', 'bar']

rawDescription: Pass command line parameters to uwsgi script


code: from fractions import Fraction

rawDescription: Python 3 Assume Module Namsepace

description: Python 3 Assume Module Namsepace


code:
class foo(object):
    def __init__(self):
        self.bar_counter = 0
    def bar(self):
        self.bar_counter += 1
        return self.bar_counter

rawDescription: Adding attributes to instance methods in Python


code:
busdef = And([busname.setResultsName("bus1"),
            busname.setResultsName("bus2"),
            integer.setResultsName("linenum"),
            decimaltable("pf qf pl ql".split())])

rawDescription: How should I organise my functions with pyparsing?


code:
def getRandomRate(self):
    return random.choice([v for attr, v in vars(self).items()
                          if len(attr) == 8 and attr[3:5] == 'To'])

rawDescription: Get random element from attributes in an object


code:
d = {}
for k, v in s:
    d.setdefault(k,set())
    d[k].add(v)

rawDescription: Python How to find duplicate values in Dictionary


code:
import datetime

start_time = 9 # per user input
end_time = 10 # per user input
divisions = 7 # per user input

total_time = end_time - start_time
start_time = datetime.datetime.combine(datetime.date.today(),datetime.time(start_time))
end_time = start_time + datetime.timedelta(hours=total_time)

increment = total_time*3600000//divisions # resolution in ms

times = [(start_time+datetime.timedelta(milliseconds=increment*i)).time()
         for i in range(divisions)]

from pprint import pprint

pprint(list(map(str,times)))

# ['09:00:00',
#  '09:08:34.285000',
#  '09:17:08.570000',
#  '09:25:42.855000',
#  '09:34:17.140000',
#  '09:42:51.425000',
#  '09:51:25.710000']

rawDescription: Python Time Math

description: Python Time Math


code:
STATIC_URL = 'https://bucket-name.s3.amazonaws.com/static/'
ADMIN_MEDIA_PREFIX = 'https://bucket-name.s3.amazonaws.com/static/admin/'

rawDescription: Proper way to handle static files and templates for Django on Heroku


code:
from django import template
register = template.Library()

@register.filter(name='class_name')
def class_name(obj):
  return obj.__class__.__name__

rawDescription: Unique HTML element IDs for each model with Django


code: np.clip(pd.Series(range(10)), 2, 3)

rawDescription: Why np.clip(pd.Series(range(10)), 2,3) returns a Series?


code:
from PySide import QtGui, QtCore
import pandas as pd
import pyqtgraph as pg
import numpy as np
QVariant = lambda value=None: value

class Widget(QtGui.QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)

        v_global_layout = QtGui.QVBoxLayout()
        v_global_layout.addWidget(TabDialog())
        v_global_layout.setAlignment(QtCore.Qt.AlignTop)

        self.setLayout(v_global_layout)

class TabDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        tab_widget = QtGui.QTabWidget()

        # Have the tabs as this dialog's class properties
        self.tab1 = Tab1(image)
        self.tab2 = Tab2()

        tab_widget.addTab(self.tab1, "1")
        tab_widget.addTab(self.tab2, "2")

        self.tab1.a.sigClicked.connect(self.pointChanged)

        main_layout = QtGui.QVBoxLayout()
        main_layout.addWidget(tab_widget)
        self.setLayout(main_layout)

    def pointChanged(self, points):
        tab2.points_from_tab1_a = tab1.a

class Tab1(QtGui.QTabWidget):
    def __init__(self):
        super().__init__()
        layout = QtGui.QHBoxLayout()
        self.fig = pg.PlotWidget(name='Example: Selecting scatter points')

        self.plot_area = self.fig.plotItem
        self.a = pg.ScatterPlotItem(pxMode=False)
        spots = []
        for i in range(10):
            for j in range(10):
                spots.append({'pos': (1*i, 1*j), 'size': 1, 'pen': {'color': 'w', 'width': 2},
                              'brush': pg.intColor(i*10+j, 100)})
        self.a.addPoints(spots)

        self.plot_area.addItem(self.a)

        self.a.dataModel = DataFrameModel()
        self.a.dataTable = QtGui.QTableView()
        self.a.dataTable.setModel(self.a.dataModel)

        layout.addWidget(self.a.dataTable)
        layout.addWidget(self.fig)
        self.setLayout(layout)

        self.a.array = np.zeros((0, 2))

        def clicked(self, points):
            for p in points:
                p.setPen('b', width=2)
                position = p.viewPos()
                self.array = np.append(self.array, np.array([[position.x(), position.y()]]), axis=0)
            c = range(len(self.array))
            c = list(map(str, c))
            self.dataModel.signalUpdate(self.array, columns=c)
            self.dataModel.printValues() # also: print(self.array)
        self.a.sigClicked.connect(clicked)

class Tab2(QtGui.QTabWidget):
    def __init__(self):
        super().__init__()
        layout = QtGui.QHBoxLayout()

        self.points_from_tab1_a = []
        ##### Here I want to use Tab1.a and not inherit all the other stuff(layout) #####
        #print("values = ", Tab1.a.array) # a should change when a new point is selected in Tab1
        #####################################
        self.setLayout(layout)

class DataFrameModel(QtCore.QAbstractTableModel):
    """ data model for a DataFrame class """
    def __init__(self):
        super(DataFrameModel, self).__init__()
        self.df = pd.DataFrame()

    def signalUpdate(self, dataIn, columns):
        self.df = pd.DataFrame(dataIn, columns)
        self.layoutChanged.emit()

    def printValues(self):
        print("DataFrame values:\n", self.df.values)

    def values(self):
        return self.df.values

    #------------- table display functions -----------------
    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QVariant()

        if orientation == QtCore.Qt.Horizontal:
            try:
                return self.df.columns.tolist()[section]
            except (IndexError, ):
                return QVariant()
        elif orientation == QtCore.Qt.Vertical:
            try:
                # return self.df.index.tolist()
                return self.df.index.tolist()[section]
            except (IndexError, ):
                return QVariant()

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QVariant()

        if not index.isValid():
            return QVariant()
        return QVariant(str(self.df.ix[index.row(), index.column()]))

    def rowCount(self, index=QtCore.QModelIndex()):
        return self.df.shape[0]

    def columnCount(self, index=QtCore.QModelIndex()):
        return self.df.shape[1]

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)

    main_window = Widget()
    main_window.setGeometry(100, 100, 640, 480)
    main_window.show()

    sys.exit(app.exec_())

rawDescription: Passing changing data from tab to tab

description: Passing changing data from tab to tab


code:
from pandas import read_csv

data = read_csv('data.dat', delimiter='\s+').values

print(data[~np.isnan(data[:, 2])][:, [0, 2]])

rawDescription: How to column stack arrays ignoring nan in Python?

description: Column stack arrays ignoring nan in Python


code:
self._writelock = Semaphore(1)
# this is a gevent locking thing. eventlet must have something like this too..
# just counts - 1 for locks and +1 for releases blocks otherwise blocks until
# 0 agian.... why not google it i though.. and yes im right:
# eventlet.semaphore.Semaphore(value=1)

def send(self, message):
    """
    you need a write lock to prevent more greenlets
    sending more messages when previous sent is not done yet.
    """

    with self._writelock:
        self.socket.sendall(message)

rawDescription: Can eventlet manage an AMQP connection with messages passing asynchronously both in and out?


code:
list_output = masked_output.tolist()
final_output = [[num for num in arr if num is not None] for arr in list_output]

rawDescription: Using ndarray.flatten() python for array of several arrays, Python


code:
def testforoo(x):
    return any(x[j]=='oo'.lower() for j in range(0,len(x)))

rawDescription: Python 3.3.3 TypeError : Can't convert 'NoneType' object to str implicitly


rawDescription: How to get a dict from scrapy item?

description: Get a dict from scrapy item


rawDescription: Python: How can I read the elements

description: Python: How can I read the elements


code:
@property
def gold_total(self):
    ...

rawDescription: Why does this python method return a memory address?


code:
for e in category.entry_set.select_related('extentry'):
    e.extentry # already loaded because of `select_related`,
               # however might be None if there is no Extentry for current e

rawDescription: Django ForeignKey _set on an inherited model


code:
mask = df.notnull().all(axis=1), ['A', 'B']
df.loc[mask] = scipy.stats.mstats.winsorize(df.loc[mask].values, limits=0.4)

rawDescription: How can I transform a dataframe in pandas without losing my index?

description: Transform a dataframe in pandas without losing my index


code: mask = pygame.mask.from_surface(self.getNextFrame(), 0)

rawDescription: How to get Mask with transparency in pygame?

description: Get Mask with transparency in pygame


code:
MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware'
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

rawDescription: Django language change not working

description: Django language change not working


code:
fig = plt.figure()
ax[1] = fig.add_subplot(3, 2, 1) # 3x2 grid, 1st plot
...
ax[6] = fig.add_subplot(3, 2, 6) # 3x2 grid, 6th plot

rawDescription: how to make colors in line graph fade in matplotlib and python

description: Make colors in line graph fade in matplotlib and python


code:
import M2Crypto
from binascii import hexlify
e = f.read(4)
n = f.read(0x80)
key = M2Crypto.RSA.new_pub_key((
    M2Crypto.m2.bn_to_mpi(M2Crypto.m2.hex_to_bn(hexlify(e))),
    M2Crypto.m2.bn_to_mpi(M2Crypto.m2.hex_to_bn(hexlify(n))),
    ))

rawDescription: M2Crypto - import keys from non-standard file?


code:
from rest_framework import viewsets
class BerriaViewSet(viewsets.ModelViewSet):
    queryset = Berria.objects.all()
    serializer_class = BerriaSerializer

rawDescription: django-rest-framework, how to paginate

description: Django-rest-framework, how to paginate


code: pd.DataFrame(np.add.outer(a, b), columns=b.index, index=a.index)

rawDescription: How to broadcast pandas series with different indices?

description: Broadcast pandas series with different indices


code:
class BitChoices(object):
  def __init__(self, choices):
    self._choices = []
    self._lookup = {}
    for index, (key, val) in enumerate(choices):
      index = 2**index
      self._choices.append((index, val))
      self._lookup[key] = index

  def __iter__(self):
    return iter(self._choices)

  def __len__(self):
    return len(self._choices)

  def __getattr__(self, attr):
    try:
      return self._lookup[attr]
    except KeyError:
      raise AttributeError(attr)

  def get_selected_keys(self, selection):
    """ Return a list of keys for the given selection """
    return [ k for k,b in self._lookup.iteritems() if b & selection]

  def get_selected_values(self, selection):
    """ Return a list of values for the given selection """
    return [ v for b,v in self._choices if b & selection]

rawDescription: Representing a multi-select field for weekdays in a Django model


code: flashlight1 = Item('flashlight', 5)

rawDescription: Storing Class Arguments in a List

description: Storing Class Arguments in a List


code:
class EstablecimientoViewSet(viewsets.ModelViewSet):
    queryset = Establecimiento.objects.only('nombre','categoria',)
    serializer_class = EstablecimientoSerializer

rawDescription: JSON from django rest Framework

description: JSON from django rest Framework


code:
ax_delays = delays.plot(x_compat=True, style='--', color=["r","b"])
rolling.plot(color=["r","b"], ax=ax_delays, legend=0)

rawDescription: Plot rolling mean together with data

description: Plot rolling mean together with data


code:
import pandas as pd
# ...
df = pd.read_sql(query.statement, query.session.bind)

rawDescription: contructing a dataframe from joined SQLAlchemy query

description: Contructing a dataframe from joined SQLAlchemy query


code: mylist = oldlist[:]

rawDescription: dealing with an empty list inside a list

description: Dealing with an empty list inside a list


code:
for years, categories in zip(all_years, all_category):
    year_won = years.string
    category_won = categories.string
    if year_won and category_won:
        csv_writer.writerow([year_won.encode('utf-8'), category_won.encode('utf-8')])

rawDescription: scraping site to move data to multiple csv columns

description: Scraping site to move data to multiple csv columns


code:
import re
import sys

my_file_m= '''TAATTCCATTCTCTACCCAGCCCCCACTCTGACCCCTTTACTCTGACCCCTTTATTGTCTACTCCTCAGAGCCCCCAGTCTGTATCCTTCTAACTTAGAAAGGGGATTATGGCTCAGGGTCCAACTCTGTGCTCAGAGCTTTCAACAACTACTCAGAAACACAAGATGCTGGGACAGTGACCTGGACTGTGGGCCTCTCATGCACCACCATCAAGGACTCAAATGGGCTTTCCGAATTCACTGGAGCCTCGAATGTCCATTCCTGAGTTCTGCAAAGGGAGAGTGGTCAGGTTGCCTCTGTCTCAGAATGAGGCTGGATAAGAT'''

pat = re.compile(r'(?=(TAA|TGA|TAG))') # Very important, if you do not need overlaps then remove '?='
lettersToColor = set().union(*[range(m.start(1),m.start(1)+3) for m in re.finditer(pat, my_file_m)])

for chari in range(len(my_file_m)): # colorize based on if it is in a sequence or not
    if(chari in lettersToColor):
        sys.stdout.write('\033[92m' + my_file_m[chari]  +'\033[0m')
    else:
        sys.stdout.write(my_file_m[chari])

rawDescription: how to find a three letter in a sequence?

description: Find a three letter in a sequence


code:
# let's assume you've read in your file with something like csvreader
# so you've got a list of lists, similar to what @Vasif shows
sorted_a = sorted(a, key=lambda row: (row[0], row[2], row[3]))

rawDescription: Array Grouping and Identify in python

description: Array Grouping and Identify in python


code:
var = [[1, 2], [3, 4]]
x = Foo(0, 1)
x.cell
x.cell = 8
var
y = Foo(1, 1)
y.cell = 88
var
var[0][1] = "Hello"
x.cell

rawDescription: How to make two classes sharing a same attribute?

description: Make two classes sharing a same attribute


code:
import numpy as np
import pandas as pd
# Create your data structures
cat1 = ['red', 'green']
cat2 = ['round', 'square']
values = [8, 10, 9, 14]
# Reshape your values to a two dimensional numpy array
data = np.array(values)
data.shape = (len(cat2), len(cat1))
# Create a DataFrame and print it
df = pd.DataFrame(data, columns=cat1, index=cat2)
df

rawDescription: Create a table of permutation data python


rawDescription: python - How to properly encode string in utf8 which is ISO8859-1 from xml

description: Python - How to properly encode string in utf8 which is ISO8859-1 from xml


code: value = soup.select('tr.row1 td:nth-of-type(3)')[0].get_text()

rawDescription: Using BeautifulSoup to pick up text in table, on webpages


code: number_of_cols = max(ceil(math.log(v, 100)) for v in codes)

rawDescription: Converting an array to a float, how to reverse the process?


code: df.pivot_table(index='Animal', columns='FeedType', values='Amount(kg)', aggfunc='sum')

rawDescription: Equivalent of R's tapply() in Python Pandas


rawDescription: Pandas google analytics API - how to switch account?


code:
def __add__(self, new):
    newlst = [];
    for i, j in zip(self.items, new.items):
        newlst.append(i+j)
    return Bar(newlst)

rawDescription: Add two instances of my class

description: Add two instances of my class


code: clock.tick(30) # Now your game will be capped at 30 fps

rawDescription: Setting a fixed FPS on a Python 3 game

description: Setting a fixed FPS on a Python 3 game


code: exclude .hglf

rawDescription: Is there a mercurial command which can generate a clone without largefiles?


code:
A[3,3] = NA
A.sum(axis=0)

rawDescription: Improving performance of operations on a NumPy array


code: div = soup.find('div', class_='pagination')

rawDescription: python beautiful soup get Chinese immediately after class tag

description: Python beautiful soup get Chinese immediately after class tag


code:
c = City('NYC')
cities = dict()
cities[c] = 1
cities[c]
cities[c.name]

rawDescription: Having two keys for each value in dictionary


code:
class ThingForm(models.ModelForm):
  verb = ModelChoiceField(Verb.objects.all(), empty_label=None)

  class Meta:
    model = Thing

rawDescription: Customize/remove Django select box blank option


code:
sheet.write_merge(0, 0, 0, 1, 'Long Cell')
sheet.write(1, 0, 1)
sheet.write(1, 1, 2)

rawDescription: How to write a cell with multiple columns in xlwt?

description: Write a cell with multiple columns in xlwt


code: randomSample = [(random() - 0.5, random() - 0.5) for _ in range(count)]

rawDescription: Pythonic way to write a for loop that doesn't use the loop index


code:
import re

title_regex = re.compile(r'\*{3} START OF THIS PROJECT GUTENBERG EBOOK (.*?) \*{3}')

for index, line in enumerate(finalLines):
    match = title_regex.match(line)

    if match:
        book_name = match.group(1)
        print(index, book_name)

rawDescription: Python: How to use %%% when parsing text


code:
df2 = pd.pivot_table(df, rows=['Company_code', 'Person'], cols=['Date'], aggfunc='sum')
print(df2)
#                      Earning1           Earning2
# Date                  2014-01  2014-02   2014-01  2014-02
# Company_code Person
# 1            Jonh         100      500       200      600
#              Peter        300      500       400      600
# 2            Jonh         300      NaN       400      NaN

rawDescription: Python summarize row into column (Pandas pivot table)


code:
p = argparse.ArgumentParser ()
p.add_argument ("--aligner", action="append", nargs="+")

rawDescription: Options with Options with Python argparse?


rawDescription: Get proper output from self var python

description: Get proper output from self var python


code:
def equal(expected, actual):
    msg = "'"+actual+"' != '"+expected+"'"
    assert expected == actual, msg

rawDescription: PyCharm show full diff when unittest fails for multiline string?


code:
from itertools import count

try:
    _range = xrange
except NameError:
    # Python 3
    _range = range

def incremental_window(it):
    """Produce monotonically increasing windows on an iterable.

    Only complete windows are yielded, if the last elements do not form
    a complete window they are ignored.

    incremental_window('ABCDEF') -> ['A'], ['B', 'C'], ['D', 'E', 'F']
    incremental_window('ABCDE') -> ['A'], ['B', 'C']

    """
    it = iter(it)
    return ([next(it) for _ in _range(s)] for s in count(1))

rawDescription: Python grouping elements in a list in increasing size


code:
import difflib

bart_stations = ['Lake Merritt', 'Daly City', 'Fruitvale', 'Coliseum/Oakland Airport',
                 'San Leandro']

while True:
    text = raw_input('Enter BART station: ')
    if not text: break  # Pressing Enter quits
    guess = difflib.get_close_matches(text, bart_stations, n=1, cutoff=0)[0]
    print('Closest match: {g}'.format(g = guess))

rawDescription: Searching an entire line with a python regex


code:
infile = open(input,"r")
for line in infile:
    line = doSomething(line, next(infile))

rawDescription: Getting next line in a file

description: Getting next line in a file


code:
def merge_dols(dol1, dol2):
  result = dict(dol1, **dol2)
  result.update((k, dol1[k] + dol2[k])
                for k in set(dol1).intersection(dol2))
  return result

rawDescription: Combining Dictionaries Of Lists In Python


code: table.Cell(Row =1, Column = Column_index("The Column Header") ).Range.Text

rawDescription: How to read contents of an Table in MS-Word file Using Python?

description: Read contents of an Table in MS-Word file Using Python


code: db = Database('sqlite', ':memory:', create_db=True)

rawDescription: PonyORM, SQLite performance

description: PonyORM, SQLite performance


rawDescription: How to extract html table by using Beautifulsoup

description: Extract html table by using Beautifulsoup


code: t = soup.find(class_="label", text=lambda s: "Fiscal" in s and "year" in s)

rawDescription: Use Multiple Conditions in BeautifulSoup


code:
class ThreadedTCPRequestHandler(SocketServer.StreamRequestHandler):
    def handle(self):
        print(self.server.mycustomdata)

class ThreadedTCPServer(SocketServer.ThreadingTCPServer):
    pass

server = ThreadedTCPServer((args.host, args.port), ThreadedTCPRequestHandler)
server.mycustomdata = 'foo.bar.z'
server.serve_forever()

rawDescription: Passing extra metadata to a RequestHandler using python's SocketServer and Children


code:
def foo(**kwargs):
    if 'param' in kwargs:
        param = kwargs['param']
    else:
        ...

rawDescription: Python: how to check whether optional function parameter is set


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


code:
#!/usr/bin/python3

import codecs

# Get the data from the file
with open('public.txt', 'rb') as fp:
  v = fp.read()

# The data is base64 encoded. Let's decode it.
v = codecs.decode(v,'base64')

#  The data is now a string in base-256. Let's convert it to a number
v = codecs.encode(v, 'hex')
v = int(v, 16)

# Now it is a number. I wonder what number it is:
print (v)
print (hex(v))

rawDescription: Reading from a file and assigning content to a variable in Python


code: df.reset_index().sort(columns=['A', 'C'], ascending=[True, False]).set_index(['A', 'B'])

rawDescription: Sorting a multi-index while respecting its index structure


code:
def professor(x):
    return [line for line in x if line[1] == "Professor"]

rawDescription: Trying to filter a list to bring back lines with a specific word


code:
sql = '''
    SELECT f.date, f.sell, t.minp, t.maxp, t.avgp
    FROM {t} f
    INNER JOIN (
        SELECT MIN(date) mindate, MAX(date) maxdate,
               MIN(sell) minp, MAX(sell) maxp, AVG(sell) avgp
        FROM {t}
        GROUP BY strftime('%s', date)/(15*60)
        ) t
        ON f.date = t.mindate or f.date = t.maxdate
    '''.format(t = currency)

rawDescription: Regroup time list in python from sql query


code:
specs = {}
for path, spec in paths:
    [obj, part] = path.split('.')
    specs.setdefault(obj, {})[part] = spec

rawDescription: Python: Created nested dictionary from list of paths


code:
def add_fav(request, entry_pk):
    entry = get_object_or_404(Entry, pk=entry_pk) #Will return you the entry with pk= entry_pk or 404 if does not exist
    #Now we try to check if user already have fav or not
    try:
        favorite = Favorite.objects.get(user=request.user)
    except Favorite.DoesNotExist:
        #If not we create a new favorite object
        favorite = Favorite.objects.create(user=request.user)
    #Then we add the entry to favs
    favorite.favs.add(entry)
    #And we save
    favorite.save()

rawDescription: Django ManyToManyField in action

description: Django ManyToManyField in action


code:
Thing.objects.annotate(tag_is_known=Case(
    When(tags__name__in=['foo', 'bar'], then=True),
    default=False,
    output_field=BooleanField()
))

rawDescription: Order a django queryset by ManyToManyField = Value


rawDescription: Unicode - Just print the string

description: Unicode - Just print the string


code:
result = root.xpath("//tag/*[starts-with(local-name(), 'TEXT')][1]")
assert(' '.join(e.text for e in result) == 'one')

rawDescription: lxml find tags by regex

description: Lxml find tags by regex


code:
data = serializers.serialize('json', self.get_queryset())
return HttpResponse(data, mimetype="application/json")

rawDescription: <Django object > is not JSON serializable


code:
def append_supply( s ):
    S1Vals.append(s)

rawDescription: Python 2.7: Function accessing a list

description: Python 2.7: Function accessing a list


code:
quitflag = False
quitlock = threading.Lock()

def worker():
    while True:
        with quitlock:
            if quitflag:
                return
        crunchData()

# ... somewhere in the daemon startup code ...
t = threading.Thread(target=worker)
t.start()

# ... somewhere in the daemon shutdown code ...
with quitlock:
    quitflag = True
t.join()

rawDescription: How to use Daemon that has a while loop?

description: Use Daemon that has a while loop